324_Book - Computer Systems A Programmer’s Perspective 1...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Computer Systems A Programmer’s Perspective 1 (Beta Draft) Randal E. Bryant David R. O’Hallaron November 16, 2001 1 c Copyright ­ 2001, R. E. Bryant, D. R. O’Hallaron. All rights reserved. 2 Contents Preface 1 Introduction 1.1 1.2 1.3 1.4 Information is Bits in Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Programs are Translated by Other Programs into Different Forms . . . . . . . . . . . . . . . It Pays to Understand How Compilation Systems Work . . . . . . . . . . . . . . . . . . . . Processors Read and Interpret Instructions Stored in Memory . . . . . . . . . . . . . . . . . 1.4.1 1.4.2 1.5 1.6 1.7 Hardware Organization of a System . . . . . . . . . . . . . . . . . . . . . . . . . . Running the hello Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i 1 2 3 4 5 5 8 9 Caches Matter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Storage Devices Form a Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 The Operating System Manages the Hardware . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.7.1 1.7.2 1.7.3 1.7.4 Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Virtual Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.8 1.9 Systems Communicate With Other Systems Using Networks . . . . . . . . . . . . . . . . . 16 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 I Program Structure and Execution 2 Representing and Manipulating Information 2.1 2.1.1 2.1.2 19 21 Information Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Hexadecimal Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3 4 2.1.3 2.1.4 2.1.5 2.1.6 2.1.7 2.1.8 2.1.9 2.2 CONTENTS Data Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Addressing and Byte Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Representing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Representing Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Boolean Algebras and Rings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Bit-Level Operations in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Logical Operations in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 2.1.10 Shift Operations in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Integer Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.3 2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.3.7 2.4 2.4.1 2.4.2 2.4.3 2.4.4 2.4.5 2.4.6 2.5 Integral Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Unsigned and Two’s Complement Encodings . . . . . . . . . . . . . . . . . . . . . 41 Conversions Between Signed and Unsigned . . . . . . . . . . . . . . . . . . . . . . 45 Signed vs. Unsigned in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Expanding the Bit Representation of a Number . . . . . . . . . . . . . . . . . . . . 49 Truncating Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Advice on Signed vs. Unsigned . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Unsigned Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Two’s Complement Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Two’s Complement Negation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Unsigned Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Two’s Complement Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Multiplying by Powers of Two . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Dividing by Powers of Two . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Fractional Binary Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 IEEE Floating-Point Representation . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Example Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Floating-Point Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Floating Point in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Integer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Floating Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 CONTENTS 3 Machine-Level Representation of C Programs 3.1 3.2 5 89 A Historical Perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Program Encodings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 3.2.1 3.2.2 3.2.3 Machine-Level Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 A Note on Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 3.3 3.4 Data Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Accessing Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 3.4.1 3.4.2 3.4.3 Operand Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Data Movement Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Data Movement Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Load Effective Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Unary and Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Shift Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Special Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Condition Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Accessing the Condition Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Jump Instructions and their Encodings . . . . . . . . . . . . . . . . . . . . . . . . . 114 Translating Conditional Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Stack Frame Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Transferring Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Register Usage Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Procedure Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Recursive Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 Basic Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Pointer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 3.5 Arithmetic and Logical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 3.5.1 3.5.2 3.5.3 3.5.4 3.5.5 3.6 Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 3.6.1 3.6.2 3.6.3 3.6.4 3.6.5 3.6.6 3.7 Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 3.7.1 3.7.2 3.7.3 3.7.4 3.7.5 3.8 Array Allocation and Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 3.8.1 3.8.2 6 3.8.3 3.8.4 3.8.5 3.8.6 3.9 3.9.1 3.9.2 CONTENTS Arrays and Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Nested Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Fixed Size Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Dynamically Allocated Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Heterogeneous Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 3.10 Alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 3.11 Putting it Together: Understanding Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . 162 3.12 Life in the Real World: Using the G DB Debugger . . . . . . . . . . . . . . . . . . . . . . . 165 3.13 Out-of-Bounds Memory References and Buffer Overflow . . . . . . . . . . . . . . . . . . . 167 3.14 *Floating-Point Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 3.14.1 Floating-Point Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 3.14.2 Extended-Precision Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 3.14.3 Stack Evaluation of Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 3.14.4 Floating-Point Data Movement and Conversion Operations . . . . . . . . . . . . . . 179 3.14.5 Floating-Point Arithmetic Instructions . . . . . . . . . . . . . . . . . . . . . . . . . 181 3.14.6 Using Floating Point in Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . 183 3.14.7 Testing and Comparing Floating-Point Values . . . . . . . . . . . . . . . . . . . . . 184 3.15 *Embedding Assembly Code in C Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 186 3.15.1 Basic Inline Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 3.15.2 Extended Form of asm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 3.16 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 4 Processor Architecture 5 Optimizing Program Performance 5.1 5.2 5.3 5.4 5.5 5.6 201 203 Capabilities and Limitations of Optimizing Compilers . . . . . . . . . . . . . . . . . . . . . 204 Expressing Program Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 Program Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 Eliminating Loop Inefficiencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 Reducing Procedure Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 Eliminating Unneeded Memory References . . . . . . . . . . . . . . . . . . . . . . . . . . 218 CONTENTS 5.7 7 Understanding Modern Processors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 5.7.1 5.7.2 5.7.3 Overall Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Functional Unit Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 A Closer Look at Processor Operation . . . . . . . . . . . . . . . . . . . . . . . . . 225 5.8 5.9 Reducing Loop Overhead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 Converting to Pointer Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 5.10.1 Loop Splitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 5.10.2 Register Spilling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 5.10.3 Limits to Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 5.10 Enhancing Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 5.11 Putting it Together: Summary of Results for Optimizing Combining Code . . . . . . . . . . 247 5.11.1 Floating-Point Performance Anomaly . . . . . . . . . . . . . . . . . . . . . . . . . 248 5.11.2 Changing Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 5.12 Branch Prediction and Misprediction Penalties . . . . . . . . . . . . . . . . . . . . . . . . . 249 5.13 Understanding Memory Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 5.13.1 Load Latency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 5.13.2 Store Latency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 5.14 Life in the Real World: Performance Improvement Techniques . . . . . . . . . . . . . . . . 260 5.15 Identifying and Eliminating Performance Bottlenecks . . . . . . . . . . . . . . . . . . . . . 261 5.15.1 Program Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 5.15.2 Using a Profiler to Guide Optimization . . . . . . . . . . . . . . . . . . . . . . . . 263 5.15.3 Amdahl’s Law . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 5.16 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 6 The Memory Hierarchy 6.1 6.1.1 6.1.2 6.1.3 6.2 6.2.1 6.2.2 6.2.3 275 Storage Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Random-Access Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Disk Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Storage Technology Trends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Locality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Locality of References to Program Data . . . . . . . . . . . . . . . . . . . . . . . . 295 Locality of Instruction Fetches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 Summary of Locality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 8 6.3 CONTENTS The Memory Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 6.3.1 6.3.2 6.4 6.4.1 6.4.2 6.4.3 6.4.4 6.4.5 6.4.6 6.4.7 6.5 6.6 Caching in the Memory Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Summary of Memory Hierarchy Concepts . . . . . . . . . . . . . . . . . . . . . . . 303 Generic Cache Memory Organization . . . . . . . . . . . . . . . . . . . . . . . . . 305 Direct-Mapped Caches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 Set Associative Caches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 Fully Associative Caches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Issues with Writes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 Instruction Caches and Unified Caches . . . . . . . . . . . . . . . . . . . . . . . . 319 Performance Impact of Cache Parameters . . . . . . . . . . . . . . . . . . . . . . . 320 Cache Memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 Writing Cache-friendly Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Putting it Together: The Impact of Caches on Program Performance . . . . . . . . . . . . . 327 6.6.1 6.6.2 6.6.3 The Memory Mountain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 Rearranging Loops to Increase Spatial Locality . . . . . . . . . . . . . . . . . . . . 331 Using Blocking to Increase Temporal Locality . . . . . . . . . . . . . . . . . . . . 335 6.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 II Running Programs on a System 7 Linking 7.1 7.2 7.3 7.4 7.5 7.6 347 349 Compiler Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 Static Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Object Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 Relocatable Object Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Symbols and Symbol Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 Symbol Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 7.6.1 7.6.2 7.6.3 How Linkers Resolve Multiply-Defined Global Symbols . . . . . . . . . . . . . . . 358 Linking with Static Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 How Linkers Use Static Libraries to Resolve References . . . . . . . . . . . . . . . 364 Relocation Entries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 Relocating Symbol References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 7.7 Relocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 7.7.1 7.7.2 CONTENTS 7.8 7.9 9 Executable Object Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 Loading Executable Object Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 7.10 Dynamic Linking with Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 7.11 Loading and Linking Shared Libraries from Applications . . . . . . . . . . . . . . . . . . . 376 7.12 *Position-Independent Code (PIC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 7.13 Tools for Manipulating Object Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 7.14 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382 8 Exceptional Control Flow 8.1 8.1.1 8.1.2 8.1.3 8.2 8.2.1 8.2.2 8.2.3 8.2.4 8.3 8.4 391 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 Classes of Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 Exceptions in Intel Processors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Logical Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 Private Address Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399 User and Kernel Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 Context Switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 System Calls and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 Process Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.4.6 Obtaining Process ID’s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 Creating and Terminating Processes . . . . . . . . . . . . . . . . . . . . . . . . . . 404 Reaping Child Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 Putting Processes to Sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 Loading and Running Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Using fork and execve to Run Programs . . . . . . . . . . . . . . . . . . . . . . 418 Signal Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 Sending Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 Receiving Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 Signal Handling Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429 Portable Signal Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 8.5 Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 8.5.1 8.5.2 8.5.3 8.5.4 8.5.5 8.6 Nonlocal Jumps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 10 8.7 8.8 CONTENTS Tools for Manipulating Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 449 9 Measuring Program Execution Time 9.1 9.1.1 9.1.2 9.2 9.2.1 9.2.2 9.2.3 9.3 9.4 9.3.1 9.4.1 9.4.2 9.4.3 9.5 9.6 9.7 9.8 9.9 The Flow of Time on a Computer System . . . . . . . . . . . . . . . . . . . . . . . . . . . 450 Process Scheduling and Timer Interrupts . . . . . . . . . . . . . . . . . . . . . . . 451 Time from an Application Program’s Perspective . . . . . . . . . . . . . . . . . . . 452 Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 Reading the Process Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456 Accuracy of Process Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 IA32 Cycle Counters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 The Effects of Context Switching . . . . . . . . . . . . . . . . . . . . . . . . . . . 462 Caching and Other Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 The à -Best Measurement Scheme . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 Measuring Time by Interval Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 Cycle Counters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 Measuring Program Execution Time with Cycle Counters . . . . . . . . . . . . . . . . . . . 460 Time-of-Day Measurements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 Putting it Together: An Experimental Protocol . . . . . . . . . . . . . . . . . . . . . . . . . 478 Looking into the Future . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 Life in the Real World: An Implementation of the à -Best Measurement Scheme . . . . . . 480 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 485 10 Virtual Memory 10.1 Physical and Virtual Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486 10.2 Address Spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 10.3 VM as a Tool for Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488 10.3.1 DRAM Cache Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 10.3.2 Page Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489 10.3.3 Page Hits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490 10.3.4 Page Faults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 10.3.5 Allocating Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492 10.3.6 Locality to the Rescue Again . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 CONTENTS 11 10.4 VM as a Tool for Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 10.4.1 Simplifying Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 10.4.2 Simplifying Sharing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 10.4.3 Simplifying Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 10.4.4 Simplifying Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 10.5 VM as a Tool for Memory Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 10.6 Address Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 10.6.1 Integrating Caches and VM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500 10.6.2 Speeding up Address Translation with a TLB . . . . . . . . . . . . . . . . . . . . . 500 10.6.3 Multi-level Page Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 10.6.4 Putting it Together: End-to-end Address Translation . . . . . . . . . . . . . . . . . 504 10.7 Case Study: The Pentium/Linux Memory System . . . . . . . . . . . . . . . . . . . . . . . 508 10.7.1 Pentium Address Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508 10.7.2 Linux Virtual Memory System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 10.8 Memory Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516 10.8.1 Shared Objects Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517 10.8.2 The fork Function Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519 10.8.3 The execve Function Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519 10.8.4 User-level Memory Mapping with the mmap Function . . . . . . . . . . . . . . . . 520 10.9 Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522 10.9.1 The malloc and free Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 523 10.9.2 Why Dynamic Memory Allocation? . . . . . . . . . . . . . . . . . . . . . . . . . . 524 10.9.3 Allocator Requirements and Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 10.9.4 Fragmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 10.9.5 Implementation Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529 10.9.6 Implicit Free Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529 10.9.7 Placing Allocated Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 10.9.8 Splitting Free Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 10.9.9 Getting Additional Heap Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . 532 10.9.10 Coalescing Free Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532 10.9.11 Coalescing with Boundary Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533 10.9.12 Putting it Together: Implementing a Simple Allocator . . . . . . . . . . . . . . . . . 535 10.9.13 Explicit Free Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543 12 CONTENTS 10.9.14 Segregated Free Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544 10.10Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 10.10.1 Garbage Collector Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547 10.10.2 Mark&Sweep Garbage Collectors . . . . . . . . . . . . . . . . . . . . . . . . . . . 548 10.10.3 Conservative Mark&Sweep for C Programs . . . . . . . . . . . . . . . . . . . . . . 550 10.11Common Memory-related Bugs in C Programs . . . . . . . . . . . . . . . . . . . . . . . . 551 10.11.1 Dereferencing Bad Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551 10.11.2 Reading Uninitialized Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551 10.11.3 Allowing Stack Buffer Overflows . . . . . . . . . . . . . . . . . . . . . . . . . . . 552 10.11.4 Assuming that Pointers and the Objects they Point to Are the Same Size . . . . . . . 552 10.11.5 Making Off-by-one Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553 10.11.6 Referencing a Pointer Instead of the Object it Points to . . . . . . . . . . . . . . . . 553 10.11.7 Misunderstanding Pointer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . 554 10.11.8 Referencing Non-existent Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 554 10.11.9 Referencing Data in Free Heap Blocks . . . . . . . . . . . . . . . . . . . . . . . . . 555 10.11.10 Introducing Memory Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 10.12Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556 III Interaction and Communication Between Programs 11 Concurrent Programming with Threads 561 563 11.1 Basic Thread Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563 11.2 Thread Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 11.2.1 Creating Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567 11.2.2 Terminating Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567 11.2.3 Reaping Terminated Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568 11.2.4 Detaching Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568 11.3 Shared Variables in Threaded Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570 11.3.1 Threads Memory Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570 11.3.2 Mapping Variables to Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570 11.3.3 Shared Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572 11.4 Synchronizing Threads with Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 11.4.1 Sequential Consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 CONTENTS 13 11.4.2 Progress Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576 11.4.3 Protecting Shared Variables with Semaphores . . . . . . . . . . . . . . . . . . . . . 579 11.4.4 Posix Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580 11.4.5 Signaling With Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581 11.5 Synchronizing Threads with Mutex and Condition Variables . . . . . . . . . . . . . . . . . 583 11.5.1 Mutex Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583 11.5.2 Condition Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586 11.5.3 Barrier Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 11.5.4 Timeout Waiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588 11.6 Thread-safe and Reentrant Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 11.6.1 Reentrant Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593 11.6.2 Thread-safe Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 11.7 Other Synchronization Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 11.7.1 Races . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 11.7.2 Deadlocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 11.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600 12 Network Programming 605 12.1 Client-Server Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605 12.2 Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606 12.3 The Global IP Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611 12.3.1 IP Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612 12.3.2 Internet Domain Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614 12.3.3 Internet Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618 12.4 Unix file I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 12.4.1 The read and write Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 620 12.4.2 Robust File I/O With the readn and writen Functions. . . . . . . . . . . . . . . 621 12.4.3 Robust Input of Text Lines Using the readline Function . . . . . . . . . . . . . . 623 12.4.4 The stat Function 12.4.5 The dup2 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626 12.4.6 The close Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627 12.4.7 Other Unix I/O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628 12.4.8 Unix I/O vs. Standard I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628 14 CONTENTS 12.5 The Sockets Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629 12.5.1 Socket Address Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629 12.5.2 The socket Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631 12.5.3 The connect Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631 12.5.4 The bind Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633 12.5.5 The listen Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633 12.5.6 The accept Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635 12.5.7 Example Echo Client and Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636 12.6 Concurrent Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638 12.6.1 Concurrent Servers Based on Processes . . . . . . . . . . . . . . . . . . . . . . . . 638 12.6.2 Concurrent Servers Based on Threads . . . . . . . . . . . . . . . . . . . . . . . . . 640 12.7 Web Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646 12.7.1 Web Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 12.7.2 Web Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 12.7.3 HTTP Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648 12.7.4 Serving Dynamic Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651 12.8 Putting it Together: The T INY Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . . 652 12.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662 A Error handling 665 A.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665 A.2 Error handling in Unix systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 A.3 Error-handling wrappers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 A.4 The csapp.h header file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 A.5 The csapp.c source file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675 B Solutions to Practice Problems 691 B.1 Intro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691 B.2 Representing and Manipulating Information . . . . . . . . . . . . . . . . . . . . . . . . . . 691 B.3 Machine Level Representation of C Programs . . . . . . . . . . . . . . . . . . . . . . . . . 700 B.4 Processor Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715 B.5 Optimizing Program Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715 B.6 The Memory Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717 CONTENTS 15 B.7 Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723 B.8 Exceptional Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725 B.9 Measuring Program Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 728 B.10 Virtual Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 730 B.11 Concurrent Programming with Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734 B.12 Network Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736 16 CONTENTS Preface This book is for programmers who want to improve their skills by learning about what is going on “under the hood” of a computer system. Our aim is to explain the important and enduring concepts underlying all computer systems, and to show you the concrete ways that these ideas affect the correctness, performance, and utility of your application programs. By studying this book, you will gain some insights that have immediate value to you as a programmer, and others that will prepare you for advanced courses in compilers, computer architecture, operating systems, and networking. The book owes its origins to an introductory course that we developed at Carnegie Mellon in the Fall of 1998, called 15-213: Introduction to Computer Systems. The course has been taught every semester since then, each time to about 150 students, mostly sophomores in computer science and computer engineering. It has become a prerequisite for all upper-level systems courses. The approach is concrete and hands-on. Because of this, we are able to couple the lectures with programming labs and assignments that are fun and exciting. The response from our students and faculty colleagues was so overwhelming that we decided that others might benefit from our approach. Hence the book. This is the Beta draft of the manuscript. The final hard-cover version will be available from the publisher in Summer, 2002, for adoption in the Fall, 2002 term. Assumptions About the Reader’s Background This course is based on Intel-compatible processors (called “IA32” by Intel and “x86” colloquially) running C programs on the Unix operating system. The text contains numerous programming examples that have been compiled and run under Unix. We assume that you have access to such a machine, and are able to log in and do simple things such as changing directories. Even if you don’t use Linux, much of the material applies to other systems as well. Intel-compatible processors running one of the Windows operating systems use the same instruction set, and support many of the same programming libraries. By getting a copy of the Cygwin tools (http://cygwin.com/), you can set up a Unix-like shell under Windows and have an environment very close to that provided by Unix. We also assume that you have some familiarity with C or C++. If your only prior experience is with Java, the transition will require more effort on your part, but we will help you. Java and C share similar syntax and control statements. However, there are aspects of C, particularly pointers, explicit dynamic memory allocation, and formatted I/O, that do not exist in Java. The good news is that C is a small language, and it i ii PREFACE is clearly and beautifully described in the classic “K&R” text by Brian Kernighan and Dennis Ritchie [37]. Regardless of your programming background, consider K&R an essential part of your personal library. New to C? To help readers whose background in C programming is weak (or nonexistent), we have included these special notes to highlight features that are especially important in C. We assume you are familiar with C++ or Java. End Several of the early chapters in our book explore the interactions between C programs and their machinelanguage counterparts. The machine language examples were all generated by the GNU GCC compiler running on an Intel IA32 processor. We do not assume any prior experience with hardware, machine language, or assembly-language programming. How to Read This Book Learning how computer systems work from a programmer’s perspective is great fun, mainly because it can be done so actively. Whenever you learn some new thing, you can try it out right away and see the result first hand. In fact, we believe that the only way to learn systems is to do systems, either working concrete problems, or writing and running programs on real systems. This theme pervades the entire book. When a new concept is introduced, it is followed in the text by one or more Practice Problems that you should work immediately to test your understanding. Solutions to the Practice Problems are at the back of the book. As you read, try to solve each problem on your own, and then check the solution to make sure you’re on the right track. Each chapter is followed by a set of Homework Problems of varying difficulty. Your instructor has the solutions to the Homework Problems in an Instructor’s Manual. Each Homework Problem is classified according to how much work it will be: Category 1: Simple, quick problem to try out some idea in the book. Category 2: Requires 5–15 minutes to complete, perhaps involving writing or running programs. Category 3: A sustained problem that might require hours to complete. Category 4: A laboratory assignment that might take one or two weeks to complete. Each code example in the text was formatted directly, without any manual intervention, from a C program compiled with GCC version 2.95.3, and tested on a Linux system with a 2.2.16 kernel. The programs are available from our Web page at www.cs.cmu.edu/˜ics. The file names of the larger programs are documented in horizontal bars that surround the formatted code. For example, the program iii code/intro/hello.c 1 2 3 4 5 6 #include <stdio.h> int main() { printf("hello, world\n"); } code/intro/hello.c can be found in the file hello.c in directory code/intro/. We strongly encourage you to try running the example programs on your system as you encounter them. There are various places in the book where we show you how to run programs on Unix systems: unix> ./hello hello, world unix> In all of our examples, the output is displayed in a roman font, and the input that you type is displayed in an italicized font. In this particular example, the Unix shell program prints a command-line prompt and waits for you to type something. After you type the string “./hello” and hit the return or enter key, the shell loads and runs the hello program from the current directory. The program prints the string “hello, world\n” and terminates. Afterwards, the shell prints another prompt and waits for the next command. The vast majority of our examples do not depend on any particular version of Unix, and we indicate this independence with the generic “unix>” prompt. In the rare cases where we need to make a point about a particular version of Unix such as Linux or Solaris, we include its name in the command-line prompt. Finally, some sections (denoted by a “*”) contain material that you might find interesting, but that can be skipped without any loss of continuity. Acknowledgements We are deeply indebted to many friends and colleagues for their thoughtful criticisms and encouragement. A special thanks to our 15-213 students, whose infectious energy and enthusiasm spurred us on. Nick Carter and Vinny Furia generously provided their malloc package. Chris Lee, Mathilde Pignol, and Zia Khan identified typos in early drafts. Guy Blelloch, Bruce Maggs, and Todd Mowry taught the course over multiple semesters, gave us encouragement, and helped improve the course material. Herb Derby provided early spiritual guidance and encouragement. Allan Fisher, Garth Gibson, Thomas Gross, Satya, Peter Steenkiste, and Hui Zhang encouraged us to develop the course from the start. A suggestion from Garth early on got the whole ball rolling, and this was picked up and refined with the help of a group led by Allan Fisher. Mark Stehlik and Peter Lee have been very supportive about building this material into the undergraduate curriculum. Greg Kesden provided iv PREFACE helpful feedback. Greg Ganger and Jiri Schindler graciously provided some disk drive characterizations and answered our questions on modern disks. Tom Stricker showed us the memory mountain. A special group of students, Khalil Amiri, Angela Demke Brown, Chris Colohan, Jason Crawford, Peter Dinda, Julio Lopez, Bruce Lowekamp, Jeff Pierce, Sanjay Rao, Blake Scholl, Greg Steffan, Tiankai Tu, and Kip Walker, were instrumental in helping us develop the content of the course. In particular, Chris Colohan established a fun (and funny) tone that persists to this day, and invented the legendary “binary bomb” that has proven to be a great tool for teaching machine code and debugging concepts. Chris Bauer, Alan Cox, David Daugherty, Peter Dinda, Sandhya Dwarkadis, John Greiner, Bruce Jacob, Barry Johnson, Don Heller, Bruce Lowekamp, Greg Morrisett, Brian Noble, Bobbie Othmer, Bill Pugh, Michael Scott, Mark Smotherman, Greg Steffan, and Bob Wier took time that they didn’t have to read and advise us on early drafts of the book. A very special thanks to Peter Dinda (Northwestern University), John Greiner (Rice University), Bruce Lowekamp (William & Mary), Bobbie Othmer (University of Minnesota), Michael Scott (University of Rochester), and Bob Wier (Rocky Mountain College) for class testing the Beta version. A special thanks to their students as well! Finally, we would like to thank our colleagues at Prentice Hall. Eric Frank (Editor) and Harold Stone (Consulting Editor) have been unflagging in their support and vision. Jerry Ralya (Development Editor) has provided sharp insights. Thank you all. Randy Bryant Dave O’Hallaron Pittsburgh, PA Aug 1, 2001 Chapter 1 Introduction A computer system is a collection of hardware and software components that work together to run computer programs. Specific implementations of systems change over time, but the underlying concepts do not. All systems have similar hardware and software components that perform similar functions. This book is written for programmers who want to improve at their craft by understanding how these components work and how they affect the correctness and performance of their programs. In their classic text on the C programming language [37], Kernighan and Ritchie introduce readers to C using the hello program shown in Figure 1.1. code/intro/hello.c 1 2 3 4 5 6 #include <stdio.h> int main() { printf("hello, world\n"); } code/intro/hello.c Figure 1.1: The hello program. Although hello is a very simple program, every major part of the system must work in concert in order for it to run to completion. In a sense, the goal of this book is to help you understand what happens and why, when you run hello on your system. We will begin our study of systems by tracing the lifetime of the hello program, from the time it is created by a programmer, until it runs on a system, prints its simple message, and terminates. As we follow the lifetime of the program, we will briefly introduce the key concepts, terminology, and components that come into play. Later chapters will expand on these ideas. 1 2 CHAPTER 1. INTRODUCTION 1.1 Information is Bits in Context Our hello program begins life as a source program (or source file) that the programmer creates with an editor and saves in a text file called hello.c. The source program is a sequence of bits, each with a value of 0 or 1, organized in 8-bit chunks called bytes. Each byte represents some text character in the program. Most modern systems represent text characters using the ASCII standard that represents each character with a unique byte-sized integer value. For example, Figure 1.2 shows the ASCII representation of the hello.c program. # 35 h 104 i 105 > 62 n 110 \n 10 c 99 \n 10 l 108 i 105 u 117 n 110 p 112 o 111 d 100 e <sp> 101 32 m 109 n 110 d 100 < 60 a 97 t 116 \ 92 s 115 i 105 f 102 n 110 t 116 n 110 ( 40 " 34 d 100 ( 40 " 34 ) 41 i 105 ) 41 h 104 ; 59 o 111 \n 10 e 101 \n 10 . 46 { 123 l 108 } 125 t <sp> 116 32 r 114 r 114 i 105 l 108 \n <sp> <sp> <sp> <sp> 10 32 32 32 32 l 108 o 111 , <sp> 44 32 w 119 Figure 1.2: The ASCII text representation of hello.c. The hello.c program is stored in a file as a sequence of bytes. Each byte has an integer value that corresponds to some character. For example, the first byte has the integer value 35, which corresponds to the character ’#’. The second byte has the integer value 105, which corresponds to the character ’i’, and so on. Notice that each text line is terminated by the invisible newline character ’\n’, which is represented by the integer value 10. Files such as hello.c that consist exclusively of ASCII characters are known as text files. All other files are known as binary files. The representation of hello.c illustrates a fundamental idea: All information in a system — including disk files, programs stored in memory, user data stored in memory, and data transferred across a network — is represented as a bunch of bits. The only thing that distinguishes different data objects is the context in which we view them. For example, in different contexts, the same sequence of bytes might represent an integer, floating point number, character string, or machine instruction. This idea is explored in detail in Chapter 2. Aside: The C programming language. C was developed in 1969 to 1973 by Dennis Ritchie of Bell Laboratories. The American National Standards Institute (ANSI) ratified the ANSI C standard in 1989. The standard defines the C language and a set of library functions known as the C standard library. Kernighan and Ritchie describe ANSI C in their classic book, which is known affectionately as “K&R” [37]. In Ritchie’s words [60], C is “quirky, flawed, and an enormous success.” So why the success? ¯ C was closely tied with the Unix operating system. C was developed from the beginning as the system programming language for Unix. Most of the Unix kernel, and all of its supporting tools and libraries, were written in C. As Unix became popular in universities in the late 1970s and early 1980s, many people were 1.2. PROGRAMS ARE TRANSLATED BY OTHER PROGRAMS INTO DIFFERENT FORMS exposed to C and found that they liked it. Since Unix was written almost entirely in C, it could be easily ported to new machines, which created an even wider audience for both C and Unix. C is a small, simple language. The design was controlled by a single person, rather than a committee, and the result was a clean, consistent design with little baggage. The K&R book describes the complete language and standard library, with numerous examples and exercises, in only 261 pages. The simplicity of C made it relatively easy to learn and to port to different computers. C was designed for a practical purpose. C was designed to implement the Unix operating system. Later, other people found that they could write the programs they wanted, without the language getting in the way. 3 ¯ ¯ C is the language of choice for system-level programming, and there is a huge installed based of application-level programs as well. However, it is not perfect for all programmers and all situations. C pointers are a common source of confusion and programming errors. C also lacks explicit support for useful abstractions such as classes and objects. Newer languages such as C++ and Java address these issues for application-level programs. End Aside. 1.2 Programs are Translated by Other Programs into Different Forms The hello program begins life as a high-level C program because it can be read and understand by human beings in that form. However, in order to run hello.c on the system, the individual C statements must be translated by other programs into a sequence of low-level machine-language instructions. These instructions are then packaged in a form called an executable object program, and stored as a binary disk file. Object programs are also referred to as executable object files. On a Unix system, the translation from source file to object file is performed by a compiler driver: unix> gcc -o hello hello.c Here, the GCC compiler driver reads the source file hello.c and translates it into an executable object file hello. The translation is performed in the sequence of four phases shown in Figure 1.3. The programs that perform the four phases ( preprocessor, compiler, assembler, and linker) are known collectively as the compilation system. printf.o hello.c source program (text) prehello.i processor (cpp) compiler (cc1) hello.s assembler hello.o (as) relocatable object programs (binary) linker (ld) hello modified source program (text) assembly program (text) executable object program (binary) Figure 1.3: The compilation system. ¯ Preprocessing phase. The preprocessor (cpp) modifies the original C program according to directives that begin with the # character. For example, the #include <stdio.h> command in line 1 of hello.c tells the preprocessor to read the contents of the system header file stdio.h and insert it directly into the program text. The result is another C program, typically with the .i suffix. 4 CHAPTER 1. INTRODUCTION ¯ Compilation phase. The compiler (cc1) translates the text file hello.i into the text file hello.s, which contains an assembly-language program. Each statement in an assembly-language program exactly describes one low-level machine-language instruction in a standard text form. Assembly language is useful because it provides a common output language for different compilers for different high-level languages. For example, C compilers and Fortran compilers both generate output files in the same assembly language. Assembly phase. Next, the assembler (as) translates hello.s into machine-language instructions, packages them in a form known as a relocatable object program, and stores the result in the object file hello.o. The hello.o file is a binary file whose bytes encode machine language instructions rather than characters. If we were to view hello.o with a text editor, it would appear to be gibberish. Linking phase. Notice that our hello program calls the printf function, which is part of the standard C library provided by every C compiler. The printf function resides in a separate precompiled object file called printf.o, which must somehow be merged with our hello.o program. The linker (ld) handles this merging. The result is the hello file, which is an executable object file (or simply executable) that is ready to be loaded into memory and executed by the system. Aside: The GNU project. G CC is one of many useful tools developed by the GNU (GNU’s Not Unix) project. The GNU project is a taxexempt charity started by Richard Stallman in 1984, with the ambitious goal of developing a complete Unix-like system whose source code is unencumbered by restrictions on how it can be modified or distributed. As of 2002, the GNU project has developed an environment with all the major components of a Unix operating system, except for the kernel, which was developed separately by the Linux project. The GNU environment includes the EMACS editor, GCC compiler, GDB debugger, assembler, linker, utilities for manipulating binaries, and many others. The GNU project is a remarkable achievement, and yet it is often overlooked. The modern open source movement (commonly associated with Linux) owes its intellectual origins to the GNU project’s notion of free software. Further, Linux owes much of its popularity to the GNU tools, which provide the environment for the Linux kernel. End Aside. ¯ ¯ 1.3 It Pays to Understand How Compilation Systems Work For simple programs such as hello.c, we can rely on the compilation system to produce correct and efficient machine code. However, there are some important reasons why programmers need to understand how compilation systems work: ¯ Optimizing program performance. Modern compilers are sophisticated tools that usually produce good code. As programmers, we do not need to know the inner workings of the compiler in order to write efficient code. However, in order to make good coding decisions in our C programs, we do need a basic understanding of assembly language and how the compiler translates different C statements into assembly language. For example, is a switch statement always more efficient than a sequence of if-then-else statements? Just how expensive is a function call? Is a while loop more efficient than a do loop? Are pointer references more efficient than array indexes? Why does our loop run so much faster if we sum into a local variable instead of an argument that is passed by reference? Why do two functionally equivalent loops have such different running times? 1.4. PROCESSORS READ AND INTERPRET INSTRUCTIONS STORED IN MEMORY 5 In Chapter 3, we will introduce the Intel IA32 machine language and describe how compilers translate different C constructs into that language. In Chapter 5 we will learn how to tune the performance of our C programs by making simple transformations to the C code that help the compiler do its job. And in Chapter 6 we will learn about the hierarchical nature of the memory system, how C compilers store data arrays in memory, and how our C programs can exploit this knowledge to run more efficiently. ¯ Understanding link-time errors. In our experience, some of the most perplexing programming errors are related to the operation of the linker, especially when are trying to build large software systems. For example, what does it mean when the linker reports that it cannot resolve a reference? What is the difference between a static variable and a global variable? What happens if we define two global variables in different C files with the same name? What is the difference between a static library and a dynamic library? Why does it matter what order we list libraries on the command line? And scariest of all, why do some linker-related errors not appear until run-time? We will learn the answers to these kinds of questions in Chapter 7 Avoiding security holes. For many years now, buffer overflow bugs have accounted for the majority of security holes in network and Internet servers. These bugs exist because too many programmers are ignorant of the stack discipline that compilers use to generate code for functions. We will describe the stack discipline and buffer overflow bugs in Chapter 3 as part of our study of assembly language. ¯ 1.4 Processors Read and Interpret Instructions Stored in Memory At this point, our hello.c source program has been translated by the compilation system into an executable object file called hello that is stored on disk. To run the executable on a Unix system, we type its name to an application program known as a shell: unix> ./hello hello, world unix> The shell is a command-line interpreter that prints a prompt, waits for you to type a command line, and then performs the command. If the first word of the command line does not correspond to a built-in shell command, then the shell assumes that it is the name of an executable file that it should load and run. So in this case, the shell loads and runs the hello program and then waits for it to terminate. The hello program prints its message to the screen and then terminates. The shell then prints a prompt and waits for the next input command line. 1.4.1 Hardware Organization of a System At a high level, here is what happened in the system after you typed hello to the shell. Figure 1.4 shows the hardware organization of a typical system. This particular picture is modeled after the family of Intel Pentium systems, but all systems have a similar look and feel. 6 CPU register file PC ALU system bus memory bus CHAPTER 1. INTRODUCTION Memory Interface I/O bridge main memory I/O bus USB controller mouse keyboard graphics adapter display disk disk controller Expansion slots for other devices such as network adapters. hello executable stored on disk Figure 1.4: Hardware organization of a typical system. CPU: Central Processing Unit, ALU: Arithmetic/Logic Unit, PC: Program counter, USB: Universal Serial Bus. Buses Running throughout the system is a collection of electrical conduits called buses that carry bytes of information back and forth between the components. Buses are typically designed to transfer fixed-sized chunks of bytes known as words. The number of bytes in a word (the word size) is a fundamental system parameter that varies across systems. For example, Intel Pentium systems have a word size of 4 bytes, while serverclass systems such as Intel Itaniums and Sun SPARCS have word sizes of 8 bytes. Smaller systems that are used as embedded controllers in automobiles and factories can have word sizes of 1 or 2 bytes. For simplicity, we will assume a word size of 4 bytes, and we will assume that buses transfer only one word at a time. I/O devices Input/output (I/O) devices are the system’s connection to the external world. Our example system has four I/O devices: a keyboard and mouse for user input, a display for user output, and a disk drive (or simply disk) for long-term storage of data and programs. Initially, the executable hello program resides on the disk. Each I/O device is connected to the I/O bus by either a controller or an adapter. The distinction between the two is mainly one of packaging. Controllers are chip sets in the device itself or on the system’s main printed circuit board (often called the motherboard). An adapter is a card that plugs into a slot on the motherboard. Regardless, the purpose of each is to transfer information back and forth between the I/O bus and an I/O device. Chapter 6 has more to say about how I/O devices such as disks work. And in Chapter 12, you will learn how to use the Unix I/O interface to access devices from your application programs. We focus on the especially 1.4. PROCESSORS READ AND INTERPRET INSTRUCTIONS STORED IN MEMORY 7 interesting class of devices known as networks, but the techniques generalize to other kinds of devices as well. Main memory The main memory is a temporary storage device that holds both a program and the data it manipulates while the processor is executing the program. Physically, main memory consists of a collection of Dynamic Random Access Memory (DRAM) chips. Logically, memory is organized as a linear array of bytes, each with its own unique address (array index) starting at zero. In general, each of the machine instructions that constitute a program can consist of a variable number of bytes. The sizes of data items that correspond to C program variables vary according to type. For example, on an Intel machine running Linux, data of type short requires two bytes, types int, float, and long four bytes, and type double eight bytes. Chapter 6 has more to say about how memory technologies such as DRAM chips work, and how they are combined to form main memory. Processor The central processing unit (CPU), or simply processor, is the engine that interprets (or executes) instructions stored in main memory. At its core is a word-sized storage device (or register) called the program counter (PC). At any point in time, the PC points at (contains the address of) some machine-language instruction in main memory. 1 From the time that power is applied to the system, until the time that the power is shut off, the processor blindly and repeatedly performs the same basic task, over and over and over: It reads the instruction from memory pointed at by the program counter (PC), interprets the bits in the instruction, performs some simple operation dictated by the instruction, and then updates the PC to point to the next instruction, which may or may not be contiguous in memory to the instruction that was just executed. There are only a few of these simple operations, and they revolve around main memory, the register file, and the arithmetic/logic unit (ALU). The register file is a small storage device that consists of a collection of word-sized registers, each with its own unique name. The ALU computes new data and address values. Here are some examples of the simple operations that the CPU might carry out at the request of an instruction: ¯ ¯ ¯ ¯ 1 Load: Copy a byte or a word from main memory into a register, overwriting the previous contents of the register. Store: Copy the a byte or a word from a register to a location in main memory, overwriting the previous contents of that location. Update: Copy the contents of two registers to the ALU, which adds the two words together and stores the result in a register, overwriting the previous contents of that register. I/O Read: Copy a byte or a word from an I/O device into a register. PC is also a commonly-used acronym for “Personal Computer”. However, the distinction between the two is always clear from the context. 8 CHAPTER 1. INTRODUCTION ¯ ¯ I/O Write: Copy a byte or a word from a register to an I/O device. Jump: Extract a word from the instruction itself and copy that word into the program counter (PC), overwriting the previous value of the PC. Chapter 4 has much more to say about how processors work. 1.4.2 Running the hello Program Given this simple view of a system’s hardware organization and operation, we can begin to understand what happens when we run our example program. We must omit a lot of details here that will be filled in later, but for now we will be content with the big picture. Initially, the shell program is executing its instructions, waiting for us to type a command. As we type the characters hello at the keyboard, the shell program reads each one into a register, and then stores it in memory, as shown in Figure 1.5. CPU register file PC ALU system bus memory bus main "hello" memory Memory Interface I/O bridge I/O bus USB controller mouse keyboard graphics adapter display disk disk controller Expansion slots for other devices such as network adapters. user types "hello" Figure 1.5: Reading the hello command from the keyboard. When we hit the enter key on the keyboard, the shell knows that we have finished typing the command. The shell then loads the executable hello file by executing a sequence of instructions that copies the code and data in the hello object file from disk to main memory. The data include the string of characters ”hello, world\n” that will eventually be printed out. Using a technique known as direct memory access (DMA) (discussed in Chapter 6), the data travels directly from disk to main memory, without passing through the processor. This step is shown in Figure 1.6. Once the code and data in the hello object file are loaded into memory, the processor begins executing the machine-language instructions in the hello program’s main routine. These instruction copy the bytes 1.5. CACHES MATTER CPU register file PC ALU system bus memory bus 9 Memory Interface I/O bridge "hello,world\n" main memory hello code I/O bus USB controller mouse keyboard graphics adapter display disk disk controller Expansion slots for other devices such as network adapters. hello executable stored on disk Figure 1.6: Loading the executable from disk into main memory. in the ”hello, world\n” string from memory to the register file, and from there to the display device, where they are displayed on the screen. This step is shown in Figure 1.7. 1.5 Caches Matter An important lesson from this simple example is that a system spends a lot time moving information from one place to another. The machine instructions in the hello program are originally stored on disk. When the program is loaded, they are copied to main memory. When the processor runs the programs, they are copied from main memory into the processor. Similarly, the data string ”hello,world\n”, originally on disk, is copied to main memory, and then copied from main memory to the display device. From a programmer’s perspective, much of this copying is overhead that slows down the “real work” of the program. Thus, a major goal for system designers is make these copy operations run as fast as possible. Because of physical laws, larger storage devices are slower than smaller storage devices. And faster devices are more expensive to build than their slower counterparts. For example, the disk drive on a typical system might be 100 times larger than the main memory, but it might take the processor 10,000,000 times longer to read a word from disk than from memory. Similarly, a typical register file stores only a few hundred of bytes of information, as opposed to millions of bytes in the main memory. However, the processor can read data from the register file almost 100 times faster than from memory. Even more troublesome, as semiconductor technology progresses over the years, this processor-memory gap continues to increase. It is easier and cheaper to make processors run faster than it is to make main memory run faster. To deal with the processor-memory gap, system designers include smaller faster storage devices called caches that serve as temporary staging areas for information that the processor is likely to need in the near 10 CPU register file PC ALU system bus memory bus CHAPTER 1. INTRODUCTION Memory Interface I/O bridge main "hello,world\n" memory hello code I/O bus USB controller mouse keyboard graphics adapter display disk controller Expansion slots for other devices such as network adapters. "hello,world\n" disk hello executable stored on disk Figure 1.7: Writing the output string from memory to the display. future. Figure 1.8 shows the caches in a typical system. An L1 cache on the processor chip holds tens of CPU chip register file L1 cache cache bus ALU system bus memory bridge memory bus main memory (DRAM) L2 cache memory interface Figure 1.8: Caches. thousands of bytes and can be accessed nearly as fast as the register file. A larger L2 cache with hundreds of thousands to millions of bytes is connected to the processor by a special bus. It might take 5 times longer for the process to access the L2 cache than the L1 cache, but this is still 5 to 10 times faster than accessing the main memory. The L1 and L2 caches are implemented with a hardware technology known as Static Random Access Memory (SRAM). One of the most important lessons in this book is that application programmers who are aware of caches can exploit them to improve the performance of their programs by an order of magnitude. We will learn more about these important devices and how to exploit them in Chapter 6. 1.6 Storage Devices Form a Hierarchy This notion of inserting a smaller, faster storage device (e.g. an SRAM cache) between the processor and a larger slower device (e.g., main memory) turns out to be a general idea. In fact, the storage devices in 1.7. THE OPERATING SYSTEM MANAGES THE HARDWARE 11 every computer system are organized as the memory hierarchy shown in Figure 1.9. As we move from the L0: registers L1: Larger, slower, and cheaper storage devices L2: on-chip L1 cache (SRAM) off-chip L2 cache (SRAM) main memory (DRAM) CPU registers hold words retrieved from cache memory. L1 cache holds cache lines retrieved from memory. L2 cache holds cache lines retrieved from memory. Main memory holds disk blocks retrieved from local disks. Local disks hold files retrieved from disks on remote network servers. L3: L4: local secondary storage (local disks) L5: remote secondary storage (distributed file systems, Web servers) Figure 1.9: The memory hierarchy. top of the hierarchy to the bottom, the devices become slower, larger, and less costly per byte. The register file occupies the top level in the hierarchy, which is known as level 0 or L0. The L1 cache occupies level 1 (hence the term L1). The L2 cache occupies level 2. Main memory occupies level 3, and so on. The main idea of a memory hierarchy is that storage at one level serves as a cache for storage at the next lower level. Thus, the register file is a cache for the L1 cache, which is a cache for the L2 cache, which is a cache for the main memory, which is a cache for the disk. On some networked system with distributed file systems, the local disk serves as a cache for data stored on the disks of other systems. Just as programmers can exploit knowledge of the L1 and L2 caches to improve performance, programmers can exploit their understanding of the entire memory hierarchy. Chapter 6 will have much more to say about this. 1.7 The Operating System Manages the Hardware Back to our hello example. When the shell loaded and ran the hello program, and when the hello program printed its message, neither program accessed the keyboard, display, disk, or main memory directly. Rather, they relied on the services provided by the operating system. We can think of the operating system as a layer of software interposed between the application program and the hardware, as shown in Figure 1.10. All attempts by an application program to manipulate the hardware must go through the operating system. The operating system has two primary purposes: (1) To protect the hardware from misuse by runaway applications, and (2) To provide applications with simple and uniform mechanisms for manipulating complicated and often wildly different low-level hardware devices. The operating system achieves both goals 12 CHAPTER 1. INTRODUCTION application programs operating system processor main memory I/O devices software hardware Figure 1.10: Layered view of a computer system. via the fundamental abstractions shown in Figure 1.11: processes, virtual memory, and files. As this figure processes virtual memory files processor main memory I/O devices Figure 1.11: Abstractions provided by an operating system. suggests, files are abstractions for I/O devices. Virtual memory is an abstraction for both the main memory and disk I/O devices. And processes are abstractions for the processor, main memory, and I/O devices. We will discuss each in turn. Aside: Unix and Posix. The 1960s was an era of huge, complex operating systems, such as IBM’s OS/360 and Honeywell’s Multics systems. While OS/360 was one of the most successful software projects in history, Multics dragged on for years and never achieved wide-scale use. Bell Laboratories was an original partner in the Multics project, but dropped out in 1969 because of concern over the complexity of the project and the lack of progress. In reaction to their unpleasant Multics experience, a group of Bell Labs researchers — Ken Thompson, Dennis Ritchie, Doug McIlroy, and Joe Ossanna — began work in 1969 on a simpler operating system for a DEC PDP-7 computer, written entirely in machine language. Many of the ideas in the new system, such as the hierarchical file system and the notion of a shell as a user-level process, were borrowed from Multics, but implemented in a smaller, simpler package. In 1970, Brian Kernighan dubbed the new system “Unix” as a pun on the complexity of “Multics.” The kernel was rewritten in C in 1973, and Unix was announced to the outside world in 1974 [61]. Because Bell Labs made the source code available to schools with generous terms, Unix developed a large following at universities. The most influential work was done at the University of California at Berkeley in the late 1970s and early 1980s, with Berkeley researchers adding virtual memory and the Internet protocols in a series of releases called Unix 4.xBSD (Berkeley Software Distribution). Concurrently, Bell Labs was releasing their own versions, which become known as System V Unix. Versions from other vendors, such as the Sun Microsystems Solaris system, were derived from these original BSD and System V versions. Trouble arose in the mid 1980s as Unix vendors tried to differentiate themselves by adding new and often incompatible features. To combat this trend, IEEE (Institute for Electrical and Electronics Engineers) sponsored an effort to standardize Unix, later dubbed “Posix” by Richard Stallman. The result was a family of standards, known as the Posix standards, that cover such issues as the C language interface for Unix system calls, shell programs and utilities, threads, and network programming. As more systems comply more fully with the Posix standards, the differences between Unix version are gradually disappearing. End Aside. 1.7. THE OPERATING SYSTEM MANAGES THE HARDWARE 13 1.7.1 Processes When a program such as hello runs on a modern system, the operating system provides the illusion that the program is the only one running on the system. The program appears to have exclusive use of both the processor, main memory, and I/O devices. The processor appears to execute the instructions in the program, one after the other, without interruption. And the code and data of the program appear to be the only objects in the system’s memory. These illusions are provided by the notion of a process, one of the most important and successful ideas in computer science. A process is the operating system’s abstraction for a running program. Multiple processes can run concurrently on the same system, and each process appears to have exclusive use of the hardware. By concurrently, we mean that the instructions of one process are interleaved with the instructions of another process. The operating system performs this interleaving with a mechanism known as context switching. The operating system keeps track of all the state information that the process needs in order to run. This state, which is known as the context, includes information such as the current values of the PC, the register file, and the contents of main memory. At any point in time, exactly one process is running on the system. When the operating system decides to transfer control from the current process to a some new process, it performs a context switch by saving the context of the current process, restoring the context of the new process, and then passing control to the new process. The new process picks up exactly where it left off. Figure 1.12 shows the basic idea for our example hello scenario. shell process hello process application code OS code application code OS code application code Time context switch context switch Figure 1.12: Process context switching. There are two concurrent processes in our example scenario: the shell process and the hello process. Initially, the shell process is running alone, waiting for input on the command line. When we ask it to run the hello program, the shell carries out our request by invoking a special function known as a system call that pass control to the operating system. The operating system saves the shell’s context, creates a new hello process and its context, and then passes control to the new hello process. After hello terminates, the operating system restores the context of the shell process and passes control back to it, where it waits for the next command line input. Implementing the process abstraction requires close cooperation between both the low-level hardware and the operating system software. We will explore how this works, and how applications can create and control their own processes, in Chapter 8. One of the implications of the process abstraction is that by interleaving different processes, it distorts 14 CHAPTER 1. INTRODUCTION the notion of time, making it difficult for programmers to obtain accurate and repeatable measurements of running time. Chapter 9 discusses the various notions of time in a modern system and describes techniques for obtaining accurate measurements. 1.7.2 Threads Although we normally think of a process as having a single control flow, in modern system a process can actually consist of multiple execution units, called threads, each running in the context of the process and sharing the same code and global data. Threads are an increasingly important programming model because of the requirement for concurrency in network servers, because it is easier to share data between multiple threads than between multiple processes, and because threads are typically more efficient than processes. We will learn the basic concepts of threaded programs in Chapter 11, and we will learn how to build concurrent network servers with threads in Chapter 12. 1.7.3 Virtual Memory Virtual memory is an abstraction that provides each process with the illusion that it has exclusive use of the main memory. Each process has the same uniform view of memory, which is known as its virtual address space. The virtual address space for Linux processes is shown in Figure 1.13 (Other Unix systems use a similar layout). In Linux, the topmost 1/4 of the address space is reserved for code and data in the operating system that is common to all processes. The bottommost 3/4 of the address space holds the code and data defined by the user’s process. Note that addresses in the figure increase from bottom to the top. The virtual address space seen by each process consists of a number of well-defined areas, each with a specific purpose. We will learn more about these areas later in the book, but it will be helpful to look briefly at each, starting with the lowest addresses and working our way up: ¯ ¯ ¯ ¯ Program code and data. Code begins at the same fixed address, followed by data locations that correspond to global C variables. The code and data areas are initialized directly from the contents of an executable object file, in our case the hello executable. We will learn more about this part of the address space when we study linking and loading in Chapter 7. Heap. The code and data areas are followed immediately by the run-time heap. Unlike the code and data areas, which are fixed in size once the process begins running, the heap expands and contracts dynamically at runtime as a result of calls to C standard library routines such as malloc and free. We will study heaps in detail when we learn about managing virtual memory in Chapter 10. Shared libraries. Near the middle of the address space is an area that holds the code and data for shared libraries such as the C standard library and the math library. The notion of a shared library is a powerful, but somewhat difficult concept. We will learn how they work when we study dynamic linking in Chapter 7. Stack. At the top of the user’s virtual address space is the user stack that the compiler uses to implement function calls. Like the heap, the user stack expands and contracts dynamically during the 1.7. THE OPERATING SYSTEM MANAGES THE HARDWARE memory invisible to user code 15 0xffffffff 0xc0000000 kernel virtual memory user stack (created at runtime) 0x40000000 memory mapped region for shared libraries printf() function run-time heap (created at runtime by malloc) read/write data read-only code and data 0x08048000 0 loaded from the hello executable file unused Figure 1.13: Linux process virtual address space. execution of the program. In particular, each time we call a function, the stack grows. Each time we return from a function, it contracts. We will learn how the compiler uses the stack in Chapter 3. ¯ Kernel virtual memory. The kernel is the part of the operating system that is always resident in memory. The top 1/4 of the address space is reserved for the kernel. Application programs are not allowed to read or write the contents of this area or to directly call functions defined in the kernel code. For virtual memory to work, a sophisticated interaction is required between the hardware and the operating system software, including a hardware translation of every address generated by the processor. The basic idea is to store the contents of a process’s virtual memory on disk, and then use the main memory as a cache for the disk. Chapter 10 explains how this works and why it is so important to the operation of modern systems. 1.7.4 Files A Unix file is a sequence of bytes, nothing more and nothing less. Every I/O device, including disks, keyboards, displays, and even networks, is modeled as a file. All input and output in the system is performed by reading and writing files, using a set of operating system functions known as system calls. This simple and elegant notion of a file is nonetheless very powerful because it provides applications with a uniform view of all of the varied I/O devices that might be contained in the system. For example, application programmers who manipulate the contents of a disk file are blissfully unaware of the specific disk technology. Further, the same program will run on different systems that use different disk technologies. 16 CHAPTER 1. INTRODUCTION Aside: The Linux project. In August, 1991, a Finnish graduate student named Linus Torvalds made a modest posting announcing a new Unix-like operating system kernel: From: [email protected] (Linus Benedict Torvalds) Newsgroups: comp.os.minix Subject: What would you like to see most in minix? Summary: small poll for my new operating system Date: 25 Aug 91 20:57:08 GMT Hello everybody out there using minix I’m doing a (free) operating system (just a hobby, won’t be big and professional like gnu) for 386(486) AT clones. This has been brewing since April, and is starting to get ready. I’d like any feedback on things people like/dislike in minix, as my OS resembles it somewhat (same physical layout of the file-system (due to practical reasons) among other things). I’ve currently ported bash(1.08) and gcc(1.40), and things seem to work. This implies that I’ll get something practical within a few months, and I’d like to know what features most people would want. Any suggestions are welcome, but I won’t promise I’ll implement them :-) Linus ([email protected]) The rest, as they say, is history. Linux has evolved into a technical and cultural phenomenon. By combining forces with the GNU project, the Linux project has developed a complete, Posix-compliant version of the Unix operating system, including the kernel and all of the supporting infrastructure. Linux is available on a wide array of computers, from hand-held devices to mainframe computers. And it has renewed interest in the idea of open source software pioneered by the GNU project in the 1980s. We believe that a number of factors have contributed to the popularity of GNU/Linux systems: ¯ ¯ Linux is relatively small. With about one million ( ) lines of source code, the Linux kernel is significantly smaller than comparable commercial operating systems. We recently saw a version of Linux running on a wristwatch! Linux is robust. The code development model for Linux is unique, and has resulted in a surprisingly robust system. The model consists of (1) a large set of programmers distributed around the world who update their local copies of the kernel source code, and (2) a system integrator (Linus) who decides which of these updates will become part of the official release. The model works because quality control is maintained by a talented programmer who understands everything about the system. It also results in quicker bug fixes because the pool of distributed programmers is so large. Linux is portable. Since Linux and the GNU tools are written in C, Linux can be ported to new systems without extensive code modifications. Linux is open-source. Linux is open source, which means that it can be down-loaded, modified, repackaged, and redistributed without restriction, gratis or for a fee, as long as the new sources are included with the distribution. This is different from other Unix versions, which are encumbered with software licenses that restrict software redistributions that might add value and make the system easier to use and install. ½¼ ¯ ¯ End Aside. 1.8 Systems Communicate With Other Systems Using Networks Up to this point in our tour of systems, we have treated a system as an isolated collection of hardware and software. In practice, modern systems are often linked to other systems by networks. From the point of 1.8. SYSTEMS COMMUNICATE WITH OTHER SYSTEMS USING NETWORKS 17 view of an individual system, the network can be viewed as just another I/O device, as shown in Figure 1.14. When the system copies a sequence of bytes from main memory to the network adapter, the data flows across CPU chip register file PC ALU system bus memory bus main memory Expansion slots I/O bus USB controller mouse keyboard graphics adapter monitor disk network disk controller network adapter memory interface I/O bridge Figure 1.14: A network is another I/O device. the network to another machine, instead of say, to a local disk drive. Similarly, the system can read data sent from other machines and copy this data to its main memory. With the advent of global networks such as the Internet, copying information from one machine to another has become one of the most important uses of computer systems. For example, applications such as email, instant messaging, the World Wide Web, FTP, and telnet are all based on the ability to copy information over a network. Returning to our hello example, we could use the familiar telnet application to run hello on a remote machine. Suppose we use a telnet client running on our local machine to connect to a telnet server on a remote machine. After we log in to the remote machine and run a shell, the remote shell is waiting to receive an input command. From this point, running the hello program remotely involves the five basic steps shown in Figure 1.15. 1. user types "hello" at the keyboard 2. client sends "hello" string to telnet server 3. server sends "hello" string to the shell, which runs the hello program, and sends the output to the telnet server local telnet client 5. client prints "hello, world\n" string on display 4. telnet server sends "hello, world\n" string to client remote telnet server Figure 1.15: Using telnet to run hello remotely over a network. After we type the ”hello” string to the telnet client and hit the enter key, the client sends the string to 18 CHAPTER 1. INTRODUCTION the telnet server. After the telnet server receives the string from the network, it passes it along to the remote shell program. Next, the remote shell runs the hello program, and passes the output line back to the telnet server. Finally, the telnet server forwards the output string across the network to the telnet client, which prints the output string on our local terminal. This type of exchange between clients and servers is typical of all network applications. In Chapter 12 we will learn how to build network applications, and apply this knowledge to build a simple Web server. 1.9 Summary This concludes our initial whirlwind tour of systems. An important idea to take away from this discussion is that a system is more than just hardware. It is a collection of intertwined hardware and software components that must work cooperate in order to achieve the ultimate goal of running application programs. The rest of this book will expand on this theme. Bibliographic Notes Ritchie has written interesting first-hand accounts of the early days of C and Unix [59, 60]. Ritchie and Thompson presented the first published account of Unix [61]. Silberschatz and Gavin [66] provide a comprehensive history of the different flavors of Unix. The GNU (www.gnu.org) and Linux (www.linux.org) Web pages have loads of current and historical information. Unfortunately, the Posix standards are not available online. They must be ordered for a fee from IEEE (standards.ieee.org). Part I Program Structure and Execution 19 Chapter 2 Representing and Manipulating Information Modern computers store and process information represented as two-valued signals. These lowly binary digits, or bits, form the basis of the digital revolution. The familiar decimal, or base-10, representation has been in use for over 1000 years, having been developed in India, improved by Arab mathematicians in the 12th century, and brought to the West in the 13th century by the Italian mathematician Leonardo Pisano, better known as Fibonacci. Using decimal notation is natural for ten-fingered humans, but binary values work better when building machines that store and process information. Two-valued signals can readily be represented, stored, and transmitted, for example, as the presence or absence of a hole in a punched card, as a high or low voltage on a wire, or as a magnetic domain oriented clockwise or counterclockwise. The electronic circuitry for storing and performing computations on two-valued signals is very simple and reliable, enabling manufacturers to integrate millions of such circuits on a single silicon chip. In isolation, a single bit is not very useful. When we group bits together and apply some interpretation that gives meaning to the different possible bit patterns, however, we can represent the elements of any finite set. For example, using a binary number system, we can use groups of bits to encode nonnegative numbers. By using a standard character code, we can encode the letters and symbols in a document. We cover both of these encodings in this chapter, as well as encodings to represent negative numbers and to approximate real numbers. We consider the three most important encodings of numbers. Unsigned encodings are based on traditional binary notation, representing numbers greater than or equal to 0. Two’s complement encodings are the most common way to represent signed integers, that is, numbers that may be either positive or negative. Floatingpoint encodings are a base-two version of scientific notation for representing real numbers. Computers implement arithmetic operations such as addition and multiplication, with these different representations similar to the corresponding operations on integers and real numbers. Computer representations use a limited number of bits to encode a number, and hence some operations can overflow when the results are too large to be represented. This can lead to some surprising results. For example, on most of today’s computers, computing the expression 200 * 300 * 400 * 500 21 22 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION yields 884,901,888. This runs counter to the properties of integer arithmetic—computing the product of a set of positive numbers has yielded a negative result. On the other hand, integer computer arithmetic satisfies many of the familiar properties of true integer arithmetic. For example, multiplication is associative and commutative, so that computing all of the following C expressions yields 884,901,888: (500 ((500 ((200 400 * 400) * (300 * 200) * 400) * 300) * 200 * 500) * 300) * 400 * (200 * (300 * 500)) The computer might not generate the expected result, but at least it is consistent! Floating point arithmetic has altogether different mathematical properties. The product of a set of positive numbers will always be positive, although overflow will yield the special value ·½. On the other hand, floating point arithmetic is not associative due to the finite precision of the representation. For example, the C expression (3.14+1e20)-1e20 will evaluate to 0.0 on most machines, while 3.14+(1e201e20) will evaluate to 3.14. By studying the actual number representations, we can understand the ranges of values that can be represented and the properties of the different arithmetic operations. This understanding is critical to writing programs that work correctly over the full range of numeric values and that are portable across different combinations of machine, operating system, and compiler. Our treatment of this material is very mathematical. We start with the basic definitions of the encodings and then derive such properties as the range of representable numbers, their bit-level representations, and the properties of the arithmetic operations. We believe it is important to examine this material from such an abstract viewpoint, because programmers need to have a solid understanding of how computer arithmetic relates to the more familiar integer and real arithmetic. Although it may appear intimidating, the mathematical treatment requires just an understanding of basic algebra. We recommend working the practice problems as a way to solidify the connection between the formal treatment and some real-life examples. We derive several ways to perform arithmetic operations by directly manipulating the bit-level representations of numbers. Understanding these techniques will be important for understanding the machine-level code generated when compiling arithmetic expressions. The C++ programming language is built upon C, using the exact same numeric representations and operations. Everything said in this chapter about C also holds for C++. The Java language definition, on the other hand, created a new set of standards for numeric representations and operations. Whereas the C standard is designed to allow a wide range of implementations, the Java standard is quite specific on the formats and encodings of data. We highlight the representations and operations supported by Java at several places in the chapter. 2.1 Information Storage Rather than accessing individual bits in a memory, most computers use blocks of eight bits, or bytes as the smallest addressable unit of memory. A machine-level program views memory as a very large array of 2.1. INFORMATION STORAGE Hex digit Decimal Value Binary Value Hex digit Decimal Value Binary Value 0 0 0000 8 8 1000 1 1 0001 9 9 1001 2 2 0010 A 10 1010 3 3 0011 B 11 1011 4 4 0100 C 12 1100 5 5 0101 D 13 1101 6 6 0110 E 14 1110 7 7 0111 F 15 1111 23 Figure 2.1: Hexadecimal Notation Each Hex digit encodes one of 16 values. bytes, referred to as virtual memory. Every byte of memory is identified by a unique number, known as its address, and the set of all possible addresses is known as the virtual address space. As indicated by its name, this virtual address space is just a conceptual image presented to the machine-level program. The actual implementation (presented in Chapter 10) uses a combination of random-access memory (RAM), disk storage, special hardware, and operating system software to provide the program with what appears to be a monolithic byte array. One task of a compiler and the run-time system is to subdivide this memory space into more manageable units to store the different program objects, that is, program data, instructions, and control information. Various mechanisms are used to allocate and manage the storage for different parts of the program. This management is all performed within the virtual address space. For example, the value of a pointer in C— whether it points to an integer, a structure, or some other program unit—is the virtual address of the first byte of some block of storage. The C compiler also associates type information with each pointer, so that it can generate different machine-level code to access the value stored at the location designated by the pointer depending on the type of that value. Although the C compiler maintains this type information, the actual machine-level program it generates has no information about data types. It simply treats each program object as a block of bytes, and the program itself as a sequence of bytes. New to C? Pointers are a central feature of C. They provide the mechanism for referencing elements of data structures, including arrays. Just like a variable, a pointer has two aspects: its value and its type. The value indicates the location of some object, while its type indicates what kind (e.g., integer or floating-point number) of object is stored at that location. End 2.1.1 Hexadecimal Notation A single byte consists of eight bits. In binary notation, its value ranges from ¼¼¼¼¼¼¼¼¾ to ½½½½½½½½¾ . When viewed as a decimal integer, its value ranges from ¼½¼ to ¾ ½¼ . Neither notation is very convenient for describing bit patterns. Binary notation is too verbose, while with decimal notation, it is tedious to convert to and from bit patterns. Instead, we write bit patterns as base-16, or hexadecimal numbers. Hexadecimal (or simply “Hex”) uses digits ‘0’ through ‘9’, along with characters ‘A’ through ‘F’ to represent 16 possible values. Figure 2.1 shows the decimal and binary values associated with the 16 hexadecimal digits. Written in hexadecimal, the value of a single byte can range from 00½ to FF½ . In C, numeric constants starting with 0x or 0X are interpreted as being in hexadecimal. The characters 24 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION ‘A’ through ‘F’ may be written in either upper or lower case. For example, we could write the number FA1D37B½ as 0xFA1D37B, as 0xfa1d37b, or even mixing upper and lower case, e.g., 0xFa1D37b. We will use the C notation for representing hexadecimal values in this book. A common task in working with machine-level programs is to manually convert between decimal, binary, and hexadecimal representations of bit patterns. A starting point is to be able to convert, in both directions, between a single hexadecimal digit and a four-bit binary pattern. This can always be done by referring to a chart such as that shown in Figure 2.1. When doing the conversion manually, one simple trick is to memorize the decimal equivalents of hex digits A, C, and F. The hex values B, D, and E can be translated to decimal by computing their values relative to the first three. Practice Problem 2.1: Fill in the missing entries in the following figure, giving the decimal, binary, and hexadecimal values of different byte patterns. Decimal 0 55 136 243 Binary 00000000 Hexadecimal 00 01010010 10101100 11100111 A7 3E BC Aside: Converting between decimal and hexadecimal. For converting larger values between decimal and hexadecimal, it is best to let a computer or calculator do the work. For example, the following script in the Perl language converts a list of numbers from decimal to hexadecimal: bin/d2h 1 2 3 4 5 #!/usr/local/bin/perl # Convert list of decimal numbers into hex for ($i = 0; $i < @ARGV; $i++) printf("%d = 0x%x\n", $ARGV[$i], $ARGV[$i]); bin/d2h Once this file has been set to be executable, the command: unix> ./d2h 100 500 751 will yield output: 2.1. INFORMATION STORAGE 100 = 0x64 500 = 0x1f4 751 = 0x2ef Similarly, the following script converts from hexadecimal to decimal: 25 bin/h2d 1 2 3 4 5 6 #!/usr/local/bin/perl # Convert list of decimal numbers into hex for ($i = 0; $i < @ARGV; $i++) $val = hex($ARGV[$i]); printf("0x%x = %d\n", $val, $val); bin/h2d End Aside. 2.1.2 Words Every computer has a word size, indicating the nominal size of integer and pointer data. Since a virtual address is encoded by such a word, the most important system parameter determined by the word size is the maximum size of the virtual address space. That is, for a machine with an Ò-bit word size, the virtual addresses can range from ¼ to ¾Ò ½, giving the program access to at most ¾Ò bytes. Most computers today have a 32-bit word size. This limits the virtual address space to 4 gigabytes (written 4 GB), that is, just over ¢ ½¼ bytes. Although this is ample space for most applications, we have reached the point where many large-scale scientific and database applications require larger amounts of storage. Consequently, high-end machines with 64-bit word sizes are becoming increasingly commonplace as storage costs decrease. 2.1.3 Data Sizes Computers and compilers support multiple data formats using different ways to encode data, such as integers and floating point, as well as different lengths. For example, many machines have instructions for manipulating single bytes, as well as integers represented as two, four, and eight-byte quantities. They also support floating-point numbers represented as four and eight-byte quantities. The C language supports multiple data formats for both integer and floating-point data. The C data type char represents a single byte. Although the name “char” derives from the fact that it is used to store a single character in a text string, it can also be used to store integer values. The C data type int can also be prefixed by the qualifiers long and short, providing integer representations of various sizes. Figure 2.2 shows the number of bytes allocated for various C data types. The exact number depends on both the machine and the compiler. We show two representative cases: a typical 32-bit machine, and the Compaq Alpha architecture, a 64-bit machine targeting high end applications. Most 32-bit machines use the allocations indicated as “typical.” Observe that “short” integers have two-byte allocations, while an unqualified int is 4 bytes. A “long” integer uses the full word size of the machine. 26 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION C Declaration char short int int long int char * float double Typical 32-bit 1 2 4 4 4 4 8 Compaq Alpha 1 2 4 8 8 4 8 Figure 2.2: Sizes (in Bytes) of C Numeric Data Types. The number of bytes allocated varies with machine and compiler. Figure 2.2 also shows that a pointer (e.g., a variable declared as being of type “char *”) uses the full word size of the machine. Most machines also support two different floating-point formats: single precision, declared in C as float, and double precision, declared in C as double. These formats use four and eight bytes, respectively. New to C? For any data type Ì , the declaration Ì *p; indicates that p is a pointer variable, pointing to an object of type Ì . For example char *p; is the declaration of a pointer to an object of type char. End Programmers should strive to make their programs portable across different machines and compilers. One aspect of portability is to make the program insensitive to the exact sizes of the different data types. The C standard sets lower bounds on the numeric ranges of the different data types, as will be covered later, but there are no upper bounds. Since 32-bit machines have been the standard for the last 20 years, many programs have been written assuming the allocations listed as “typical 32-bit” in Figure 2.2. Given the increasing prominence of 64-bit machines in the near future, many hidden word size dependencies will show up as bugs in migrating these programs to new machines. For example, many programmers assume that a program object declared as type int can be used to store a pointer. This works fine for most 32-bit machines but leads to problems on an Alpha. 2.1.4 Addressing and Byte Ordering For program objects that span multiple bytes, we must establish two conventions: what will be the address of the object, and how will we order the bytes in memory. In virtually all machines, a multibyte object is stored as a contiguous sequence of bytes, with the address of the object given by the smallest address of the 2.1. INFORMATION STORAGE 27 bytes used. For example, suppose a variable x of type int has address 0x100, that is, the value of the address expression &x is 0x100. Then the four bytes of x would be stored in memory locations 0x100, 0x101, 0x102, and 0x103. For ordering the bytes representing an object, there are two common conventions. Consider a Û-bit integer having a bit representation ÜÛ ½ ÜÛ ¾ ܽ ܼ , where ÜÛ ½ is the most significant bit, and ܼ is the least. Assuming Û is a multiple of eight, these bits can be grouped as bytes, with the most significant byte having bits ÜÛ ½ ÜÛ ¾ ÜÛ , the least significant byte having bits Ü Ü Ü¼ , and the other bytes having bits from the middle. Some machines choose to store the object in memory ordered from least significant byte to most, while other machines store them from most to least. The former convention—where the least significant byte comes first—is referred to as little endian. This convention is followed by most machines from the former Digital Equipment Corporation (now part of Compaq Corporation), as well as by Intel. The latter convention—where the most significant byte comes first—is referred to as big endian. This convention is followed by most machines from IBM, Motorola, and Sun Microsystems. Note that we said “most.” The conventions do not split precisely along corporate boundaries. For example, personal computers manufactured by IBM use Intel-compatible processors and hence are little endian. Many microprocessor chips, including Alpha and the PowerPC by Motorola can be run in either mode, with the byte ordering convention determined when the chip is powered up. Continuing our earlier example, suppose the variable x of type int and at address 0x100 has a hexadecimal value of 0x01234567. The ordering of the bytes within the address range 0x100 through 0x103 depends on the type of machine: Big endian ¡¡¡ Little endian 0x100 0x101 0x102 0x103 01 23 45 67 ¡¡¡ ¡¡¡ ¡¡¡ 0x100 0x101 0x102 0x103 67 45 23 01 Note that in the word 0x01234567 the high-order byte has hexadecimal value 0x01, while the low-order byte has value 0x67. People get surprisingly emotional about which byte ordering is the proper one. In fact, the terms “little endian” and “big endian” come from the book Gulliver’s Travels by Jonathan Swift, where two warring factions could not agree by which end a soft-boiled egg should be opened—the little end or the big. Just like the egg issue, there is no technological reason to choose one byte ordering convention over the other, and hence the arguments degenerate into bickering about sociopolitical issues. As long as one of the conventions is selected and adhered to consistently, the choice is arbitrary. Aside: Origin of “Endian.” Here is how Jonathan Swift, writing in 1726, described the history of the controversy between big and little endians: . . . the two great empires of Lilliput and Blefuscu. Which two mighty powers have, as I was going to tell you, been engaged in a most obstinate war for six-and-thirty moons past. It began upon the following occasion. It is allowed on all hands, that the primitive way of breaking eggs, before we eat 28 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION them, was upon the larger end; but his present majesty’s grandfather, while he was a boy, going to eat an egg, and breaking it according to the ancient practice, happened to cut one of his fingers. Whereupon the emperor his father published an edict, commanding all his subjects, upon great penalties, to break the smaller end of their eggs. The people so highly resented this law, that our histories tell us, there have been six rebellions raised on that account; wherein one emperor lost his life, and another his crown. These civil commotions were constantly fomented by the monarchs of Blefuscu; and when they were quelled, the exiles always fled for refuge to that empire. It is computed that eleven thousand persons have at several times suffered death, rather than submit to break their eggs at the smaller end. Many hundred large volumes have been published upon this controversy: but the books of the Big-endians have been long forbidden, and the whole party rendered incapable by law of holding employments. In his day, Swift was satirizing the continued conflicts between England (Lilliput) and France (Blefuscu). Danny Cohen, an early pioneer in networking protocols, first applied these terms to refer to byte ordering [16], and the terminology has been widely adopted. End Aside. For most application programmers, the byte orderings used by their machines are totally invisible. Programs compiled for either class of machine give identical results. At times, however, byte ordering becomes an issue. The first is when binary data is communicated over a network between different machines. A common problem is for data produced by a little-endian machine to be sent to a big-endian machine, or vice-versa, leading to the bytes within the words being in reverse order for the receiving program. To avoid such problems, code written for networking applications must follow established conventions for byte ordering to make sure the sending machine converts its internal representation to the network standard, while the receiving machine converts the network standard to its internal representation. We will see examples of these conversions in Chapter 12. A second case is when programs are written that circumvent the normal type system. In the C language, this can be done using a cast to allow an object to be referenced according to a different data type from which it was created. Such coding tricks are strongly discouraged for most application programming, but they can be quite useful and even necessary for system-level programming. Figure 2.3 shows C code that uses casting to access and print the byte representations of different program objects. We use typedef to define data type byte_pointer as a pointer to an object of type “unsigned char.” Such a byte pointer references a sequence of bytes where each byte is considered to be a nonnegative integer. The first routine show_bytes is given the address of a sequence of bytes, indicated by a byte pointer, and a byte count. It prints the individual bytes in hexadecimal. The C formatting directive “%.2x” indicates that an integer should be printed in hexadecimal with at least two digits. New to C? The typedef declaration in C provides a way of giving a name to a data type. This can be a great help in improving code readability, since deeply nested type declarations can be difficult to decipher. The syntax for typedef is exactly like that of declaring a variable, except that it uses a type name rather than a variable name. Thus, the declaration of byte_pointer in Figure 2.3 has the same form as would the declaration of a variable to type “unsigned char.” For example, the declaration: typedef int *int_pointer; int_pointer ip; defines type “int_pointer” to be a pointer to an int, and declares a variable ip of this type. Alternatively, we could declare this variable directly as: 2.1. INFORMATION STORAGE 29 code/data/show-bytes.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 #include <stdio.h> typedef unsigned char *byte_pointer; void show_bytes(byte_pointer start, int len) { int i; for (i = 0; i < len; i++) printf(" %.2x", start[i]); printf("\n"); } void show_int(int x) { show_bytes((byte_pointer) &x, sizeof(int)); } void show_float(float x) { show_bytes((byte_pointer) &x, sizeof(float)); } void show_pointer(void *x) { show_bytes((byte_pointer) &x, sizeof(void *)); } code/data/show-bytes.c Figure 2.3: Code to Print the Byte Representation of Program Objects. This code uses casting to circumvent the type system. Similar functions are easily defined for other data types. 30 int *ip; End CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION New to C? The printf function (along with its cousins fprintf and sprintf) provides a way to print information with considerable control over the formatting details. The first argument is a format string, while any remaining arguments are values to be printed. Within the formatting string, each character sequence starting with ‘%’ indicates how to format the next argument. Typical examples include ‘%d’ to print a decimal integer and ‘%f’ to print a floating-point number, and ‘%c’ to print a character having the character code given by the argument. End New to C? In function show_bytes (Figure 2.3) we see the close connection between pointers and arrays, as will be discussed in detail in Section 3.8. We see that this function has an argument start of type byte_pointer (which has been defined to be a pointer to unsigned char,) but we see the array reference start[i] on line 9. In C, we can use reference a pointer with array notation, and we can reference arrays with pointer notation. In this example, the reference start[i] indicates that we want to read the byte that is i positions beyond the location pointed to by start. End Procedures show_int, show_float, and show_pointer demonstrate how to use procedure show_bytes to print the byte representations of C program objects of type int, float, and void *, respectively. Observe that they simply pass show_bytes a pointer &x to their argument x, casting the pointer to be of type “unsigned char *.” This cast indicates to the compiler that the program should consider the pointer to be to a sequence of bytes rather than to an object of the original data type. This pointer will then be to the lowest byte address used by the object. New to C? In lines 15, 20, and 24 of Figure 2.3 we see uses of two operations that are unique to C and C++. The C “address of” operator & creates a pointer. On all three lines, the expression &x creates a pointer to the location holding variable x. The type of this pointer depends on the type of x, and hence these three pointers are of type int *, float *, and void **, respectively. (Data type void * is a special kind of pointer with no associated type information.) The cast operator converts from one data type to another. Thus, the cast (byte_pointer) &x indicates that whatever type the pointer &x had before, it now is a pointer to data of type unsigned char. End These procedures use the C operator sizeof to determine the number of bytes used by the object. In general, the expression sizeof(Ì ) returns the number of bytes required to store an object of type Ì . Using sizeof, rather than a fixed value, is one step toward writing code that is portable across different machine types. We ran the code shown in Figure 2.4 on several different machines, giving the results shown in Figure 2.5. The machines used were: Linux: Intel Pentium II running Linux. NT: Sun: Intel Pentium II running Windows-NT. Sun Microsystems UltraSPARC running Solaris. Alpha: Compaq Alpha 21164 running Tru64 Unix. 2.1. INFORMATION STORAGE 31 code/data/show-bytes.c 1 2 3 4 5 6 7 8 9 void test_show_bytes(int val) { int ival = val; float fval = (float) ival; int *pval = &ival; show_int(ival); show_float(fval); show_pointer(pval); } code/data/show-bytes.c Figure 2.4: Byte Representation Examples. This code prints the byte representations of sample data objects. Machine Linux NT Sun Alpha Linux NT Sun Alpha Linux NT Sun Alpha Value 12,345 12,345 12,345 12,345 ½¾ ¿ ½¾ ¿ ½¾ ¿ ½¾ ¿ ¼ ¼ ¼ ¼ &ival &ival &ival &ival Type int int int int float float float float int * int * int * int * 39 39 00 39 00 00 46 00 3c 1c ef 80 30 30 00 30 e4 e4 40 e4 fa ff ff fc Bytes (Hex) 00 00 00 00 30 39 00 00 40 46 40 46 e4 00 40 46 ff bf 44 02 fc e4 ff 1f 01 00 00 00 Figure 2.5: Byte Representations of Different Data Values. Results for int and float are identical, except for byte ordering. Pointer values are machine-dependent. 32 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Our sample integer argument 12,345 has hexadecimal representation 0x00003039. For the int data, we get identical results for all machines, except for the byte ordering. In particular, we can see that the least significant byte value of 0x39 is printed first for Linux, NT, and Alpha, indicating little-endian machines, and last for Sun, indicating a big-endian machine. Similarly, the bytes of the float data are identical, except for the byte ordering. On the other hand, the pointer values are completely different. The different machine/operating system configurations use different conventions for storage allocation. One feature to note is that the Linux and Sun machines use four-byte addresses, while the Alpha uses eight-byte addresses. Observe that although the floating point and the integer data both encode the numeric value 12,345, they have very different byte patterns: 0x00003039 for the integer, and 0x4640E400 for floating point. In general, these two formats use different encoding schemes. If we expand these hexadecimal patterns into binary and shift them appropriately, we find a sequence of 13 matching bits, indicated below by a sequence of asterisks: 0 0 0 0 3 0 3 9 00000000000000000011000000111001 ************* 4 6 4 0 E 4 0 0 01000110010000001110010000000000 This is not coincidental. We will return to this example when we study floating-point formats. Practice Problem 2.2: Consider the following 3 calls to show_bytes: int val = 0x12345678; byte_pointer valp = (byte_pointer) &val; show_bytes(valp, 1); /* A. */ show_bytes(valp, 2); /* B. */ show_bytes(valp, 3); /* C. */ Indicate below the values that would be printed by each call on a little-endian machine and on a bigendian machine. A. Little endian: B. Little endian: C. Little endian: Big endian: Big endian: Big endian: Practice Problem 2.3: Using show_int and show_float, we determine that the integer 3490593 has hexadecimal representation 0x00354321, while the floating-point number ¿ ¼ ¿ ¼ has hexadecimal representation representation 0x4A550C84. A. Write the binary representations of these two hexadecimal values. B. Shift these two strings relative to one another to maximize the number of matching bits. C. How many bits match? What parts of the strings do not match? 2.1. INFORMATION STORAGE 33 2.1.5 Representing Strings A string in C is encoded by an array of characters terminated by the null (having value 0) character. Each character is represented by some standard encoding, with the most common being the ASCII character code. Thus, if we run our routine show_bytes with arguments "12345" and 6 (to include the terminating character), we get the result 31 32 33 34 35 00. Observe that the ASCII code for decimal digit Ü happens to be 0x3Ü, and that the terminating byte has the hex representation 0x00. This same result would be obtained on any system using ASCII as its character code, independent of the byte ordering and word size conventions. As a consequence, text data is more platform-independent than binary data. Aside: Generating an ASCII table. You can display a table showing the ASCII character code by executing the command man ascii. End Aside. Practice Problem 2.4: What would be printed as a result of the following call to show_bytes: char *s = "ABCDEF"; show_bytes(s, strlen(s)); Note that letters ‘A’ through ‘Z’ have ASCII codes 0x41 through 0x5A. Aside: The Unicode character set. The ASCII character set is suitable for encoding English language documents, but it does not have much in the way of special characters, such as the French ‘c.’ It is wholly unsuited for encoding documents in languages such as ¸ Greek, Russian, and Chinese. Recently, the 16-bit Unicode character set has been adopted to support documents in all languages. This doubling of the character set representation enables a very large number of different characters to be represented. The Java programming language uses Unicode when representing character strings. Program libraries are also available for C that provide Unicode versions of the standard string functions such as strlen and strcpy. End Aside. 2.1.6 Representing Code Consider the following C function: 1 2 3 4 int sum(int x, int y) { return x + y; } When compiled on our sample machines, we generate machine code having the following byte representations: Linux: 55 89 e5 8b 45 0c 03 45 08 89 ec 5d c3 NT: 55 89 e5 8b 45 0c 03 45 08 89 ec 5d c3 34 ˜ 0 1 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION & 1 0 0 1 0 0 0 1 0 1 | 0 1 0 0 1 1 1 1 ˆ 0 1 0 0 1 1 1 0 Figure 2.6: Operations of Boolean Algebra. Binary values 1 and 0 encode logic values T RUE and FALSE, while operations ˜, &, |, and ˆ encode logical operations N OT, A ND, O R, and E XCLUSIVE -O R, respectively. Sun: 81 C3 E0 08 90 02 00 09 Alpha: 00 00 30 42 01 80 FA 6B Here we find that the instruction codings are different, except for the NT and Linux machines. Different machine types use different and incompatible instructions and encodings. The NT and Linux machines both have Intel processors and hence support the same machine-level instructions. In general, however, the structure of an executable NT program differs from a Linux program, and hence the machines are not fully binary compatible. Binary code is seldom portable across different combinations of machine and operating system. A fundamental concept of computer systems is that a program, from the perspective of the machine, is simply sequences of bytes. The machine has no information about the original source program, except perhaps some auxiliary tables maintained to aid in debugging. We will see this more clearly when we study machine-level programming in Chapter 3. 2.1.7 Boolean Algebras and Rings Since binary values are at the core of how computers encode, store, and manipulate information, a rich body of mathematical knowledge has evolved around the study of the values 0 and 1. This started with the work of George Boole around 1850, and hence goes under the heading of Boolean algebra. Boole observed that by encoding logic values T RUE and FALSE as binary values 1 and 0, he could formulate an algebra that captures the properties of propositional logic. There is an infinite number of different Boolean algebras, where the simplest is defined over the two-element set ¼ ½ . Figure 2.6 defines several operations in this Boolean algebra. Our symbols for representing these operations are chosen to match those used by the C bit-level operations, as will be discussed later. The Boolean operation ˜ corresponds to the logical operation N OT, denoted in propositional logic as . That is, we say that È is true when È is not true, and vice-versa. Correspondingly, ˜Ô equals 1 when Ô equals 0, and vice-versa. Boolean operation & corresponds to the logical operation A ND, denoted in propositional logic as . We say that È É holds when both È and É are true. Correspondingly, Ô & Õ equals 1 only when Ô ½ and Õ ½. Boolean operation | corresponds to the logical operation O R, denoted in propositional logic as . We say that È É holds when either È or É are true. Correspondingly, Ô | Õ equals 1 when either Ô ½ or Õ ½. Boolean operation ˆ corresponds to the logical operation E XCLUSIVE -O R , denoted in propositional logic as ¨. We say that È ¨ É holds when either È or É are true, but not both. 2.1. INFORMATION STORAGE Shared Properties Property Commutativity Associativity Distributivity Identities Annihilator Cancellation Unique to Rings Inverse Unique to Boolean Algebras Distributivity Complement Idempotency Absorption DeMorgan’s laws ´ · 35 Integer Ring ¢ ¢ ´ ´ · ¢ ´ ·¼ ½ ¼ µ ¼ · ¢¢ µ · µ µ· ¢ ¢¢ ´ µ·´ ·´ · µ ¢ µ µ ¢ ¢ ´ · Boolean Algebra | | & & ´ | µ| |´ | µ ´ & µ& &´ & µ &´ | µ ´ & µ|´ & |¼ &½ &¼ ¼ ˜´˜ µ µ — — — — — — — — — ¼ — |´ & µ ´ | µ &´ | µ |˜ ½ &˜ ¼ & | |´ & µ &´ | µ ˜´ & µ ˜ | ˜ ˜´ | µ ˜ & ˜ Figure 2.7: Comparison of Integer Ring and Boolean Algebra. The two mathematical structures share many properties, but there are key differences, particularly between and ˜. Correspondingly, Ô ˆ Õ equals 1 when either Ô ½ and Õ ¼ , or Ô ¼ and Õ ½ . Claude Shannon, who would later found the field of information theory, first made the connection between Boolean algebra and digital logic. In his 1937 master’s thesis, he showed that Boolean algebra could be applied to the design and analysis of networks of electromechanical relays. Although computer technology has advanced considerably since that time, Boolean algebra still plays a central role in digital systems design and analysis. There are many parallels between integer arithmetic and Boolean algebra, as well as several important differences. In particular, the set of integers, denoted , forms a mathematical structure known as a ring, denoted · ¢ ¼ ½ , with addition serving as the sum operation, multiplication as the product operation, negation as the additive inverse, and elements 0 and 1 serving as the additive and multiplicative identities. The Boolean algebra ¼ ½ | & ˜ ¼ ½ has similar properties. Figure 2.7 highlights properties of these two structures, showing the properties that are common to both and those that are unique to one or the other. One important difference is that ˜ is not an inverse for under |. 36 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Aside: What good is abstract algebra? Abstract algebra involves identifying and analyzing the common properties of mathematical operations in different domains. Typically, an algebra is characterized by a set of elements, some of its key operations, and some important elements. As an example, modular arithmetic also forms a ring. For modulus Ò, the algebra is denoted , with components defined as follows: Ò Ò Ò Ò · ¢ ¼½ · Ò Ò Ò ¢ Ò ¼½ ½ · ÑÓ ¢ ÑÓ ¼ ¼ ¼ Ò Ò Ò Ò Even though modular arithmetic yields different results from integer arithmetic, it has many of the same mathematical properties. Other well-known rings include rational and real numbers. End Aside. If we replace the O R operation of Boolean algebra by the E XCLUSIVE -O R operation, and the complement operation ˜ with the identity operation Á —where Á ´ µ for all —we have a structure ¼ ½ ˆ & Á ¼ ½ . This structure is no longer a Boolean algebra—in fact it’s a ring. It can be seen to be a particularly simple form of the ring consisting of all integers ¼ ½ Ò ½ with both addition and multiplication performed modulo Ò. In this case, we have Ò ¾. That is, the Boolean A ND and E XCLUSIVE -O R operations correspond to multiplication and addition modulo 2, respectively. One curious property of this algebra is that every element is its own additive inverse: ˆ Á ´ µ ˆ ¼. Aside: Who, besides mathematicians, care about Boolean rings? Every time you enjoy the clarity of music recorded on a CD or the quality of video recorded on a DVD, you are taking advantage of Boolean rings. These technologies rely on error-correcting codes to reliably retrieve the bits from a disk even when dirt and scratches are present. The mathematical basis for these error-correcting codes is a linear algebra based on Boolean rings. End Aside. We can extend the four Boolean operations to also operate on bit vectors, i.e., strings of 0s and 1s of some fixed length Û. We define the operations over bit vectors according their applications to the matching elements of the arguments. For example, we define Û ½ Û ¾ ¼ & Û ½ Û ¾ ¼ to be Û ½ & & Û ¾ & ¼ , and similarly for operations ˜, |, and ˆ. Letting ¼ ½ Û denote the set Û ½ Û ¾ ¼ of all strings of 0s and 1s having length Û, and Û denote the string consisting of Û repetitions of symbol , then one can see that the resulting algebras: ¼ ½ Û | & ˜ ¼Û ½Û and ¼ ½ Û ˆ & Á ¼Û ½Û form Boolean algebras and rings, respectively. Each value of Û defines a different Boolean algebra and a different Boolean ring. Aside: Are Boolean rings the same as modular arithmetic? The two-element Boolean ring ˆ&Á is identical to the ring of integers modulo two ¾ ¾ ¾ ¾ The generalization to bit vectors of length Û, however, however, yields a very different ring from modular arithmetic. End Aside. ¼½ ¼½ · ¢ ¼½. Practice Problem 2.5: Fill in the following table showing the results of evaluating Boolean operations on bit vectors. 2.1. INFORMATION STORAGE Operation Result ¼½½¼½¼¼½ ¼½¼½¼½¼½ 37 ˜ ˜ & | ˆ One useful application of bit vectors is to represent finite sets. For example, we can denote any subset ¼½ Û ½ as a bit vector Û ½ ½ if and only if ¾ . For example, ½ ¼ , where (recalling that we write Û ½ on the left and ¼ on the right), we have ¼½½¼½¼¼½ representing the set ¼¿ , and ¼½¼½¼½¼½ representing the set ¼¾ . Under this interpretation, Boolean operations | and & correspond to set union and intersection, respectively, and ˜ corresponds to set complement. For example, the operation & yields bit vector ¼½¼¼¼¼¼½ , while ¼ . In fact, for any set Ë , the structure È ´Ë µ Ë forms a Boolean algebra, where È ´Ë µ denotes the set of all subsets of Ë , and denotes the set complement operator. That is, for any set , its complement is the set ¾ Ë ¾ . The ability to represent and manipulate finite sets using bit vector operations is a practical outcome of a deep mathematical principle. 2.1.8 Bit-Level Operations in C One useful feature of C is that it supports bit-wise Boolean operations. In fact, the symbols we have used for the Boolean operations are exactly those used by C: | for O R, & for A ND, ˜ for N OT, and ˆ for E XCLUSIVE O R. These can be applied to any “integral” data type, that is, one declared as type char or int, with or without qualifiers such as short, long, or unsigned. Here are some example expression evaluations: C Expression ˜0x41 ˜0x00 0x69 & 0x55 0x69 | 0x55 Binary Expression ˜ ¼½¼¼¼¼¼½ ˜ ¼¼¼¼¼¼¼¼ ¼½½¼½¼¼½ & ¼½¼½¼½¼½ ¼½½¼½¼¼½ | ¼½¼½¼½¼½ Binary Result ½¼½½½½½¼ ½½½½½½½½ ¼½¼¼¼¼¼½ ¼½½½½½¼½ C Result 0xBE 0xFF 0x41 0x7D As our examples show, the best way to determine the effect of a bit-level expression is to expand the hexadecimal arguments to their binary representations, perform the operations in binary, and then convert back to hexadecimal. Practice Problem 2.6: To show how the ring properties of ˆ can be useful, consider the following program: 1 2 3 void inplace_swap(int *x, int *y) { *x = *x ˆ *y; /* Step 1 */ 38 4 5 6 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION *y = *x ˆ *y; *x = *x ˆ *y; } /* Step 2 */ /* Step 3 */ As the name implies, we claim that the effect of this procedure is to swap the values stored at the locations denoted by pointer variables x and y. Note that unlike the usual technique for swapping two values, we do not need a third location to temporarily store one value while we are moving the other. There is no performance advantage to this way of swapping. It is merely an intellectual amusement. Starting with values and in the locations pointed to by x and y, respectively, fill in the following table giving the values stored at the two locations after each step of the procedure. Use the ring properties to show that the desired effect is achieved. Recall that every element is its own additive inverse, that is, ˆ ¼. Step Initially Step 1 Step 2 Step 3 *x *y One common use of bit-level operations is to implement masking operations, where a mask is a bit pattern that indicates a selected set of bits within a word. As an example, the mask 0xFF (having 1s for the least significant eight bits) indicates the low-order byte of a word. The bit-level operation x & 0xFF yields a value consisting of the least significant byte of x, but with all other bytes set to 0. For example, with x 0x89ABCDEF, the expression would yield 0x000000EF. The expression ˜0 will yield a mask of all 1s, regardless of the word size of the machine. Although the same mask can be written 0xFFFFFFFF for a 32-bit machine, such code is not as portable. Practice Problem 2.7: Write C expressions for the following values, with the results for x size shown in square brackets: 0x98FDECBA and a 32-bit word A. The least significant byte of x, with all other bits set to 1 [0xFFFFFFBA]. B. The complement of the least significant byte of x, with all other bytes left unchanged [0x98FDEC45]. C. All but the least significant byte of x, with the least significant byte set to 0 [0x98FDEC00]. Although our examples assume a 32-bit word size, your code should work for any word size Û . Practice Problem 2.8: The Digital Equipment VAX computer was a very popular machine from the late 1970s until the late 1980s. Rather than instructions for Boolean operations A ND and O R, it had instructions bis (bit set) and bic (bit clear). Both instructions take a data word x and a mask word m. They generate a result z consisting of the bits of x modified according to the bits of m. With bis, the modification involves setting z to 1 at each bit position where m is 1. With bic, the modification involves setting z to 0 at each bit position where m is 1. We would like to write C functions bis and bic to compute the effect of these two instructions. Fill in the missing expressions in the code below using the bit-level operations of C. 2.1. INFORMATION STORAGE /* Bit Set */ int bis(int x, int m) { /* Write an expression in C that computes the effect of bit set */ int result = ___________; return result; } /* Bit Clear */ int bic(int x, int m) { /* Write an expression in C that computes the effect of bit set */ int result = ___________; return result; } 39 2.1.9 Logical Operations in C C also provides a set of logical operators ||, &&, and !, which correspond to the O R, A ND, and N OT operations of propositional logic. These can easily be confused with the bit-level operations, but their function is quite different. The logical operations treat any nonzero argument as representing T RUE and argument 0 as representing FALSE. They return either 1 or 0 indicating a result of either T RUE or FALSE, respectively. Here are some example expression evaluations: Expression !0x41 !0x00 !!0x41 0x69 && 0x55 0x69 || 0x55 Result 0x00 0x01 0x01 0x01 0x01 Observe that a bit-wise operation will have behavior matching that of its logical counterpart only in the special case where the arguments are restricted to be either 0 or 1. A second important distinction between the logical operators && and ||, versus their bit-level counterparts & and | is that the logical operators do not evaluate their second argument if the result of the expression can be determined by evaluating the first argument. Thus, for example, the expression a && 5/a will never cause a division by zero, and the expression p && *p++ will never cause the dereferencing of a null pointer. Practice Problem 2.9: Suppose that x and y have byte values 0x66 and 0x93, respectively. Fill in the following table indicating the byte values of the different C expressions 40 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Expression x&y x|y ˜x | ˜y x & !y Value Expression x && y x || y !x || !y x && ˜y Value Practice Problem 2.10: Using only bit-level and logical operations, write a C expression that is equivalent to x == y. That is, it will return 1 when x and y are equal and 0 otherwise. 2.1.10 Shift Operations in C C also provides a set of shift operations for shifting bit patterns to the left and to the right. For an operand x having bit representation ÜÒ ½ ÜÒ ¾ ܼ , the C expression x << k yields a value with bit representation ÜÒ ½ ÜÒ ¾ ܼ ¼ ¼ . That is, x is shifted bits to the left, dropping off the most significant bits and filling the left end with 0s. The shift amount should be a value between ¼ and Ò ½. Shift operations group from left to right, so x << j << k is equivalent to (x << j) << k. Be careful about operator precedence: 1<<5 - 1 is evaluated as 1 << (5-1), not as (1<<5) - 1. There is a corresponding right shift operation x >> k, but it has a slightly subtle behavior. Generally, machines support two forms of right shift: logical and arithmetic. A logical right shift fills the left end with 0s, giving a result ¼ ¼ ÜÒ ½ ÜÒ ¾ Ü . An arithmetic right shift fills the left end with repetitions of the most significant bit, giving a result ÜÒ ½ ÜÒ ½ ÜÒ ½ ÜÒ ¾ Ü . This convention might seem peculiar, but as we will see it is useful for operating on signed integer data. The C standard does not precisely define which type of right shift should be used. For unsigned data (i.e., integral objects declared with the qualifier unsigned), right shifts must be logical. For signed data (the default), either arithmetic or logical shifts may be used. This unfortunately means that any code assuming one form or the other will potentially encounter portability problems. In practice, however, almost all compiler/machine combinations use arithmetic right shifts for signed data, and many programmers assume this to be the case. Practice Problem 2.11: Fill in the table below showing the effects of the different shift operations on single-byte quantities. Write each answer as two hexadecimal digits. x 0xF0 0x0F 0xCC 0x55 x << 3 x >> 2 (Logical) x >> 2 (Arithmetic) 2.2. INTEGER REPRESENTATIONS C Declaration char unsigned char short [int] unsigned short [int] int unsigned [int] long [int] unsigned long [int] Guaranteed Minimum Maximum 127 127 0 255 32,767 32,767 0 63,535 32,767 32,767 0 65,535 2,147,483,647 2,147,483,647 0 4,294,967,295 Typical 32-bit Minimum Maximum 128 127 0 255 32,768 32,767 0 63,535 2,147,483,648 2,147,483,647 0 4,294,967,295 2,147,483,648 ¾ ½ ¿ 0 4,294,967,295 41 Figure 2.8: C Integral Data types. Text in square brackets is optional. 2.2 Integer Representations In this section we describe two different ways bits can be used to encode integers—one that can only represent nonnegative numbers, and one that can represent negative, zero, and positive numbers. We will see later that they are strongly related both in their mathematical properties and their machine-level implementations. We also investigate the effect of expanding or shrinking an encoded integer to fit a representation with a different length. 2.2.1 Integral Data Types C supports a variety of integral data types—ones that represent a finite range of integers. These are shown in Figure 2.8. Each type has a size designator: char, short, int, and long, as well as an indication of whether the represented number is nonnegative (declared as unsigned), or possibly negative (the default). The typical allocations for these different sizes were given in Figure 2.2. As indicated in Figure 2.8, these different sizes allow different ranges of values to be represented. The C standard defines a minimum range of values each data type must be able to represent. As shown in the figure, a typical 32-bit machine uses a 32-bit representation for data types int and unsigned, even though the C standard allows 16-bit representations. As described in Figure 2.2, the Compaq Alpha uses a 64-bit word to represent long integers, giving an upper limit of over ½ ¢ ½¼½ for unsigned values, and a range of over ¦ ¾¾ ¢ ½¼½ for signed values. New to C? Both C and C++ support signed (the default) and unsigned numbers. Java supports only signed numbers. End 2.2.2 Unsigned and Two’s Complement Encodings Assume we have an integer data type of Û bits. We write a bit vector as either Ü, to denote the entire vector, or as ÜÛ ½ ÜÛ ¾ ܼ to denote the individual bits within the vector. Treating Ü as a number written in binary notation, we obtain the unsigned interpretation of Ü. We express this interpretation as a function 42 Quantity CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Word Size Û 32 64 0xFFFFFFFF 0xFFFFFFFFFFFFFFFF 4,294,967,295 18,446,744,073,709,551,615 0x7FFFFFFF 0x7FFFFFFFFFFFFFFF 2,147,483,647 9,223,372,036,854,775,807 0x80000000 0x8000000000000000 2,147,483,648 9,223,372,036,854,775,808 0xFFFFFFFF 0xFFFFFFFFFFFFFFFF 0x00000000 0x0000000000000000 ÍÅ Ü Û ÌÅ Ü Û ÌÅ Ò Û 1 ¼ 8 0xFF 255 0x7F 127 0x80 128 0xFF 0x00 16 0xFFFF 65,535 0x7FFF 32,767 0x8000 32,768 0xFFFF 0x0000 Figure 2.9: “Interesting” Numbers. Both numeric values and hexadecimal representations are shown. ¾Í Û (for “binary to unsigned,” length Û): ¾Í Û ´Üµ Û ½ ¼ ܾ (2.1) (In this equation, the notation “ ” means that the left hand side is defined to equal to the right hand side). That is, function ¾Í Û maps length Û strings of 0s and 1s to nonnegative integers. The least value is given by bit vector ¼¼ ¡ ¡ ¡ ¼ having integer value ¼, and the greatest value is given by bit vector ½½ ¡ ¡ ¡ ½ ÈÛ ½ Û having integer value ÍÅ Ü Û ¾ ½. Thus, the function ¾Í Û can be defined as a mapping ¼¾ Û Û ¾Í Û ¼ ½ ¼ ¾ ½ . Note that ¾Í Û is a bijection—it associates a unique value to each bit vector of length Û, and conversely each integer between 0 and ¾Û ½ has a unique binary representation as a bit vector of length Û. For many applications, we wish to represent negative values as well. The most common computer representation of signed numbers is known as two’s complement form. This is defined by interpreting the most significant bit of the word to have negative weight. We express this interpretation as a function ¾Ì Û (for “binary to two’s complement” length Û): ¾Ì Û ´Üµ Ü Û ½¾ Û ½ · Û ¾ ¼ ܾ (2.2) The most significant bit is also called the sign bit. When set to 1, the represented value is negative, and when set to 0 the value is nonnegative. The least representable value is given by bit vector ½¼ ¡ ¡ ¡ ¼ (i.e., set the bit with negative weight but clear all others) having integer value ÌÅ Ò Û ¾Û ½. The greatest ÈÛ ¾ Û ½ value is given by bit vector ¼½ ¡ ¡ ¡ ½ , having integer value ÌÅ Ü Û ¾ ½. Again, one ¼¾ Û Û ½ Û ½ can see that ¾Ì Û is a bijection ¾Ì Û ¼ ½ ¾ ¾ ½ , associating a unique integer in the representable range for each bit pattern. Figure 2.9 shows the bit patterns and numeric values for several “interesting” numbers for different word sizes. The first three give the ranges of representable integers. A few points are worth highlighting. First, the two’s complement range is asymmetric: ÌÅ Ò Û ÌÅ Ü Û · ½, that is, there is no positive counterpart to ÌÅ Ò Û . As we shall see, this leads to some peculiar properties of two’s complement arithmetic and can 2.2. INTEGER REPRESENTATIONS 43 be the source of subtle program bugs. Second, the maximum unsigned value is nearly twice the maximum two’s complement value: ÍÅ Ü Û ¾ÌÅ Ü Û · ½. This follows from the fact that two’s complement notation reserves half of the bit patterns to represent negative values. The other cases are the constants ½ and ¼. Note that ½ has the same bit representation as ÍÅ Ü Û —a string of all 1s. Numeric value ¼ is represented as a string of all 0s in both representations. The C standard does not require signed integers to be represented in two’s complement form, but nearly all machines do so. To keep code portable, one should not assume any particular range of representable values or how they are represented, beyond the ranges indicated in Figure 2.2. The C library file <limits.h> defines a set of constants delimiting the ranges of the different integer data types for the particular machine on which the compiler is running. For example, it defines constants INT_MAX, INT_MIN, and UINT_MAX describing the ranges of signed and unsigned integers. For a two’s complement machine where data type int has Û bits, these constants correspond to the values of ÌÅ Ü Û , ÌÅ Ò Û , and ÍÅ Ü Û . Practice Problem 2.12: Assuming Û , we can assign a numeric value to each possible hex digit, assuming either an unsigned or two’s complement interpretation. Fill in the following table according to these interpretations Ü (Hex) 0 3 8 A F ¾Í ´Üµ ¾Ì ´Ü µ Aside: Alternative represenations of signed numbers There are two other standard representations for signed numbers: One’s Complement: Same as two’s complement, except that the most significant bit has weight Û ½ rather than : ¾ ´¾ ½ ½µ Û ¾Ç Û Sign-Magnitude: ´µ Ü ½ ´¾ ½ ½µ · ÜÛ Û Û ¾ Ü ¼ ¾ The most significant bit is a sign bit that determines whether the remaining bits should be given negative or positive weight: ¾Ë Û ´µ Ü ´ ½µ Û ½ ¡ Ü Û ¾ Ü ¼ ¾ ½¼ ¡ ¡ ¡ ¼ Both of these representations have the curious property that there are two different encodings of the number 0. For both representations, is interpreted as . The value can be represented in sign-magnitude as and in one’s complement as . Although machines based on one’s complement representations were built in the past, almost all modern machines use two’s complement. We will see that sign-magnitude encoding is used with floating-point numbers. End Aside. ¼¼ ¡ ¡ ¡ ¼ ½½ ¡ ¡ ¡ ½ ·¼ ¼ As an example, consider the following code: 44 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Weight ½ ¦ 2 4 8 16 32 64 128 256 512 1,024 2,048 4,096 8,192 16,384 ¿¾ Total 12,345 Bit Value 1 ½ 0 0 0 0 1 8 1 16 1 32 0 0 0 0 0 0 0 0 0 0 0 0 1 4096 1 8192 0 0 0 0 12,345 12,345 Bit 1 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 Value ½ 2 4 0 0 0 64 128 256 512 1,024 2,048 0 0 16,384 32,768 12,345 53,191 Bit Value 1 ½ 1 2 1 4 0 0 0 0 0 0 1 64 1 128 1 256 1 512 1 1,024 1 2,048 0 0 0 0 1 16,384 1 32,768 53,191 Figure 2.10: Two’s Complement Representations of 12,345 and 12,345, and Unsigned Representation of 53,191. Note that the latter two have identical bit representations. 2.2. INTEGER REPRESENTATIONS 1 2 3 4 5 45 short int x = 12345; short int mx = -x; show_bytes((byte_pointer) &x, sizeof(short int)); show_bytes((byte_pointer) &mx, sizeof(short int)); When run on a big-endian machine, this code prints 30 39 and cf c7, indicating that x has hexadecimal representation 0x3039, while mx has hexadecimal representation 0xCFC7. Expanding these into binary we get bit patterns ¼¼½½¼¼¼¼¼¼½½½¼¼½ for x and ½½¼¼½½½½½½¼¼¼½½½ for mx. As Figure 2.10 shows, Equation 2.2 yields values 12,345 and 12,345 for these two bit patterns. 2.2.3 Conversions Between Signed and Unsigned Since both ¾Í Û and ¾Ì Û are bijections, they have well-defined inverses. Define ; Û to be ¾Í ½ , Û and ̾ Û to be ¾Ì ½ . These functions give the unsigned or two’s complement bit patterns for a numeric ¾ value. Given an integer Ü in the range ¼ Ü ¾Û , the function ; Û ´Üµ gives the unique Û-bit unsigned representation of Ü. Similarly, when Ü is in the range ¾Û ½ Ü ¾Û ½ , the function ̾ Û ´Üµ gives the unique Û-bit two’s complement representation of Ü. Observe that for values in the range ¼ Ü ¾Û ½ , both of these functions will yield the same bit representation—the most significant bit will be 0, and hence it does not matter whether this bit has positive or negative weight. Consider the following function: Í¾Ì Û ´Üµ ¾Ì Û ´Í¾ Û ´Üµµ. This function takes a number between ¼ and ¾Û ½ ½ and yields a number between ¾Û ½ and ¾Û ½ ½, where the two numbers have identical bit representations, except that the argument is unsigned, while the result has a two’s complement representation. Conversely, the function Ì¾Í Û ´Üµ ¾Í Û ´Ì¾ Û ´Üµµ yields the unsigned number having the same bit representation as the two’s complement value of x. For example, as Figure 2.10 indicates, the 16-bit, two’s complement representation of 12,345 is identical to the 16-bit, unsigned representation of 53,191. Therefore Ì¾Í ½ ´ ½¾ ¿ µ ¿ ½ ½, and Í¾Ì ½ ´ ¿ ½ ½µ ½¾ ¿ . These two functions might seem purely of academic interest, but they actually have great practical importance. They formally define the effect of casting between signed and unsigned values in C. For example, consider executing the following code on a two’s complement machine: 1 2 int x = -1; unsigned ux = (unsigned) x; This code will set ux to ÍÅ Ü Û , where Û is the number of bits in data type int, since by Figure 2.9 we can see that the Û-bit two’s complement representation of ½ has the same bit representation as ÍÅ Ü Û . In general, casting from a signed value x to unsigned value (unsigned) x is equivalent to applying function Ì¾Í . The cast does not change the bit representation of the argument, just how these bits are interpreted as a number. Similarly, casting from unsigned value u to signed value (int) u is equivalent to applying function Í¾Ì . Practice Problem 2.13: Using the table you filled in when solving Problem 2.12, fill in the following table describing the function Ì¾Í : 46 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION 2w +2w–1 Two’s Complement 0 2w–1 Unsigned 0 –2w–1 Figure 2.11: Conversion From Two’s Complement to Unsigned. numbers to large positive numbers. Function Ì¾Í converts negative ½ ¼ ¿ Ü Ì¾Í ´Üµ To get a better understanding of the relation between a signed number Ü and its unsigned counterpart Ì¾Í Û ´Üµ, we can use the fact that they have identical bit representations to derive a numerical relationship. Comparing Equations 2.1 and 2.2, we can see that for bit pattern Ü, if we compute the difference ¾Í Û ´Üµ ¾Ì Û ´Üµ, the weighted sums for bits from 0 to Û ¾ will cancel each other, leaving a value: ¾Í Û ´Üµ ¾Ì Û ´Üµ ÜÛ ½ ´¾Û ½ ¾Û ½ µ ÜÛ ½ ¾Û . This gives a relationship ¾Í Û ´Üµ ÜÛ ½ ¾Û · ¾Ì Û ´Üµ. If we let Ü ¾Ì Û ´Üµ, we then have ¾Í Û ´Ì¾ Û´ ܵµ Ì¾Í Û ´Üµ Ü ½ ¾ Û Û · Ü (2.3) This relationship is useful for proving relationships between unsigned and two’s complement arithmetic. In the two’s complement representation of Ü, bit ÜÛ ½ determines whether or not Ü is negative, giving Ì¾Í Û ´Üµ ´ Ü·¾ Ü Û Ü Ü ¼ ¼ (2.4) Figure 2.11 illustrates the behavior of function Ì¾Í . As it illustrates, when mapping a signed number to its unsigned counterpart, negative numbers are converted to large positive numbers, while nonnegative numbers remain unchanged. Practice Problem 2.14: Explain how Equation 2.4 applies to the entries in the table you generated when solving Problem 2.13. Going in the other direction, we wish to derive the relationship between an unsigned number Ü and its signed counterpart Í¾Ì Û ´Üµ. If we let Ü ¾Í Û ´Üµ, we have ¾Ì Û ´Í¾ Û´ ܵµ Í¾Ì Û ´Üµ Ü Û ½ ¾ Û · Ü (2.5) 2.2. INTEGER REPRESENTATIONS 2w 2w–1 Unsigned 47 +2w–1 0 Two’s Complement 0 –2w–1 Figure 2.12: Conversion From Unsigned to Two’s Complement. greater than ¾Û ½ ½ to negative values. Function Í¾Ì converts numbers In the unsigned representation of Ü, bit ÜÛ ½ determines whether or not Ü is greater than or equal to ¾Û ½ , giving Í¾Ì Û ´Üµ ´ Ü Ü ¾ Û Ü Ü ¾ ¾ Û Û ½ ½ (2.6) This behavior is illustrated in Figure 2.12. For small ( ¾Û ½ ) numbers, the conversion from unsigned to signed preserves the numeric value. For large ( ¾Û ½ ) the number is converted to a negative value. To summarize, we can consider the effects of converting in both directions between unsigned and two’s Û ½ complement representations. For values in the range ¼ Ü ¾ we have Ì¾Í Û ´Üµ Ü and Í¾Ì Û ´Üµ Ü. That is, numbers in this range have identical unsigned and two’s complement representations. For values outside of this range, the conversions either add or subtract ¾Û . For example, we have Ì¾Í Û ´ ½µ ½ · ¾Û ÍÅ Ü Û —the negative number closest to 0 maps to the largest unsigned number. At the other extreme, one can see that Ì¾Í Û ´ÌÅ Ò Û µ ¾Û ½ · ¾Û ¾Û ½ ÌÅ Ü Û · ½—the most negative number maps to an unsigned number just outside the range of positive, two’s complement numbers. Using the example of Figure 2.10, we can see that Ì¾Í ½ ´ ½¾ ¿ µ ¿ · ½¾ ¿ ¿ ½ ½. 2.2.4 Signed vs. Unsigned in C As indicated in Figure 2.8, C supports both signed and unsigned arithmetic for all of its integer data types. Although the C standard does not specify a particular representation of signed numbers, almost all machines use two’s complement. Generally, most numbers are signed by default. For example, when declaring a constant such as 12345 or 0x1A2B, the value is considered signed. To create an unsigned constant, the character ‘U’ or ‘u’ must be added as suffix, e.g., 12345U or 0x1A2Bu. C allows conversion between unsigned and signed. The rule is that the underlying bit representation is not changed. Thus, on a two’s complement machine, the effect is to apply the function Í¾Ì Û when converting from unsigned to signed, and Ì¾Í Û when converting from signed to unsigned, where Û is the number of bits for the data type. Conversions can happen due to explicit casting, such as in the code: 1 int tx, ty; 48 2 3 4 5 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION unsigned ux, uy; tx = (int) ux; uy = (unsigned) ty; or implicitly when an expression of one type is assigned to a variable of another, as in the code: 1 2 3 4 5 int tx, ty; unsigned ux, uy; tx = ux; /* Cast to signed */ uy = ty; /* Cast to unsigned */ When printing numeric values with printf, the directives %d, %u, and %x should be used to print a number as a signed decimal, an unsigned decimal, and in hexadecimal format, respectively. Note that printf does not make use of any type information, and so it is possible to print a value of type int with directive %u and a value of type unsigned with directive %d. For example, consider the following code: 1 2 3 4 5 int x = -1; unsigned u = 2147483648; /* 2 to the 31st */ printf("x = %u = %d\n", x, x); printf("u = %u = %d\n", u, u); When run on a 32-bit machine it prints the following: x = 4294967295 = -1 u = 2147483648 = -2147483648 In both cases, printf prints the word first as if it represented an unsigned number and second as if it represented a signed number. We can see the conversion routines in action: Ì¾Í ¿¾ ´ ½µ ÍÅ Ü ¿¾ ¿½ ¿½ ¿¾ ¿½ ¾ ¾ and Í¾Ì ¿¾ ´¾ µ ¾ ¾ ¾ ÌÅ Ò ¿¾. Some peculiar behavior arises due to C’s handling of expressions containing combinations of signed and unsigned quantities. When an operation is performed where one operand is signed and the other is unsigned, C implicitly casts the signed argument to unsigned and performs the operations assuming the numbers are nonnegative. As we will see, this convention makes little difference for standard arithmetic operations, but it leads to nonintuitive results for relational operators such as < and >. Figure 2.13 shows some sample relational expressions and their resulting evaluations, assuming a 32-bit machine using two’s complement representation. The nonintuitive cases are marked by ‘*’. Consider the comparison -1 < 0U. Since the second operand is unsigned, the first one is implicitly cast to unsigned, and hence the expression is equivalent to the comparison 4294967295U < 0U (recall that Ì¾Í Û ´ ½µ ÍÅ Ü Û ), which of course is false. The other cases can be understood by similar analyses. 2.2. INTEGER REPRESENTATIONS Expression 0 == 0U -1 < 0 -1 < 0U 2147483647 > -2147483648 2147483647U > -2147483648 2147483647 > (int) 2147483648U -1 > -2 (unsigned) -1 > -2 Type unsigned signed unsigned signed unsigned signed signed unsigned Evaluation 1 1 0* 1 0* 1* 1 0* 49 Figure 2.13: Effects of C Promotion Rules on 32-Bit Machine. Nonintuitive cases marked by ‘*’. When either operand of a comparison is unsigned, the other operand is implicitly cast to unsigned. 2.2.5 Expanding the Bit Representation of a Number One common operation is to convert between integers having different word sizes, while retaining the same numeric value. Of course, this may not be possible when the destination data type is too small to represent the desired value. Converting from a smaller to a larger data type, however, should always be possible. To convert an unsigned number to a larger data type, we can simply add leading 0s to the representation. this operation is known as zero extension. For converting a two’s complement number to a larger data type, the rule is to perform a sign extension, adding copies of the most significant bit to the representation. Thus, if our original value has bit representation ÜÛ ½ ÜÛ ¾ ܼ , the expanded representation would be ÜÛ ½ ÜÛ ½ ÜÛ ½ ÜÛ ¾ ܼ . As an example, consider the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 short sx = val; /* -12345 */ unsigned short usx = sx; /* 53191 */ int x = sx; /* -12345 */ unsigned ux = usx; /* 53191 */ printf("sx = %d:\t", sx); show_bytes((byte_pointer) &sx, sizeof(short)); printf("usx = %u:\t", usx); show_bytes((byte_pointer) &usx, sizeof(unsigned short)); printf("x = %d:\t", x); show_bytes((byte_pointer) &x, sizeof(int)); printf("ux = %u:\t", ux); show_bytes((byte_pointer) &ux, sizeof(unsigned)); When run on a 32-bit, big-endian machine using two’s complement representations this code prints: sx usx x ux = = = = -12345: 53191: -12345: 53191: cf cf ff 00 c7 c7 ff cf c7 00 cf c7 50 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION We see that although the two’s complement representation of 12,345 and the unsigned representation of 53,191 are identical for a 16-bit word size, they differ for a 32-bit word size. In particular, 12,345 has hexadecimal representation 0xFFFFCFC7, while 53,191 has hexadecimal representation 0x0000CFC7. The former has been sign-extended—16 copies of the most significant bit 1, having hexadecimal representation 0xFFFF, have been added as leading bits. The latter has been extended with 16 leading 0s, having hexadecimal representation 0x0000. Can we justify that sign extension works? What we want to prove is that ¾Ì Û· ´ Ü ½ Û Ü ½ Ü ½ Ü ¾ Û Û Û Ü¼ µ ¾Ì Û ´ ÜÛ ½ Ü ¾ Û Ü¼ µ where in the expression on the left-hand side, we have made additional copies of bit ÜÛ ½ . The proof follows by induction on . That is, if we can prove that sign-extending by one bit preserves the numeric value, then this property will hold when sign-extending by an arbitrary number of bits. Thus, the task reduces to proving that ¾Ì Û·½ ´ ÜÛ ½ Ü ½ Ü ¾ Û Û Ü¼ µ ¾Ì Û ´ ÜÛ ½ Ü ¾ Û Ü¼ µ Expanding the left-hand expression with Equation 2.2 gives ¾Ì Û·½ ´ ÜÛ ½ Ü ½ Ü ¾ Û Û Ü¼ µ Ü Ü Ü Ü Û Û ½¾ Û ½ ¼ · ܾ Û Û Û ½¾ Û · Ü ½¾ ½ · Û ¾ ¼ ܾ Û ½ ´¾ Û ¾ Û ½ µ · ¾ ¼ Û ¾ ¼ ܾ Û ½¾ Û ½ · Û Ü¾ ܼ µ ¾Ì Û ´ ÜÛ ½ Ü ¾ Û The key property we exploit is that ¾Û · ¾Û ½ ¾Û ½. Thus, the combined effect of adding a bit of weight ¾Û and of converting the bit having weight ¾Û ½ to be one with weight ¾Û ½ is to preserve the original numeric value. One point worth making is that the relative order of conversion from one data size to another and between unsigned and signed can affect the behavior of a program. Consider the following additional code for our previous example: 1 2 3 4 unsigned uy = x; /* Mystery! */ printf("uy = %u:\t", uy); show_bytes((byte_pointer) &uy, sizeof(unsigned)); 2.2. INTEGER REPRESENTATIONS This portion of the code causes the following to be printed: uy = 4294954951: ff ff cf c7 51 This shows that the expressions: (unsigned) (int) sx /* 4294954951 */ and (unsigned) (unsigned short) sx /* 53191 */ produce different values, even though the original and the final data types are the same. In the former expression, we first sign extend the 16-bit short to a 32-bit int, whereas zero extension is performed in the latter expression. 2.2.6 Truncating Numbers Suppose that rather than extending a value with extra bits, we reduce the number of bits representing a number. This occurs, for example, in the code: 1 2 3 int x = 53191; short sx = (short) x; int y = sx; /* -12345 */ /* -12345 */ On a typical 32-bit machine, when we cast x to be short, we truncate the 32-bit int to be a 16-bit short int. As we saw before, this 16-bit pattern is the two’s complement representation of 12,345. When we cast this back to int, sign extension will set the high-order 16 bits to 1s, yielding the 32-bit two’s complement representation of 12,345. When truncating a Û-bit number Ü ÜÛ ½ ÜÛ ¾ ܼ to a -bit number, we drop the high-order Û bits, giving a bit vector ܼ Ü ½ Ü ¾ ܼ . Truncating a number can alter its value—a form of overflow. We now investigate what numeric value will result. For an unsigned number Ü, the result of truncating it to bits is equivalent to computing Ü ÑÓ ¾ . This can be seen by applying the modulus operation to Equation 2.1: ¾Í Û ´ ÜÛ Ü ½ Û Ü¼ µ ÑÓ Û ½ ¼ ¾ ܾ ܾ ÑÓ ¾ ½ ½ ¼ ¼ ÑÓ ¾ ܾ ´ ¾Í Ü Ü ½ ܼ µ 52 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION ÑÓ ¾ ¼ In È the½ above derivation we make use of the property that ¾ ¾ ¾ ½ ¾ . ¼ for any , and that È ½ ¼Ü¾ For a two’s complement number Ü, a similar argument shows that ¾Ì Û ´ ÜÛ ÜÛ ½ ܼ µ ÑÓ ¾ ¾Í ´ Ü Ü ½ ܼ µ. That is, Ü ÑÓ ¾ can be represented by an unsigned number having bit-level representation Ü ½ ܼ . In general, however, we treat the truncated number as being signed. This will have numeric value Í¾Ì ´Ü ÑÓ ¾ µ. Summarizing, the effects of truncation are: ¾Í ¾Ì Ü Ü ½ ´Ü Ü ½ ´ ܼ µ ܼ µ ¾Í Û ´ ÜÛ ÜÛ ½ Í¾Ì ´ ¾Ì Û ´ ÜÛ Ü¼ µ ÑÓ ¾ Ü ½ ܼ µ ÑÓ Û (2.7) ¾µ (2.8) Practice Problem 2.15: Suppose we truncate a four-bit value (represented by hex digits 0 through F) to a three-bit value (represented as hex digits 0 through 7). Fill in the table below showing the effect of this truncation for some cases, in terms of the unsigned and two’s complement interpretations of those bit patterns. Hex Original 0 3 8 A F Truncated 0 3 0 2 7 Unsigned Original Truncated ¼ ¿ ½¼ ½ Two’s Complement Original Truncated ¼ ½ ¿ Explain how Equations 2.7 and 2.8 apply to these cases. 2.2.7 Advice on Signed vs. Unsigned As we have seen, the implicit casting of signed to unsigned leads to some nonintuitive behavior. Nonintuitive features often lead to program bugs, and ones involving the nuances of implicit casting can be especially difficult to see. Since the casting is invisible, we can often overlook its effects. Practice Problem 2.16: Consider the following code that attempts to sum the elements of an array a, where the number of elements is given by parameter length: 1 2 3 4 5 6 7 8 9 10 /* WARNING: This is buggy code */ float sum_elements(float a, unsigned length) { int i; float result = 0; for (i = 0; i <= length-1; i++) result += a[i]; return result; } 2.3. INTEGER ARITHMETIC When run with argument length equal to 0, this code should return ¼ ¼. Instead it encounters a memory error. Explain why this happens. Show how this code can be corrected. 53 One way to avoid such bugs is to never use unsigned numbers. In fact, few languages other than C support unsigned integers. Apparently these other language designers viewed them as more trouble than they are worth. For example, Java supports only signed integers, and it requires that they be implemented with two’s complement arithmetic. The normal right shift operator >> is guaranteed to perform an arithmetic shift. The special operator >>> is defined to perform a logical right shift. Unsigned values are very useful when we want to think of words as just collections of bits with no numeric interpretation. This occurs, for example, when packing a word with flags describing various Boolean conditions. Addresses are naturally unsigned, so systems programmers find unsigned types to be helpful. Unsigned values are also useful when implementing mathematical packages for modular arithmetic and for multiprecision arithmetic, in which numbers are represented by arrays of words. 2.3 Integer Arithmetic Many beginning programmers are surprised to find that adding two positive numbers can yield a negative result, and that the comparison x < y can yield a different result than the comparison x-y < 0. These properties are artifacts of the finite nature of computer arithmetic. Understanding the nuances of computer arithmetic can help programmers write more reliable code. 2.3.1 Unsigned Addition Consider two nonnegative integers Ü and Ý , such that ¼ Ü Ý ¾Û ½. Each of these numbers can be represented by Û-bit unsigned numbers. If we compute their sum, however, we have a possible range ¼ Ü·Ý ¾Û·½ ¾. Representing this sum could require Û ·½ bits. For example, Figure 2.14 shows a plot of the function Ü · Ý when Ü and Ý have four-bit representations. The arguments (shown on the horizontal axes) range from 0 to 15, but the sum ranges from 0 to 30. The shape of the function is a sloping plane. If we were to maintain the sum as a Û · ½ bit number and add it to another value, we may require Û · ¾ bits, and so on. This continued “word size inflation” means we cannot place any bound on the word size required to fully represent the results of arithmetic operations. Some programming languages, such as Lisp, actually support infinite precision arithmetic to allow arbitrary (within the memory limits of the machine, of course) integer arithmetic. More commonly, programming languages support fixed-precision arithmetic, and hence operations such as “addition” and “multiplication” differ from their counterpart operations over integers. Unsigned arithmetic can be viewed as a form of modular arithmetic. Unsigned addition is equivalent to computing the sum modulo ¾Û . This value can be computed by simply discarding the high-order bit in the Û · ½-bit representation of Ü · Ý. For example, consider a four-bit number representation with Ü and Ý ½¾, having bit representations ½¼¼½ and ½½¼¼ , respectively. Their sum is ¾½, having a 5-bit representation ½¼½¼½ . But if we discard the high-order bit, we get ¼½¼½ , that is, decimal value . This matches the value ¾½ ÑÓ ½ . In general, we can see that if Ü · Ý ¾ Û , the leading bit in the Û · ½-bit representation of the sum will equal 54 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Integer Addition 32 28 24 20 16 12 8 4 0 0 2 4 6 2 8 10 12 0 14 4 6 10 8 12 14 Figure 2.14: Integer Addition. With a four-bit word size, the sum could require 5 bits. x +y 2w+1 2w 0 Overflow x +u y Figure 2.15: Relation Between Integer Addition and Unsigned Addition. When Û ¾ ½, the sum overflows. Ü · Ý is greater than 2.3. INTEGER ARITHMETIC 55 Unsigned Addition (4-bit word) Overflow 16 14 12 10 8 6 4 2 0 0 2 4 6 2 8 10 12 0 14 4 6 10 8 12 14 Normal Figure 2.16: Unsigned Addition. With a four-bit word size, addition is performed modulo 16. 0, and hence discarding it will not change the numeric value. On the other hand, if ¾Û Ü · Ý ¾Û·½ , the leading bit in the Û · ½-bit representation of the sum will equal 1, and hence discarding it is equivalent to subtracting ¾Û from the sum. These two cases are illustrated in Figure 2.15. This will give us a value in the range ¼ Ü · Ý ¾Û ¾Û·½ ¾Û ¾Û , which is precisely the modulo ¾Û sum of Ü and Ý . Let us define the operation +u for arguments Ü and Ý such that ¼ Ü Ý ¾Û as: Û Ü+ Ý u Û ´ Ü·Ý Ü·Ý ¾ Ü·Ý Û ¾ Û Ü·Ý ¾ Û ¾ Û ·½ (2.9) This is precisely the result we get in C when performing addition on two Û-bit unsigned values. An arithmetic operation is said to overflow when the full integer result cannot fit within the word size limits of the data type. As Equation 2.9 indicates, overflow occurs when the two operands sum to ¾Û or more. Figure 2.16 shows a plot of the unsigned addition function for word size Û . The sum is computed u modulo ¾ ½ . When Ü · Ý ½ , there is no overflow, and Ü + Ý is simply Ü · Ý . This is shown as the region forming a sloping plane labeled “Normal.” When Ü · Ý ½ , the addition overflows, having 56 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION the effect of decrementing the sum by 16. This is shown as the region forming a sloping plane labeled “Overflow.” When executing C programs, overflows are not signalled as errors. At times, however, we might wish to determine whether overflow has occurred. For example, suppose we compute × Ü +u Ý , and we wish to Û determine whether × equals Ü · Ý . We claim that overflow has occurred if and only if × Ü (or equivalently × Ý.) To see this, observe that Ü · Ý Ü, and hence if × did not overflow, we will surely have × Ü. On the other hand, if × did overflow, we have × Ü · Ý ¾Û . Given that Ý ¾Û , we have Ý ¾Û ¼, and hence × Ü · Ý ¾Û Ü. In our earlier example, we saw that +u ½¾ . We can see that overflow occurred, since . Modular addition forms a mathematical structure known as an Abelian group, named after the Danish mathematician Niels Henrik Abel (1802–1829). That is, it is commutative (that’s where the “Abelian” part comes in) and associative. It has an identity element 0, and every element has an additive inverse. Let us consider the set of Û-bit unsigned numbers with addition operation +u . For every value Ü, there must Û be some value -u Ü such that -u Ü +u Ü ¼. When Ü ¼, the additive inverse is clearly ¼. For Û Û Û Ü ¼, consider the value ¾Û Ü. Observe that this number is in the range ¼ ¾Û Ü ¾Û , and Û ´Ü · ¾ ܵ ÑÓ ¾Û ¾Û ÑÓ ¾Û ¼. Hence it is the inverse of Ü under +uÛ . These two cases lead to the following equation for ¼ Ü ¾Û : -u Ü Û Practice Problem 2.17: We can represent a bit pattern of length Û with a single hex digit. For an unsigned interpretation of these digits use Equation 2.10 fill in the following table giving the values and the bit representations (in hex) of the unsigned additive inverses of the digits shown. Ü ´ Ü ¾ Û Ü Ü Ü ¼ ¼ (2.10) -u Decimal Decimal Ü Hex 0 3 8 A F Hex 2.3.2 Two’s Complement Addition A similar problem arises for two’s complement addition. Given integer values Ü and Ý in the range ¾Û ½ Ü Ý ¾Û ½ ½, their sum is in the range ¾Û Ü · Ý ¾Û ¾, potentially requiring Û · ½ bits to represent exactly. As before, we avoid ever-expanding data sizes by truncating the representation to Û bits. The result is not as familiar mathematically as modular addition, however. The Û-bit two’s complement sum of two numbers has the exact same bit-level representation as the unsigned sum. In fact, most computers use the same machine instruction to perform either unsigned or signed 2.3. INTEGER ARITHMETIC x +y 57 +2w Case 4 Positive Overflow x +t y +2w –1 Case 3 +2w –1 0 –2w –1 Negative Overflow 0 Case 2 –2w –1 Case 1 –2w Figure 2.17: Relation Between Integer and Two’s Complement Addition. When Ü · Ý is less than ¾Û ½, there is a negative overflow. When it is greater than ¾Û ½ · ½, there is a positive overflow. addition. Thus, we can define two’s complement addition for word size Û, denoted as +tÛ on operands and Ý such that ¾Û ½ Ü Ý ¾Û ½ as Ü Ü +t Ý Û Í¾Ì Û ´Ì¾Í Û ´Üµ +u Ì¾Í Û ´Ý µµ Û (2.11) By Equation 2.3 we can write Ì¾Í Û ´Üµ as ÜÛ ½ ¾Û · Ü, and Ì¾Í Û ´Ý µ as ÝÛ ½ ¾Û · Ý . Using the property that +u is simply addition modulo ¾Û , along with the properties of modular addition, we then have Û Ü +t Ý Û Í¾Ì Û ´Ì¾Í Û ´Üµ +u Ì¾Í Û ´Ý µµ Û Û Í¾Ì Û ´ ÜÛ ½ ¾ · Ü · ÝÛ ½ ¾Û · Ý µ ÑÓ Í¾Ì Û ´Ü · Ý µ ÑÓ ¾Û ¾ Û The terms ÜÛ ½ ¾Û and ÝÛ ½ ¾Û drop out since they equal 0 modulo ¾Û . To better understand this quantity, let us define Þ as the integer sum Þ Ü · Ý , Þ ¼ as Þ ¼ Þ ÑÓ ¾Û , and Þ ¼¼ as Þ ¼¼ Í¾Ì Û ´Þ ¼ µ. The value Þ ¼¼ is equal to Ü +tÛ Ý . We can divide the analysis into four cases as illustrated in Figure 2.17: 1. Þ 2. ¼ . Then we will again have Þ ¼ Þ · ¾Û , giving ¾Û ½ · ¾Û ¾Û ½ Þ ¼ ¾Û . ¼ is in such a range that Þ ¼¼ Þ ¼ ¾Û , and therefore Þ ¼¼ Examining Equation 2.6, we see that Þ Þ ¼ ¾Û Þ · ¾Û ¾Û Þ . That is, our two’s complement sum Þ ¼¼ equals the integer sum Ü · Ý. ¾ Û negative overflow. We have added two negative numbers Ü and Ý (that’s the only way we can have ¾Û ½) and obtained a nonnegative result Þ¼¼ Ü · Ý · ¾Û . ½ . Then we will have Þ ¼ Þ · ¾ . This gives ¼ Þ ¼ ¾ ½ · ¾ ½ . ¾ ¼ is in the range such that Þ ¼¼ Þ ¼ . This case is referred to as Examining Equation 2.6, we see that Þ ¾ Û Þ ¾ Û Û Û Û Û ½ Þ ¼ 3. ½ . Then we will have Þ ¼ Þ , giving ¼ Þ ¼ two’s complement sum Þ ¼¼ equals the integer sum Ü · Ý . Þ ¾ Û ¾ Û ½ , and hence Þ ¼¼ Þ¼ Þ . Again, the 58 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Ü Ý Ü · Ý Ü +t Ý ½¿ ¿ ¼¼½½ Case 1 1 2 3 ½¼¼¼ ½¼½½ ½ ¼ ¼¼¼¼ ¿ ½¼¼¼ ½¼¼¼ ¿ ½¼¼¼ ¾ ¼¼½¼ ¼½¼½ ½½¼½ ¼½¼½ ½¼ ¼½½½ 4 ¼½¼½ ¼½¼½ ½¼½¼ Figure 2.18: Two’s Complement Addition Examples. The bit-level representation of the four-bit two’s complement sum can be obtained by performing binary addition of the operands and truncating the result to bits. 4. . We will again have Þ ¼ Þ , giving ¾Û ½ Þ ¼ ¾Û . But in this range we have Þ ¼¼ Þ ¼ ¾Û , giving Þ ¼¼ Ü · Ý ¾Û . This case is referred to as positive overflow. We have added Û ½ two positive numbers Ü and Ý (that’s the only way we can have Þ ¾ ) and obtained a negative ¼¼ Ü · Ý ¾Û . result Þ ¾ Û ½ Þ ¾ Û By the preceding analysis, we have shown that when operation +tÛ is applied to values Ü and Ý in the range ¾Û ½ Ü Ý ¾Û ½ ½, we have Ü+ Ý t Û Ü·Ý ¾ Ü·Ý Ü·Ý·¾ Û Û ½ Ü · Ý ¾ ½ Ü · Ý Ü · Ý ¾ ½ ¾ Û Û Û ¾ Û ½ Normal Positive Overflow (2.12) Negative Overflow Figure 2.19 illustrates two’s complement addition for word size Û . The operands range between and . When Ü · Ý , two’s complement addition has a negative underflow, causing the sum to be incremented by 16. When Ü·Ý , the addition yields Ü · Ý . When Ü · Ý , the addition has a positive overflow, causing the sum to be decremented by 16. Each of these three ranges forms a sloping plane in the figure. Equation 2.12 also lets us identify the cases where overflow has occurred. When both Ü and Ý are negative, t but Ü +tÛ Ý ¼, we have negative overflow. When both Ü and Ý are positive, but Ü +Û Ý ¼, we have positive overflow. Practice Problem 2.18: As an illustration, Figure 2.18 shows some examples of four-bit two’s complement addition. Each example is labeled by the case to which it corresponds in the derivation of Equation 2.12. Note that ¾ ½ , and hence negative overflow yields a result 16 more than the integer sum, and positive overflow yields a result 16 less. We include bit-level representations of the operands and the result. Observe that the result can be obtained by performing binary addition of the operands and truncating the result to four bits. 2.3. INTEGER ARITHMETIC 59 Two's Complement Addition (4-bit word) 8 6 4 2 0 -2 -4 -6 -8 Negative Overflow Normal Positive Overflow 6 4 2 0 -2 -8 -4 -6 -4 -2 -6 0 2 4 -8 6 Figure 2.19: Two’s Complement Addition. With a four-bit word size, addition can have a negative overflow when Ü · Ý and a positive overflow when Ü · Ý . 60 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Fill in the following table in the style of Figure 2.18. Give the integer values of the 5-bit arguments, the values of both their integer and two’s complement sums, the bit-level representation of the two’s complement sum, and the case from the derivation of Equation 2.12. Ü Ý Ü ·Ý Ü +t Ý Case ½¼¼¼¼ ½¼¼¼¼ ½½¼¼¼ ½½½½¼ ¼½¼¼¼ ½¼½¼½ ½¼¼¼¼ ¼¼½½½ ¼¼½¼½ ¼½¼¼¼ 2.3.3 Two’s Complement Negation We can see that every number Ü in the range ¾Û ½ Ü ¾Û ½ has an additive inverse under +tÛ as follows. First, for Ü ¾Û ½, we can see that its additive inverse is simply Ü. That is, we have Û ½ Û ½ ¾ Ü ¾ and Ü +tÛ Ü Ü · Ü ¼. For Ü ¾Û ½ ÌÅ Ò Û , on the other hand, Ü ¾Û ½ cannot be represented as a Û-bit number. We claim that this special value has itself as the additive inverse under +tÛ . The value of ¾Û·½ +tÛ ¾Û·½ is given by the third case of Equation 2.12, since ¾Û ½ · ¾Û ½ ¾Û . This gives ¾Û·½ +tÛ ¾Û·½ ¾Û · ¾Û ¼. From this analysis we can define the two’s complement negation operation -tÛ for Ü in the range ¾¾ ½ Ü ¾Û ½ as: -Û Ü t ´ Ü ¾ Û ½ Ü Ü ¾ ¾ Û Û ½ ½ (2.13) Practice Problem 2.19: We can represent a bit pattern of length Û with a single hex digit. For a two’s complement interpretation of these digits, fill in the following table to determine the additive inverses of the digits shown. Ü Hex 0 3 8 A F Decimal -t Decimal Ü Hex What do you observe about the bit patterns generated by two’s complement and unsigned (Problem 2.17) negation. 2.3. INTEGER ARITHMETIC 61 A well-known technique for performing two’s complement negation at the bit level is to complement the bits and then increment the result. In C, this can be written as ˜x + 1. To justify the correctness of this technique, observe that for any single bit Ü , we have ˜Ü ½ Ü . Let Ü be a bit vector of length Û and Ü ¾Ì Û ´Üµ be the two’s complement number it represents. By Equation 2.2, the complemented bit vector ˜Ü has numeric value ¾Ì Û ´˜Üµ Ü ´½ Û ½ µ¾ Û Û ½ · Û ¾ ´½ ½ ¾ Û ½ · ½ ¾ ¾ ¼ Ü ½¾ µ¾ Ü Û Û ½ · Û ¾ ¼ ܾ Ü ¾ Û ·¾ Û ½ ½ ¼ ¾Ì Û ´Üµ The key simplification in the above derivation is that ˜Ü we obtain Ü. È ¾ ¾ Û ¼ ¾ Û ½ ½. It follows that by incrementing . To increment a number Ü represented at the bit-level as Ü ÜÛ ½ ÜÛ ¾ ܼ , define the operation Ò Ö as follows. Let be the position of the rightmost zero, such that Ü is of the form ÜÛ ½ ÜÛ ¾ Ü ·½ ¼ ½ We then define Ò Ö ´Üµ to be ÜÛ ½ ÜÛ ¾ Ü ·½ ½ ¼ ¼ . For the special case where the bit-level representation of Ü is ½ ½ ½ , define Ò Ö ´Üµ to be ¼ ¼ . To show that Ò Ö ´Üµ yields the bit-level representation of Ü +tÛ ½, consider the following cases: 1. When Ü value ¼. 2. When ½¼ ½½ ½ ½ , we have Ü ½ . The incremented value Ò Ö ´Üµ ¼ ¼ has numeric ¼½ ½ , we have Ü ÌÅ Ü Û . The incremented value Ò Ö ´Üµ has numeric value ÌÅ Ò Û . From Equation 2.12, we can see that ÌÅ Ü Û +tÛ ½ is one of the positive overflow cases, yielding ÌÅ Ò Û . ¼ Û ½, i.e., Ü 3. When Û ½, i.e., Ü ÌÅ Ü Û and Ü ½, we can see that the low-order · ½ bits of Ò Ö ´Üµ È ½ has numeric value ¾ , while the low-order · ½ bits of Ü has numeric value ¾ ½. The ¼¾ high-order Û · ½ bits have matching numeric values. Thus, Ò Ö ´Üµ has numeric value Ü · ½. In addition, for Ü ÌÅ Ü Û , adding 1 to Ü will not cause an overflow, and hence Ü +tÛ ½ has numeric value Ü · ½ as well. As illustrations, Figure 2.20 shows how complementing and incrementing affect the numeric values of several four-bit vectors. 2.3.4 Unsigned Multiplication Û Integers Ü and Ý in the range ¼ Ü Ý ¾ ½ can be represented as Û-bit unsigned numbers, but their Û product Ü ¡ Ý can range between ¼ and ´¾ ½µ¾ ¾¾Û ¾Û·½ · ½. This could require as many as ¾Û bits to represent. Instead, unsigned multiplication in C is defined to yield the Û-bit value given by the low-order 62 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Ü ¼½¼½ ¼½½½ ½½¼¼ ¼¼¼¼ ½¼¼¼ ˜Ü ½¼½¼ ¼ ½¼¼¼ ¼¼½½ ½½½½ ¼½½½ ¿ ½ Ò Ö ´˜Üµ ½¼½½ ½¼¼½ ¼½¼¼ ¼¼¼¼ ½¼¼¼ ¼ Figure 2.20: Examples of Complementing and Incrementing four-bit numbers. The effect is to compute the two’s value negation. Û bits of the ¾Û-bit integer product. product modulo ¾ Û By Equation 2.7, this can be seen to be equivalent to computing the . Thus, the effect of the Û-bit unsigned multiplication operation *u is: Û Ü *u Ý Û ´ Ü ¡ ݵ ÑÓ ¾ Û (2.14) It is well known that modular arithmetic forms a ring. We can therefore deduce that unsigned arithmetic Û over Û-bit numbers forms a ring ¼ ¾ ½ +uÛ *uÛ -uÛ ¼ ½ . 2.3.5 Two’s Complement Multiplication Integers Ü and Ý in the range ¾Û ½ Ü Ý ¾Û ½ ½ can be represented as Û-bit two’s complement numbers, but their product Ü ¡ Ý can range between ¾Û ½ ¡ ´¾Û ½ ½µ ¾¾Û ¾ · ¾Û ½ and ¾Û ½ ¡ ¾Û ½ ¾¾Û ¾. This could require as many as ¾Û bits to represent in two’s complement form—most cases would fit into ¾Û ½ bits, but the special case of ¾¾Û ¾ requires the full ¾Û bits (to include a sign bit of 0). Instead, signed multiplication in C is generally performed by truncating the ¾Û-bit product to Û bits. By Equation 2.8, the effect of the Û-bit two’s complement multiplication operation *tÛ is: Ü *t Ý Û Í¾Ì Û ´´Ü ¡ Ý µ ÑÓ ¾ Û µ (2.15) We claim that the bit-level representation of the product operation is identical for both unsigned and two’s complement multiplication. That is, given bit vectors Ü and Ý of length Û, the bit-level representation of the unsigned product ¾Í Û ´Üµ *u ¾Í Û ´Ý µ is identical to the bit-level representation of the two’s complement Û product ¾Ì Û ´Üµ *tÛ ¾Ì Û ´Üµ. This implies that the machine can use a single type of multiply instruction to multiply both signed and unsigned integers. To see this, let Ü ¾Ì Û ´Üµ and Ý ¾Ì Û ´Ý µ be the two’s complement values denoted by these bit patterns, and let ܼ ¾Í Û ´Üµ and Ý ¼ ¾Í Û ´Ý µ be the unsigned values. From Equation 2.3, we have ¼ Ü · ÜÛ ½¾Û , and ݼ Ý · ÝÛ ½¾Û . Computing the product of these values modulo ¾Û gives: Ü ´ ܼ ¡ ݼ µ ÑÓ ¾ Û Ü · Ü ½¾ µ ¡ ´Ý · Ý ½¾ Ü ¡ Ý · ´Ü ½ Ý · Ý ½Üµ¾ ´Ü ¡ Ý µ ÑÓ ¾ ´ Û Û Û Û Û Û Û ÑÓ Û ¾ Û (2.16) ¾Û ÑÓ ¾ Û Û · Ü ½Ý ½ ¾ Û (2.17) (2.18) Thus, the low-order Û bits of Ü ¡ Ý and ܼ ¡ Ý ¼ are identical. 2.3. INTEGER ARITHMETIC Mode Unsigned Two’s Comp. Unsigned Two’s Comp. Unsigned Two’s Comp. 63 Ü Ý ½¼½ ¿ ¿ ¼½½ ¼½½ ½½½ ½ ½½½ ¼½½ ¼½½ ½¼½ ½¼¼ ½¼¼ ¼½½ ¼½½ Ü¡Ý Truncated Ü ¡ Ý ¿ ¾ ½ ¼¼½½½½ ½½¼½½½ ¼½½½¼¼ ¼¼¼½¼¼ ¼¼½¼¼½ ¼¼½¼¼½ ½½½ ½ ½½½ ½¼¼ ½¼¼ ¼¼½ ¼¼½ ¿ ¿ ¿ ¿ ½ ½ Figure 2.21: 3-Bit Unsigned and Two’s Complement Multiplication Examples. Although the bit-level representations of the full products may differ, those of the truncated products are identical. As illustrations, Figure 2.21 shows the results of multiplying different 3-bit numbers. For each pair of bitlevel operands, we perform both unsigned and two’s complement multiplication. Note that the unsigned, truncated product always equals Ü ¡ Ý ÑÓ , and that the bit-level representations of both truncated products are identical. Practice Problem 2.20: Fill in the following table showing the results of multiplying different 3-bit numbers, in the style of Figure 2.21 Mode Unsigned Two’s Comp. Unsigned Two’s Comp. Unsigned Two’s Comp. Ü Ý Ü ½½¼ ½½¼ ¼¼½ ¼¼½ ½½½ ½½½ ¼½¼ ¼½¼ ½½½ ½½½ ½½½ ½½½ ¡ Ý Truncated Ü ¡ Ý We can see that unsigned arithmetic and two’s complement arithmetic over Û-bit numbers are isomorphic— the operations +u , -u , and *u have the exact same effect at the bit level as do +tÛ , -tÛ , and *tÛ . From this Û Û Û Û ½ we can deduce that two’s complement arithmetic forms a ring ¾Û ½ ¾ ½ +tÛ *tÛ -tÛ ¼ ½ . 2.3.6 Multiplying by Powers of Two On most machines, the integer multiply instruction is fairly slow—requiring 12 or more clock cycles— whereas other integer operations such as addition, subtraction, bit-level operations, and shifting require only one clock cycle. As a consequence, one important optimization used by compilers is to attempt to replace multiplications by constant factors with combinations of shift and addition operations. Let Ü be the unsigned integer represented by bit pattern ÜÛ ½ ÜÛ ¾ claim the bit-level representation of ܾ is given by ÜÛ ½ ÜÛ ¾ ܼ ܼ . ¼ Then for any ¼, we ¼ , where 0s have been 64 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION added to the right. This property can be derived using Equation 2.1: ¾Í Û· ´ Ü ½ Ü ¾ Û Û Ü¼ Û ½ ¼ ¼ ¼µ ܾ· ܾ Û ½ ¼ ¡ ¾ ܾ For Û, we can truncate the shifted bit vector to be of length Û, giving ÜÛ ½ ÜÛ ¾ ܼ ¼ ¼. By Equation 2.7, this bit-vector has numeric value ܾ ÑÓ ¾Û Ü *u ¾ . Thus, for unsigned variable Û x, the C expression x << k is equivalent to x * pwr2k, where pwr2k equals ¾k . In particular, we can compute pwr2k as 1U << k. By similar reasoning, we can show that for a two’s complement number Ü having bit pattern ÜÛ ½ ÜÛ ¾ and any in the range ¼ Û, bit pattern ÜÛ ½ ܼ ¼ ¼ will be the two’s complement representation of Ü *tÛ ¾ . Therefore, for signed variable x , the C expression x << k is equivalent to x * pwr2k, where pwr2k equals ¾k . Note that multiplying by a power of two can cause overflow with either unsigned or two’s complement arithmetic. Our result shows that even then we will get the same effect by shifting. Practice Problem 2.21: As we will see in Chapter 3, the leal instruction on an Intel-compatible processor can perform computations of the form a<<k + b, where k is either 0, 1, or 2, and b is either 0 or some program value. The compiler often uses this instruction to perform multiplications by constant factors. For example, we can compute 3*a as a<<1 + a. What multiples of a can be computed with this instruction? ܼ , 2.3.7 Dividing by Powers of Two Integer division on most machines is even slower than integer multiplication—requiring 30 or more clock cycles. Dividing by a power of two can also be performed using shift operations, but we use a right shift rather than a left shift. The two different shifts—logical and arithmetic—serves this purpose for unsigned and two’s complement numbers, respectively. Integer division always rounds toward zero. For Ü ¼ and Ý ¼, the result should be Ü Ý , where for any ¼ · ½. As examples ¿ ½ real number , is defined to be the unique integer ¼ such that ¼ ¿, ¿ ½ , and ¿ ¿. Consider the effect of performing a logical right shift on an unsigned number. Let Ü be the unsigned integer represented by bit pattern ÜÛ ½ ÜÛ ¾ ܼ , and be in the range ¼ Û. Let ܼ be the ¼¼ be the unsigned number with unsigned number with Û -bit representation ÜÛ ½ ÜÛ ¾ Ü , and Ü -bit representation Ü ½ ܼ . We claim that ܼ Ü ¾ . To see this, by Equation 2.1, we have ÈÛ ½ ¼ ÈÛ ½ Ü ¾ and ܼ¼ È ½ Ü ¾ . We can therefore write Ü as Ü ¾ ܼ · ܼ¼ . Ü ¼ ܾ,Ü ¼ 2.3. INTEGER ARITHMETIC Observe that ¼ 65 ¾ Ü ¾ ܼ¼ ܼ · ܼ¼ ¾ È ½ ¾ ¼ ܼ · ܼ¼ ¾ ¼ ½ , and hence ¼ ܼ . ܼ¼ Û ¾ , implying that Û Ü¼¼ ¾ ¼ . Therefore Observe that performing a logical right shift of bit vector ¼ Û Û This bit vector has numeric value ܼ . That is, logically right shifting an unsigned number by is equivalent to dividing it by ¾ . Therefore, for unsigned variable x, the C expression x >> k is equivalent to x / pwr2k, where pwr2k equals ¾k . Now consider the effect of performing an arithmetic right shift on a two’s complement number. Let Ü be the two’s complement integer represented by bit pattern ÜÛ ½ ÜÛ ¾ ܼ , and be in the range ¼ Û. Let ܼ be the two’s complement number represented by the Û bits ÜÛ ½ ÜÛ ¾ Ü , and ܼ¼ be the unsigned number represented by the low-order bits Ü ½ ܼ . By a similar analysis as the unsigned case, we have Ü ¾ ܼ · ܼ¼ , and ¼ ܼ¼ ¾ , giving ܼ Ü ¾ . Furthermore, observe that shifting bit vector ÜÛ ½ ÜÛ ¾ ܼ right arithmetically by yields a bit vector Ü ½ Ü ¾ Ü ½ Ü ¾ Ü Ü¼ by yields bit vector ¼ . That is, integer division should round negative results upward integer ¼ such that ¼ ½ toward zero. For example the C expression -5/2 yields -2. Thus, right shifting a negative number by is not equivalent to dividing it by ¾ when rounding occurs. For example, the four-bit representation of is ½¼½½ . If we shift it right by one arithmetically we get ½½¼½ , which is the two’s complement representation of ¿. We can correct for this improper rounding by “biasing” the value before shifting. This technique exploits the property that Ü Ý ´Ü · Ý ½µ Ý for integers Ü and Ý such that Ý ¼. Thus, for Ü ¼, if we first add ¾ ½ to Ü before right shifting, we will get a correctly rounded result. This analysis shows that for a two’s complement machine using arithmetic right shifts, the C expression (x<0 ? (x + (1<<k)1) : x) >> k is equivalent to x/pwr2k, where pwr2k equals ¾k . For example, to divide by ¾, we first add bias ¾ ½ ½ giving bit pattern ½½¼¼ . Right shifting this by one arithmetically gives bit pattern ½½½¼ , which is the two’s complement representation of ¾. Practice Problem 2.22: In the following code, we have omitted the definitions of constants M and N: #define M /* Mystery number 1 */ #define N /* Mystery number 2 */ int arith(int x, int y) { int result = 0; result = x*M + y/N; /* M and N are mystery numbers. */ return result; } Ü ½ Ü ½ Ü ½ Ü ¾ Ü which is the sign extension from Û bits to Û bits of Ü ½ Ü ¾ Ü . Thus, this shifted bit vector is the two’s complement representation of Ü Ý . For Ü ¼, our analysis shows that this shifted result is the desired value. For Ü ¼ and Ý ¼, however, the result of integer division should be Ü Ý , where for any real number , is defined to be the unique Û Û Û Û Û Û 66 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION We compiled this code for particular values of M and N. The compiler optimized the multiplication and division using the methods we have discussed. The following is a translation of the generated machine code back into C: /* Translation of assembly code for arith */ int optarith(int x, int y) { int t = x; x <<= 4; x -= t; if (y < 0) y += 3; y >>= 2; /* Arithmetic shift */ return x+y; } What are the values of M and N? 2.4 Floating Point Floating-point representation encodes rational numbers of the form Î Ü ¢ ¾Ý . It is useful for performing computations involving very large numbers ( Î ¼), numbers very close to 0 ( Î ½), and more generally as an approximation to real arithmetic. Up until the 1980s, every computer manufacturer devised its own conventions for how floating-point numbers were represented and the details of the operations performed on them. In addition, they often did not worry too much about the accuracy of the operations, viewing speed and ease of implementation as being more critical than numerical precision. All of this changed around 1985 with the advent of IEEE Standard 754, a carefully crafted standard for representing floating-point numbers and the operations performed on them. This effort started in 1976 under Intel’s sponsorship with the design of the 8087, a chip that provided floating-point support for the 8086 processor. They hired William Kahan, a professor at the University of California, Berkeley, as a consultant to help design a floating point standard for its future processors. They allowed Kahan to join forces with a committee generating an industry-wide standard under the auspices of the Institute of Electrical and Electronics Engineers (IEEE). The committee ultimately adopted a standard close to the one Kahan had devised for Intel. Nowadays virtually all computers support what has become known as IEEE floating point. This has greatly improved the portability of scientific application programs across different machines. Aside: The IEEE The Institute of Electrical and Electronic Engineers (IEEE—pronounced “I-Triple-E”) is a professional society that encompasses all of electronic and computer technology. They publish journals, sponsor conferences, and set up committees to define standards on topics ranging from power transmission to software engineering. End Aside. In this section we will see how numbers are represented in the IEEE floating-point format. We will also explore issues of rounding, when a number cannot be represented exactly in the format and hence must be 2.4. FLOATING POINT 67 adjusted upward or downward. We will then explore the mathematical properties of addition, multiplication, and relational operators. Many programmers consider floating point to be, at best, uninteresting and at worst, arcane and incomprehensible. We will see that since the IEEE format is based on a small and consistent set of principles, it is really quite elegant and understandable. 2.4.1 Fractional Binary Numbers A first step in understanding floating-point numbers is to consider binary numbers having fractional values. Let us first examine the more familiar decimal notation. Decimal notation uses a representation of the form: Ñ Ñ ½ ¡ ¡ ¡ ½ ¼ ½ ¾ ¡ ¡ ¡ Ò , where each decimal digit ranges between 0 and 9. This notation represents a number Ñ ½¼ Ò ¢ The weighting of the digits is defined relative to the decimal point symbol ‘ ’: digits to the left are weighted by positive powers of ten, giving integral values, while digits to the right are weighted by negative powers of ten, giving fractional values. For example, ½¾ ¿ ½¼ represents the number ½ ¢ ½¼½ · ¾ ¢ ½¼¼ · ¿ ¢ ½¼ ½ · ¿ ¢ ½¼ ¾ ½¾ ½¼¼ . By analogy, consider a notation of the form Ñ Ñ ½ ¡ ¡ ¡ ½ ¼ ½ ranges between 0 and 1. This notation represents a number Ñ ¾ ¡ ¡ ¡ , where each binary digit, or bit, Ò ¾ ¢ (2.19) Ò The symbol ‘ ’ now becomes a binary point, with bits on the left being weighted by positive powers of two, and those on the right being weighted by negative powers of two. For example, ½¼½ ½½¾ represents the ½ ½ ¿ number ½ ¢ ¾¾ · ¼ ¢ ¾½ · ½ ¢ ¾¼ · ½ ¢ ¾ ½ · ½ ¢ ¾ ¾ ·¼·½· · , ¾ One can readily see from Equation 2.19 that shifting the binary point one position to the left has the effect of dividing the number by two. For example, while ½¼½ ½½¾ represents the number ¿ , ½¼ ½½½¾ represents the ½ number ¾ · ¼ · ¾ · ½ · ½ ¾ . Similarly, shifting the binary point one position to the right has the effect ½ of multiplying the number by two. For example, ½¼½½ ½¾ represents the number · ¼ · ¾ · ½ · ¾ ½½ ½ . ¾ Note that numbers of the form ¼ ½½ ¡ ¡ ¡ ½¾ represent numbers just below ½. For example, sents ¿ . We will use the shorthand notation ½ ¼ ¯ to represent such values. ¼ ½½½½½½¾ repre- Assuming we consider only finite-length encodings, decimal notation cannot represent numbers such as ½ ¿ and exactly. Similarly, fractional binary notation can only represent numbers that can be written Ü ¢ ¾Ý . Other values can only be approximated. For example, although the number ½ can be approximated with increasing accuracy by lengthening the binary representation, we cannot represent it exactly as a fractional binary number: 68 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Representation ¼ ¼¾ ¼ ¼½¾ ¼ ¼½¼¾ ¼ ¼¼½½¾ ¼ ¼¼½½¼¾ ¼ ¼¼½½¼½¾ ¼ ¼¼½½¼½¼¾ ¼ ¼¼½½¼¼½½¾ Value ¼ Decimal ¼ ¼½¼ ¼ ¾ ½¼ ¼ ¾ ½¼ ¼½ ¼½ ½ ¾ ¿ ½ ¿¾ ½¿ ¾ ½¾ ½ ¾ ½¼ ½¼ ¼ ¾¼¿½¾ ½¼ ¼ ¾¼¿½¾ ½¼ ¼½ ¾½ ½¼ Practice Problem 2.23: Fill in the missing information in the table below Fractional Value ½ ¿ ¾¿ ½ ½¼ ½½¼½ ½ ¼½½ ¿ ¿¼ ¾ Binary Rep. ¼ ¼½ Decimal Rep. ¼¾ Practice Problem 2.24: The imprecision of floating point arithmetic can have disastrous effects, as shown by the following (true) story. On February 25, 1991, during the Gulf War, an American Patriot Missile battery in Dharan, Saudi Arabia, failed to intercept an incoming Iraqi Scud missile. The Scud struck an American Army barracks and killed 28 soldiers. The U. S. General Accounting Office (GAO) conducted a detailed analysis of the failure [49] and determined that the underlying cause was an imprecision in a numeric calculation. In this exercise, you will reproduce part of the GAO’s analysis. The Patriot system contains an internal clock, implemented as a counter that is incremented every 0.1 seconds. To determine the time in seconds, the program would multiply the value of this counter by a ½ 24-bit quantity that was a fractional binary approximation to ½¼ . In particular, the binary representation ½ is the nonterminating sequence: of ½¼ ¼ ¼¼¼½½¼¼½½ ¼¼½½ ¡ ¡ ¡¾ where the portion in brackets is repeated indefinitely. The computer approximated ¼ ½ using just the leading bit plus the first 23 bits of this sequence to the right of the binary point. Let us call this number Ü. A. What is the binary representation of Ü ¼ ½? B. What is the approximate decimal value of Ü ¼ ½? 2.4. FLOATING POINT C. The clock starts at 0 when the system is first powered up and keeps counting up from there. In this case, the system had been running for around 100 hours. What was the difference between the time computed by the software and the actual time? D. The system predicts where an incoming missile will appear based on its velocity and the time of the last radar detection. Given that a Scud travels at around 2,000 meters per second, how far off was its prediction? Normally, a slight error in the absolute time reported by a clock reading would not affect a tracking computation. Instead, it should depend on the relative time between two successive readings. The problem was that the Patriot software had been upgraded to use a more accurate function for reading time, but not all of the function calls had been replaced by the new code. As a result, the tracking software used the accurate time for one reading and the inaccurate time for the other [67]. 69 2.4.2 IEEE Floating-Point Representation Positional notation such as considered in the previous section would be very inefficient for representing very large numbers. For example, the representation of ¢ ¾½¼¼ would consist of the bit pattern ½¼½ followed by one hundred ¼’s. Instead, we would like to represent numbers in a form Ü ¢ ¾Ý by giving the values of Ü and Ý . The IEEE floating point standard represents a number in a form Î ´ ¢Å ¢ ½µ × ¾ : ), where the interpre- ¯ ¯ ¯ ¯ ¯ ¯ The sign × determines whether the number is negative (× ½) or positive (× tation of the sign bit for numeric value 0 is handled as a special case. ¼ The significand Å is a fractional binary number that ranges either between ½ and ¾ ¯ or between ¼ and ½ ¯. The exponent weights the value by a (possibly negative) power of two. The bit representation of a floating-point number is divided into three fields to encode these values: The single sign bit s directly encodes the sign ×. The -bit exponent field exp The Ò-bit fraction field frac Ò ½ ¡ ¡ ¡ ½ ¼ encodes the significand Å , but the value encoded also depends on whether or not the exponent field equals 0. ½ ¡ ¡ ¡ ½¼ encodes the exponent . In the single-precision floating-point format (a float in C), fields s, exp, and frac are 1, , and Ò ¾¿ bits each, yielding a 32-bit representation. In the double-precision floating-point format (a double in C), fields s, exp, and frac are 1, ½½, and Ò ¾ bits each, yielding a 64-bit representation. The value encoded by a given bit representation can be divided into three different cases, depending on the value of exp. 70 Normalized Values CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION This is the most common case. They occur when the bit pattern of exp is neither all 0s (numeric value 0) or all 1s (numeric value 255 for single precision, 2047 for double). In this case, the exponent field is interpreted as representing a signed integer in biased form. That is, the exponent value is × where is the unsigned number having bit representation ½ ¡ ¡ ¡ ½ ¼ , and × is a bias value equal to ½ ½ (127 for single precision and 1023 for double). This yields exponent ranges from ½¾ to ·½¾ ¾ for single precision and ½¼¾¾ to ·½¼¾¿ for double precision. The fraction field frac is interpreted as representing the fractional value , where ¼ ½, having binary representation ¼ Ò ½ ¡ ¡ ¡ ½ ¼ , that is, with the binary point to the left of the most significant bit. The significand is defined to be Å ½ · . This is sometimes called an implied leading 1 representation, because we can view Å to be the number with binary representation ½ Ò ½ Ò ¾ ¡ ¡ ¡ ¼ . This representation is a trick for getting an additional bit of precision for free, since we can always adjust the exponent so that significand Å is in the range ½ Å ¾ (assuming there is no overflow). We therefore do not need to explicitly represent the leading bit, since it always equals 1. Denormalized Values When the exponent field is all 0s, the represented number is in denormalized form. In this case, the exponent value is ½ × , and the significand value is Å , that is, the value of the fraction field without an implied leading 1. Aside: Why set the bias this way for denormlized values? Having the exponent value be × rather than simply × might seem counterintuitive. We will see shortly that it provides for smooth transition from denormalized to normalized values.End Aside. ½ Denormalized numbers serve two purposes. First, they provide a way to represent numeric value 0, since with a normalized number we must always have Å ½, and hence we cannot represent 0. In fact the floating-point representation of ·¼ ¼ has a bit pattern of all 0s: the sign bit is 0, the exponent field is all 0s (indicating a denormalized value), and the fraction field is all 0s, giving Å ¼. Curiously, when the sign bit is 1, but the other fields are all 0s, we get the value ¼ ¼. With IEEE floating-point format, the values ¼ ¼ and ·¼ ¼ are considered different in some ways and the same in others. A second function of denormalized numbers is to represent numbers that are very close to 0.0. They provide a property known as gradual underflow in which possible numeric values are spaced evenly near 0.0. Special Values A final category of values occurs when the exponent field is all 1s. When the fraction field is all 0s, the resulting values represent infinity, either ·½ when × ¼, or ½ when × ½. Infinity can represent results that overflow, as when we multiply two very large numbers, or when we divide by zero. When the fraction field is nonzero, the resulting value is called a “Æ Æ ,” short for “Not a Number.” Such values are returned as Ô result of an operation where the result cannot be given as a real number or as infinity, as when the computing ½ or ½ ½. They can also be useful in some applications for representing uninitialized data. 2.4. FLOATING POINT A. Complete Range 71 –∞ –10 –5 Denormalized 0 Normalized +5 Infinity +10 +∞ B. Values between ½ ¼ and ·½ ¼. –0 –1 –0.8 –0.6 –0.4 –0.2 Denormalized 0 +0 +0.2 Infinity +0.4 +0.6 +0.8 +1 Normalized Figure 2.22: Representable Values for 6-Bit Floating-Point Format. There are Ò ¾ significand bits. The bias is 3. ¿ exponent bits and 2.4.3 Example Numbers Figure 2.22 shows the set of values that can be represented in a hypothetical 6-bit format having ¿ ¿ ½ exponent bits and Ò ¾ significand bits. The bias is ¾ ½ ¿. Part A of the figure shows all representable values (other than Æ Æ ). The two infinities are at the extreme ends. The normalized numbers with maximum magnitude are ¦½ . The denormalized numbers are clustered around 0. These can be seen more clearly in part B of the figure, where we show just the numbers between ½ ¼ and ·½ ¼. The two zeros are special cases of denormalized numbers. Observe that the representable numbers are not uniformly distributed—they are denser nearer the origin. Figure 2.23 shows some examples for a hypothetical eight-bit floating-point format having exponent ½ ½ bits and Ò ¿ fraction bits. The bias is ¾ . The figure is divided into three regions representing the three classes of numbers. Closest to 0 are the denormalized numbers, starting with 0 itself. Denormalized ½ numbers in this format have ½ , giving a weight ¾ . The fractions range over the ½ values ¼ , giving numbers Î in the range ¼ to ¢ . ½¾ , and the fractions also range ½ ½·¼ ½ to ½ · , giving The smallest normalized numbers in this format also have ½ ½ over the values ¼ . However, the significands then range from numbers Î in the range ½¾ to ½½¾ . Observe the smooth transition between the largest denormalized number ½¾ and the smallest normalized number ½¾ . This smoothness is due to our definition of for denormalized values. By making it ½ × rather than × , we compensate for the fact that the significand of a denormalized number does not have an implied leading 1. As we increase the exponent, we get successively larger normalized values, passing through 1.0 and then to the largest normalized number. This number has exponent , giving a weight ¾ ½¾ . The fraction ½ equals giving a significand Å . Thus the numeric value is Î ¾ ¼. Going beyond this overflows to ·½. 72 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Description Zero Smallest Pos. 0 0 0 0 0 0 0 0 0 0 0 0 0 Bit Rep. 0000 000 0000 001 0000 010 0000 011 ¼ ¼ ¼ ¼ ¡¡¡ ½ ½ Å ¼ ¼ Î ¼ ½ ¾ ¿ ½ ¾ ¿ ½ ½¾ ¾ ½¾ ¿ ½¾ Largest Denorm. Smallest Norm. 0000 0000 0001 0001 0110 0110 0111 0111 0111 ¡¡¡ 110 111 000 001 ¼ ¼ ½ ½ ½¾ ½¾ ¼ ½ ½¾ ½¾ ½ ½ ½ ½ ½ ½ ½ One ¡¡¡ 110 111 000 001 010 ½ ½ ¼ ¼ ¼ ¼ ½ ¾ ½¼ ½¼ Largest Norm. Infinity 0 1110 110 0 1110 111 0 1111 000 ½ ½ ¾¾ ¾¼ · – – – – ½ expo- Figure 2.23: Example Nonnegative Values for eight-bit Floating-Point Format. There are nent bits and Ò ¿ significand bits. The bias is . 2.4. FLOATING POINT 73 One interesting property of this representation is that if we interpret the bit representations of the values in Figure 2.23 as unsigned integers, they occur in ascending order, as do the values they represent as floatingpoint numbers. This is no accident—the IEEE format was designed so that floating-point numbers could be sorted using an integer-sorting routine. A minor difficulty is in dealing with negative numbers, since they have a leading one, and they occur in descending order, but this can be overcome without requiring floating-point operations to perform comparisons (see Problem 2.47). Practice Problem 2.25: Consider a 5-bit floating-point representation based on the IEEE floating-point format, with one sign bit, ¾), and two fraction bits (Ò ¾). The exponent bias is ¾¾ ½ ½ ½. two exponent bits ( The table below enumerates the entire nonnegative range for this 5-bit floating-point representation. Fill in the blank table entries using the following directions: : The value represented by considering the exponent field to be an unsigned integer. : The value of the exponent after biasing. : The value of the fraction. Å Î : The value of the significand. : The numeric value represented. Express the values of , Å and Î as fractions of the form Ü . You need not fill in entries marked “—”. Bits 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 00 00 00 01 01 01 01 10 10 10 10 11 11 11 11 00 01 10 11 00 01 10 11 00 01 10 11 00 01 10 11 Å Î ¾ ½ ¼ — — — — — — — — — — — — — — — — · ÆÆ ÆÆ ÆÆ ½ Figure 2.24 shows the representations and numeric values of some important single and double-precision floating-point numbers. As with the eight-bit format shown in Figure 2.23 we can see some general properties for a floating-point representation with a -bit exponent and an Ò-bit fraction: 74 Description Zero Smallest denorm. Largest denorm. Smallest norm. One Largest norm. exp ¼¼ ¼¼ ¼¼ ¼¼ ¼½ ½½ CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION frac ¼ ¼ ½ ¼ ¼ ½ ¡¡¡ ¡¡¡ ¡¡¡ ¡¡¡ ¡¡¡ ¡¡¡ ¼¼ ¼¼ ¼¼ ¼½ ½½ ½¼ ¡¡¡ ¡¡¡ ¡¡¡ ¡¡¡ ¡¡¡ ¡¡¡ Single Precision Value Decimal Double Precision Value Decimal ¾ ´½ ¼¼ ¼½ ½½ ¼¼ ¼¼ ½½ ¾¿ ¢ ¾ ½¾ ½¾ ´½ ¯µ ¢ ¾ ½¾ ½¢¾ ¾ ´¾ ¼ ½ ½¾ ½¾ ¢ ¯ ¢ ½ ¾ µ ¼ ¢ ¢ ¢ ¼¼ ½¼ ¿ ½¼ ¿ ½¼ ½¼ ¾ ½¾ ¿ ¢ ½¼ ¿ ´¾ ¢ ¯ ¢ ¢ ¢ ¯ ¢ ¾ ¾ µ ¾ ½ ¾ ½ ¾ ¼ ½¼¾¾ ½¼¾¾ ¾¾ ¾¾ ½¼¾¾ ¼ ¢ ¢ ¢ ¼¼ ¿¾ ¿¼ ½¼ ¿¼ ½¼ ½¼ ½¼ µ ¾ ½¼¾¿ ½ ¢ ½¼ ¿¼ Figure 2.24: Examples of Nonnegative Floating-Point Numbers. ¯ ¯ ¯ ¯ ¯ ¯ The value ·¼ ¼ always has a bit representation of all ¼’s. The smallest positive denormalized value has a bit representation consisting of a 1 in the least signif Ò and an icant bit position and otherwise all 0s. It has a fraction (and significand) value Å ¾ ½ ·¾ exponent value ¾ ½ · ¾. The numeric value is therefore Î ¾ Ò ¾ . The largest denormalized value has a bit representation consisting of an exponent field of all 0s and Ò (which we a fraction field of all 1s. It has a fraction (and significand) value Å ½ ¾ have written ½ ¯) and an exponent value ¾ ½ · ¾. The numeric value is therefore Î Ò µ ¢ ¾ ¾ ½ ·¾ , which is just slightly smaller than the smallest normalized value. ´½ ¾ The smallest positive normalized value has a bit representation with a 1 in the least signicant bit of the exponent field and otherwise all 0s. It has a significand value Å ½ and an exponent value ¾ ½ · ¾. The numeric value is therefore Î ¾ ¾ ½ ·¾. The value ½ ¼ has a bit representation with all but the most significant bit of the exponent field equal to 1 and all other bits equal to 0. Its significand value is Å ½ and its exponent value is ¼. The largest normalized value has a bit representation with a sign bit of 0, the least significant bit of Ò , giving the exponent equal to 0, and all other bits equal to 1. It has a fraction value of ½ ¾ Ò (which we have written ¾ ¯). It has an exponent value ½ ½, a significand Å ¾ ¾ ¾ Ò µ ¢ ¾¾ ½ ½ ´½ ¾ Ò ½ µ ¢ ¾¾ ½ . giving a numeric value Î ´¾ ¾ Practice Problem 2.26: A. For a floating-point format with a -bit exponent and an Ò-bit fraction, give a formula for the smallest positive integer that cannot be represented exactly (because it would require an Ò · ½-bit fraction to be exact). , Ò ¾¿)? B. What is the numeric value of this integer for single-precision format ( 2.4.4 Rounding Floating-point arithmetic can only approximate real arithmetic, since the representation has limited range and precision. Thus, for a value Ü, we generally want a systematic method of finding the “closest” matching 2.4. FLOATING POINT Mode Round-to-even Round-toward-zero Round-down Round-up $1.40 $1 $1 $1 $2 $1.60 $2 $1 $1 $2 $1.50 $2 $1 $1 $2 $2.50 $2 $2 $2 $3 $–1.50 $–2 $–1 $–2 $–1 75 Figure 2.25: Illustration of Rounding Modes for Dollar Rounding. The first rounds to a nearest value, while the other three bound the result above or below. value ܼ that can be represented in the desired floating-point format. This is the task of the rounding operation. The key problem is to define the direction to round a value that is halfway between two possibilities. For example, if I have $1.50 and want to round it to the nearest dollar, should the result be $1 or $2? An alternative approach is to maintain a lower and an upper bound on the actual number. For example, we could determine representable values Ü and Ü· such that the value Ü is guaranteed to lie between them: Ü Ü Ü· . The IEEE floating-point format defines four different rounding modes. The default method finds a closest match, while the other three can be used for computing upper and lower bounds. Figure 2.25 illustrates the four rounding modes applied to the problem of rounding a monetary amount to the nearest whole dollar. Round-to-even (also called round-to-nearest) is the default mode. It attempts to find a closest match. Thus, it rounds $1.40 to $1 and $1.60 to $2, since these are the closest whole dollar values. The only design decision is to determine the effect of rounding values that are halfway between two possible results. Round-to-even mode adopts the convention that it rounds the number either upward or downward such that the least significant digit of the result is even. Thus, it rounds both $1.50 and $2.50 to $2. The other three modes produce guaranteed bounds on the actual value. These can be useful in some numerical applications. Round-toward-zero mode rounds positive numbers downward and negative numbers upward, giving a value Ü such that Ü Ü . Round-down mode rounds both positive and negative numbers downward, giving a value Ü such that Ü Ü. Round-up mode rounds both positive and negative numbers upward, giving a value Ü· such that Ü Ü· . Round-to-even at first seems like it has a rather arbitrary goal—why is there any reason to prefer even numbers? Why not consistently round values halfway between two representable values upward? The problem with such a convention is that one can easily imagine scenarios in which rounding a set of data values would then introduce a statistical bias into the computation of an average of the values. The average of a set of numbers that we rounded by this means would be slightly higher than the average of the numbers themselves. Conversely, if we always rounded numbers halfway between downward, the average of a set of rounded numbers would be slightly lower than the average of the numbers themselves. Rounding toward even numbers avoids this statistical bias in most real-life situations. It will round upward about 50% of the time and round downward about 50% of the time. Round-to-even rounding can be applied even when we are not rounding to a whole number. We simply consider whether the least significant digit is even or odd. For example, suppose we want to round decimal numbers to the nearest hundredth. We would round 1.2349999 to 1.23 and 1.2350001 to 1.24, regardless of rounding mode, since they are not halfway between 1.23 and 1.24. On the other hand, we would round both 1.2350000 and 1.2450000 to 1.24, since four is even. 76 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Similarly, round-to-even rounding can be applied to binary fractional numbers. We consider least significant bit value 0 to be even and 1 to be odd. In general, the rounding mode is only significant when we have a bit pattern of the form ¡¡¡ ¡ ¡ ¡ ½¼¼ ¡ ¡ ¡, where and denote arbitary bit values with the rightmost being the position to which we wish to round. Only bit patterns of this form denote values that are halfway between two possible results. As examples, consider the problem of rounding values to ¿ the nearest quarter (i.e., 2 bits to the right of the binary point). We would round ½¼ ¼¼¼½½¾ (¾ ¿¾ ) down ¿ ½ to ½¼ ¼¼¾ (¾), and ½¼ ¼¼½½¼¾ (¾ ½ ) up to ½¼ ¼½¾ (¾ ), because these values are not halfway between two possible values. We would round ½¼ ½½½¼¼¾ (¾ ) up to ½½ ¼¼¾ (¿) and ½¼ ½¼½¼¼¾ down to ½¼ ½¼¾ (¾ ½ ), ¾ since these values are halfway between two possible results, and we prefer to have the least significant bit equal to zero. 2.4.5 Floating-Point Operations The IEEE standard specifies a simple rule for determining the result of an arithmetic operation such as addition or multiplication. Viewing floating-point values Ü and Ý as real numbers, and some operation ¬ defined over real numbers, the computation should yield ÊÓÙÒ ´Ü ¬ Ý µ, the result of applying rounding to the exact result of the real operation. In practice, there are clever tricks floating-point unit designers use to avoid performing this exact computation, since the computation need only be sufficiently precise to guarantee a correctly rounded result. When one of the arguments is a special value such as ¼, ½ or Æ Æ , the standard specifies conventions that attempt to be reasonable. For example ½ ¼ is defined to yield ½, while ½ · ¼ is defined to yield ·½. One strength of the IEEE standard’s method of specifying the behavior of floating-point operations is that it is independent of any particular hardware or software realization. Thus, we can examine its abstract mathematical properties without considering how it is actually implemented. We saw earlier that integer addition, both unsigned and two’s complement, forms an Abelian group. Addition over real numbers also forms an Abelian group, but we must consider what effect rounding has on these properties. Let us define Ü +f Ý to be ÊÓÙÒ ´Ü · Ý µ. This operation is defined for all values of Ü and Ý , although it may yield infinity even when both Ü and Ý are real numbers due to overflow. The operation is commutative, with Ü +f Ý Ý +f Ü for all values of Ü and Ý. On the other hand, the operation is not associative. For example, with single-precision floating point the expression (3.14+1e10)-1e10 would evaluate to 0.0—the value 3.14 would be lost due to rounding. On the other hand, the expression 3.14+(1e10-1e10) would evaluate to 3.14. As with an Abelian group, most values have inverses under floating-point addition, that is, Ü +f Ü ¼. The exceptions are infinities (since ·½ ½ Æ Æ ), and Æ Æ ’s, since Æ Æ +f Ü Æ Æ for any Ü. The lack of associativity in floating-point addition is the most important group property that is lacking. It has important implications for scientific programmers and compiler writers. For example, suppose a compiler is given the following code fragment: x = a + b + c; y = b + c + d; The compiler might be tempted to save one floating-point addition by generating the code: t = b + c; 2.4. FLOATING POINT x = a + t; y = t + d; 77 However, this computation might yield a different value for x than would the original, since it uses a different association of the addition operations. In most applications, the difference would be so small as to be inconsequential. Unfortunately, compilers have no way of knowing what trade-offs the user is willing to make between efficiency and faithfulness to the exact behavior of the original program. As a result, they tend to be very conservative, avoiding any optimizations that could have even the slightest effect on functionality. On the other hand, floating-point addition satisfies the following monotonicity property: if then Ü· Ü · for any values of , , and Ü other than Æ Æ . This property of real (and integer) addition is not obeyed by unsigned or two’s complement addition. Floating-point multiplication also obeys many of the properties one normally associates with multiplication, namely those of a ring. Let us define Ü *f Ý to be ÊÓÙÒ ´Ü ¢ Ý µ. This operation is closed under multiplication (although possibly yielding infinity or Æ Æ ), it is commutative, and it has 1.0 as a multiplicative identity. On the other hand, it is not associative due to the possibility of overflow or the loss of precision due to rounding. For example, with single-precision floating point, the expression (1e20*1e20)*1e-20 will evaluate to ·½, while 1e20*(1e20*1e-20) will evaluate to 1e20. In addition, floating-point multiplication does not distribute over addition. For example, with single-precision floating point, the expression 1e20*(1e20-1e20) will evaluate to 0.0, while 1e20*1e20-1e20*1e20 will evaluate to NaN. On the other hand, floating-point multiplication satisfies the following monotonicity properties for any values of , , and other than Æ Æ : and and ¼ ¼ µ µ *f *f *f *f In addition, we are also guaranteed that *f ¼, as long as Æ Æ . As we saw earlier, none of these monotonicity properties hold for unsigned or two’s complement multiplication. This lack of associativity and distributivity is of serious concern to scientific programmers and to compiler writers. Even such a seemingly simple task as writing code to determine whether two lines intersect in three-dimensional space can be a major challenge. 2.4.6 Floating Point in C C provides two different floating-point data types: float and double. On machines that support IEEE floating point, these data types correspond to single and double-precision floating point. In addition, the machines use the round-to-even rounding mode. Unfortunately, since the C standard does require the machine use IEEE floating point, there are no standard methods to change the rounding mode or to get special values such as ¼, ·½, ½, or Æ Æ . Most systems provide a combination of include (‘.h’) files and procedure libraries to provide access to these features, but the details vary from one system to another. For example, the GNU compiler GCC defines macros INFINITY (for ·½) and NAN (for Æ Æ ) when the following sequence occurs in the program file: #define _GNU_SOURCE 1 78 #include <math.h> CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Practice Problem 2.27: Fill in the following macro definitions to generate the double-precision values ·½, ½, and ¼. #define POS_INFINITY #define NEG_INFINITY #define NEG_ZERO #endif You cannot use any include files (such as math.h), but you can make use of the fact that the largest finite number that can be represented with double precision is around ½ ¢ ½¼¿¼ . When casting values between int, float, and double formats, the program changes the numeric values and the bit representations as follows (assuming a 32-bit int): ¯ ¯ ¯ ¯ From int to float, the number cannot overflow, but it may be rounded. From int or float to double, the exact numeric value can be preserved because double has both greater range (i.e., the range of representable values), as well as greater precision (i.e., the number of significant bits). From double to float, the value can overflow to ·½ or ½, since the range is smaller. Otherwise it may be rounded since the precision is smaller. From float or double to int the value will be truncated toward zero. For example ½ will be converted to ½, while ½ will be converted to ½. Note that this behavior is very different from rounding. Furthermore, the value may overflow. The C standard does not specify a fixed result for this case, but on most machines the result will either be ÌÅ Ü Û or ÌÅ Ò Û , where Û is the number of bits in an int. Aside: Ariane 5: the high cost of floating-point overflow Converting large floating-point numbers to integers is a common source of programming errors. Such an error had particularly disastrous consequences for the maiden voyage of the Ariane 5 rocket, on June 4, 1996. Just 37 seconds after lift-off, the rocket veered off its flight path, broke up, and exploded. On board the rocket were communication satellites, valued at $500 million. A later investigation [46] showed that the computer controlling the inertial navigation system had sent invalid data to the computer controlling the engine nozzles. Instead of sending flight control information, it had sent a diagnostic bit pattern indicating that, in an effort to convert a 64-bit floating point number into a 16-bit signed integer, an overflow had been encountered. The value that overflowed measured the horizontal velocity of the rocket, which could be more than five times higher than that achieved by the earlier Ariane 4 rocket. In the design of the Ariane 4 software, they had carefully analyzed the numeric values and determined that the horizontal velocity would never overflow a 16-bit number. Unfortunately, they simply reused this part of the software in the Ariane 5 without checking the assumptions on which it had been based. End Aside. 2.5. SUMMARY Practice Problem 2.28: Assume variables x, f, and d are of type int, float, and double, respectively. Their values are arbitrary, except that neither f nor d equals ·½, ½, or Æ Æ . For each of the following C expressions, either argue that it will always be true (i.e., evaluate to 1) or give a value for the variables such that it is not true (i.e., evaluates to 0). A. x == (int)(float) x B. x == (int)(double) x C. f == (float)(double) f D. d == (float) d E. f == -(-f) F. 2/3 == 2/3.0 G. (d >= 0.0) || ((d*2) < 0.0) H. (d+f)-d == f 79 2.5 Summary Computers encode information as bits, generally organized as sequences of bytes. Different encodings are used for representing integers, real numbers, and character strings. Different models of computers use different conventions for encoding numbers and for ordering the bytes within multibyte data. The C language is designed to accomodate a wide range of different implementations in terms of word sizes and numeric encodings. Most current machines have 32-bit word sizes, although high-end machines increasingly have 64-bit words. Most machines use two’s complement encoding of integers and IEEE encoding of floating point. Understanding these encodings at the bit level, and the mathematical characteristics of the arithmetic operations is important for writing programs that operate correctly over the full range of numeric values. The C standard dictates that when casting between signed and unsigned integers, the underlying bit pattern should not change. On a two’s complement machine, this behavior is characterized by functions Ì¾Í Û and Í¾Ì Û , for a Û-bit value. The implicit casting of C gives results that many programmers do not anticipate, often leading to program bugs. Due to the finite lengths of the encodings, computer arithmetic has properties quite different from conventional integer and real arithmetic. The finite length can cause numbers to overflow, when they exceed the range of the representation. Floating point values can also underflow, when they are so close to ¼ ¼ that they are changed to zero. The finite integer arithmetic implemented by C, as well as most other programming languages, has some peculiar properties compared to true integer arithmetic. For example, the expression x*x can evaluate to a negative number due to overflow. Nonetheless, both unsigned and two’s complement arithmetic satisfies the properties of a ring. This allows compilers to do many optimizations. For example, in replacing the expression 7*x by (x<<3)-x, we make use of the associative, commutative and distributive properties, along with the relationship between shifting and multiplying by powers of two. 80 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Floating point representations approximate real numbers by encoding numbers of the form Ü ¢ ¾Ý . The most common floating point representation was defined by IEEE Standard 754. It provides for several different precisions, with the most common being single (32 bits) and double (64 bits). IEEE floating point also has representations for special values ½ and not-a-number. Floating point arithmetic must be used very carefully, since it has only limited range and precision, and since it does not obey common mathematical properties such as associativity. We have seen several clever ways to exploit combinations bit-level operations and arithmetic operations. For example, we saw that with two’s complement arithmetic, ˜x+1 is equivalent to -x. As another example, suppose we want a bit pattern of the form ¼ ¼½ ½ , consisting of Û 0s followed by 1s. Such bit patterns are useful for masking operations. This pattern can be generated by the C expression (1<<k)1, exploiting the property that the desired bit pattern has numeric value ¾ ½. For example, the expression (1<<8)-1 will generate the bit pattern 0xFF. Bibliographic Notes Reference books on C [37, 30] discuss properties of the different data types and operations. The C standard does not specify details such as precise word sizes or numeric encodings. Such details are intentionally omitted to make it possible to implement C on a wide range of different machines. Several books have been written giving advice to C programmers [38, 47] that warn about problems with overflow, implicit casting to unsigned, and some of the other pitfalls we have covered in this chapter. These books also provide helpful advice on variable naming, coding styles, and code testing. Books on Java (we recommend the one coauthored by James Gosling, the creator of the language [1]) describe the data formats and arithmetic operations supported by Java. Most books on logic design [82, 36] have a section on encodings and arithmetic operations. Such books describe different ways of implementing arithmetic circuits. Appendix A of Hennessy and Patterson’s computer architecture textbook [31] does a particularly good job of describing different encodings (including IEEE floating point) as well as different implementation techniques. Overton’s book on IEEE floating point [53] provides a detailed description of the format as well as the properties from the perspective of a numerical applications programmer. Homework Problems Homework Problem 2.29 [Category 1]: Compile and run the sample code that uses show bytes (file show-bytes.c) on different machines to which you have access. Determine the byte orderings used by these machines. Homework Problem 2.30 [Category 1]: Try running the code for show bytes for different sample values. Homework Problem 2.31 [Category 1]: Write procedures show_short, show_long, and show_double that print the byte representations of 2.5. SUMMARY 81 C objects of types short int, long int, and double respectively. Try these out on several machines. Homework Problem 2.32 [Category 2]: Write a procedure is_little_endian that will return 1 when compiled and run on a little-endian machine, and will return 0 when compiled and run on a big-endian machine. This program should run on any machine, regardless of its word size. Homework Problem 2.33 [Category 2]: Write a C expression that will yield a word consisting of the least significant byte of x, and the remaining bytes of y. For operands x 0x89ABCDEF and y 0x76543210, this would give 0x765432EF. Homework Problem 2.34 [Category 2]: Using only bit-level and logical operations, write C expressions that yield 1 for the described condition and 0 otherwise. Your code should work on a machine with any word size. Assume x is an integer. A. Any bit of x equals 1. B. Any bit of x equals 0. C. Any bit in the least significant byte of x equals 1. D. Any bit in the least significant byte of x equals 0. Homework Problem 2.35 [Category 3]: Write a procedure int_shifts_are_arithmetic() that yields 1 when run a machine that uses arithmetic right shifts for int’s and 0 otherwise. Your code should work on a machine with any word size. Test your code on several machines. Write and test a procedure unsigned_shifts_are_arithmetic() that determines the form of shifts used for unsigned int’s. Homework Problem 2.36 [Category 2]: You are given the task of writing a procedure int_size_is_32() that yields 1 when run on a machine for which an int is 32 bits, and yields 0 otherwise. Here is a first attempt: 1 2 3 4 5 6 7 8 9 10 11 12 /* The following code does not run properly on some machines */ int bad_int_size_is_32() { /* Set most significant bit (msb) of 32-bit machine */ int set_msb = 1 << 31; /* Shift past msb of 32-bit word */ int beyond_msb = 1 << 32; /* set_msb is nonzero when word size >= 32 beyond_msb is zero when word size <= 32 return set_msb && !beyond_msb; } */ 82 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION When compiled and run on a 32-bit SUN SPARC, however, this procedure returns 0. The following compiler message gives us an indication of the problem: warning: left shift count >= width of type A. In what way does our code fail to comply with the C standard? B. Modify the code to run properly on any machine for which int’s are at least 32 bits. C. Modify the code to run properly on any machine for which int’s are at least 16 bits. Homework Problem 2.37 [Category 1]: You just started working for a company that is implementing a set of procedures to operate on a data structure where four signed bytes are packed into a 32-bit unsigned. Bytes within the word are numbered from 0 (least significant) to 3 (most significant). You have been assigned the task of implementing a function for a machine using two’s complement arithmetic and arithmetic right shifts with the following prototype: /* Declaration of data type where 4 bytes are packed into an unsigned */ typedef unsigned packed_t; /* Extract byte from word. Return as signed integer */ int xbyte(packed_t word, int bytenum); That is, the function will extract the designated byte and sign extend it to be a 32-bit int. Your predecessor (who was fired for his incompetence) wrote the following code: /* Failed attempt at xbyte */ int xbyte(packed_t word, int bytenum) { return (word >> (bytenum << 3)) & 0xFF; } A. What is wrong with this code? B. Give a correct implementation of the function that uses only left and right shifts, along with one subtraction. Homework Problem 2.38 [Category 1]: Fill in the following table showing the effects of complementing and incrementing several 5-bit vectors, in the style of Figure 2.20. Show both the bit vectors and the numeric values. 2.5. SUMMARY 83 Ü ¼½½¼½ ¼½½½½ ½½¼¼¼ ½½½½½ ½¼¼¼¼ ˜Ü Ò Ö ´˜Üµ Homework Problem 2.39 [Category 2]: Show that first decrementing and then complementing is equivalent to complementing and then incrementing. That is, for any signed value x, the C expressions -x, ˜x+1, and ˜(x-1) yield identical results. What mathematical properties of two’s complement addition does your derivation rely on? Homework Problem 2.40 [Category 3]: Suppose we want to compute the complete ¾Û-bit representation of Ü ¡ Ý , where both Ü and Ý are unsigned, on a machine for which data type unsigned is Û bits. The low-order Û bits of the product can be computed with the expression x*y, so we only require a procedure with prototype unsigned int unsigned_high_prod(unsigned x, unsigned y); that computes the high-order Û bits of Ü ¡ Ý for unsigned variables. We have access to a library function with prototype: int signed_high_prod(int x, int y); that computes the high-order Û bits of Ü ¡ Ý for the case where Ü and Ý are in two’s complement form. Write code calling this procedure to implement the function for unsigned arguments. Justify the correctness of your solution. [Hint:] Look at the relationship between the signed product derivation of Equation 2.18. Homework Problem 2.41 [Category 2]: Suppose we are given the task of generating code to multiply integer variable x by various different constant factors à . To be efficient we want to use only the operations +, -, and <<. For the following values of à , write C expressions to perform the multiplication using at most three operations per expression. A. B. C. D. Ü ¡ Ý and the unsigned product ܼ ¡ ݼ in the à à à à : : ½ : : 84 CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Homework Problem 2.42 [Category 2]: Write C expressions to generate the following bit patterns, where represents repetitions of symbol . Assume a Û-bit data type. Your code may contain references to parameters j and k, representing the values of and , but not a parameter representing Û. A. B. ½ ¼ Û ¼ . ½¼ Û . Suppose we number the bytes in a Û-bit word from 0 (least significant) to Û ½ (most significant). Write code for the following C function, that will return an unsigned value in which byte i of argument x has been replaced by byte b. unsigned replace_byte (unsigned x, int i, unsigned char b); Homework Problem 2.43 [Category 2]: Here are some examples showing how the function should work replace_byte(0x12345678, 2, 0xAB) --> 0x12AB5678 replace_byte(0x12345678, 0, 0xAB) --> 0x123456AB Homework Problem 2.44 [Category 3]: Fill in code for the following C functions. Function srl performs a logical right shift using an arithmetic right shift (given by value xsra), followed by other operations not including right shifts or division. Function sra performs an arithmetic right shift using a logical right shift (given by value xsrl), followed by other operations not including right shifts or division. You may assume that int’s are 32-bits long. The shift amount k can range from 0 to 31. unsigned srl(unsigned x, int k) { /* Perform shift arithmetically */ unsigned xsra = (int) x >> k; /* ... */ } int sra(int x, int k) { /* Perform shift logically */ int xsrl = (unsigned) x >> k; 2.5. SUMMARY 85 /* ... */ } Homework Problem 2.45 [Category 2]: Assume we are running code on a 32-bit machine using two’s complement arithmetic for signed variables. The variables are declared and initialized as follows: int x = foo(); int y = bar(); unsigned ux = x; unsigned uy = y; /* Arbitrary value */ /* Arbitrary value */ For each of the following C expressions, either (1) argue that it is true (i.e., evaluates to 1) for all values of x and y, or (2) give example values of x and y for which it is false (i.e., evaluates to 0.) A. (x >= 0) || ((2*x) < 0) B. (x & 7) != 7 || (x<<30 < 0) C. (x * x) >= 0 D. x < 0 || -x <= 0 E. x > 0 || -x >= 0 F. x*y == ux*uy G. ˜x*y + uy*ux == -y Homework Problem 2.46 [Category 2]: Consider numbers having a binary representation consisting of an infinite string of the form ¼ Ý Ý Ý Ý Ý Ý ¡ ¡ ¡, where Ý is a -bit sequence. For example, the binary representation of ½ is ¼ ¼½¼½¼½¼½ ¡ ¡ ¡ (Ý ¼½), while ¿ the representation of ½ is ¼ ¼¼½½¼¼½½¼¼½½ ¡ ¡ ¡ (Ý ¼¼½½). A. Let ¾Í ´Ý µ, that is, the number having binary representation Ý . Give a formula in terms of and for the value represented by the infinite string. [Hint: Consider the effect of shifting the binary point positions to the right.] B. What is the numeric value of the string for the following values of Ý ? (a) ¼¼½ 86 (b) (c) ½¼¼½ ¼¼¼½½½ CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION Homework Problem 2.47 [Category 1]: Fill in the return value for the following procedure that tests whether its first argument is greater than or equal to its second. Assume the function f2u returns an unsigned 32-bit number having the same bit representation as its floating-point argument. You can assume that neither argument is Æ Æ . The two flavors of zero: ·¼ and ¼ are considered equal. int float_ge(float x, float y) { unsigned ux = f2u(x); unsigned uy = f2u(y); /* Get the sign bits */ unsigned sx = ux >> 31; unsigned sy = uy >> 31; /* Give an expression using only ux, uy, sx, and sy */ return /* ... */ ; } Homework Problem 2.48 [Category 1]: Given a floating-point format with a -bit exponent and an Ò-bit fraction, give formulas for the exponent , significand Å , the fraction , and the value Î for the following quantities. In addition, describe the bit representation. A. The number ¼ . B. The largest odd integer that can be represented exactly. C. The reciprocal of the smallest positive normalized value. Homework Problem 2.49 [Category 1]: Intel-compatible processors also support an “extended precision” floating-point format with an 80-bit word divided into a sign bit, ½ exponent bits, a single integer bit, and Ò ¿ fraction bits. The integer bit is an explicit copy of the implied bit in the IEEE floating-point representation. That is, it equals 1 for normalized values and 0 for denormalized values. Fill in the following table giving the approximate values of some “interesting” numbers in this format: 2.5. SUMMARY Description Smallest denormalized Smallest normalized Largest normalized Extended Precision Value Decimal 87 Homework Problem 2.50 [Category 1]: Consider a 16-bit floating-point representation based on the IEEE floating-point format, with one sign bit, seven exponent bits ( ), and eight fraction bits (Ò ). The exponent bias is ¾ ½ ½ ¿. Fill in the table below for the following numbers, with the following instructions for each column: Hex: The four hexadecimal digits describing the encoded form. Å: : The value of the significand. This should be a number of the form Ü or Ü , where Ü is an integer, Ý and Ý is an integral power of 2. Examples include: 0, , and ¾½ . The integer value of the exponent. The numeric value represented. Use the notation Ü or Ü ¢ ¾Þ , where Ü and Þ are integers. Î: As an example, to represent the number ¾ , we would have × ¼, Å , and ½. Our number would therefore have an exponent field of 0x40 (decimal value ¿ · ½ ) and a significand field 0xC0 (binary ½½¼¼¼¼¼¼¾ ), giving a hex representation 40C0. You need not fill in entries marked “—”. Description Hex ½ Å Î — —- ¼ Smallest value 256 Largest Denormalized ½ — — — — Number with hex representation 3AA0 Homework Problem 2.51 [Category 1]: You have been assigned the task of writing a C function to compute a floating-point representation of ¾Ü . You realize that the best way to do this is to directly construct the IEEE single-precision representation of the result. When Ü is too small, your routine will return ¼ ¼. When Ü is too large, it will return ·½. Fill in the blank portions of the following code to compute the correct result. Assume the function u2f returns a floating-point value having an identical bit representation as its unsigned argument. 88 float fpwr2(int x) CHAPTER 2. REPRESENTING AND MANIPULATING INFORMATION /* Result exponent and significand */ unsigned exp, sig; unsigned u; if (x < ______) /* Too small. Return 0.0 */ exp = ____________; sig = ____________; else if (x < ______) /* Denormalized result */ exp = ____________; sig = ____________; else if (x < ______) /* Normalized result. */ exp = ____________; sig = ____________; else /* Too big. Return +oo */ exp = ____________; sig = ____________; /* Pack exp and sig into 32 bits */ u = exp << 23 | sig; /* Return as float */ return u2f(u); Homework Problem 2.52 [Category 1]: ¾¾ Around 250 B.C., the Greek mathematician Archimedes proved that ¾¾¿ . Had he had access ½ to a computer and the standard library <math.h>, he would have been able to determine that the singleprecision floating-point approximation of has the hexadecimal representation 0x40490FDB. Of course, all of these are just approximations, since is not rational. A. What is the fractional binary number denoted by this floating-point value? B. What is the fractional binary representation of ¾¾ ? [Hint: See Problem 2.46]. diverge? C. At what bit position (relative to the binary point) do these two approximations to Chapter 3 Machine-Level Representation of C Programs When programming in a high-level language, such as C, we are shielded from the detailed, machine-level implementation of our program. In contrast, when writing programs in assembly code, a programmer must specify exactly how the program manages memory and the low-level instructions the program uses to carry out the computation. Most of the time, it is much more productive and reliable to work at the higher level of abstraction provided by a high-level language. The type checking provided by a compiler helps detect many program errors and makes sure we reference and manipulate data in consistent ways. With modern, optimizing compilers, the generated code is usually at least as efficient as what a skilled, assembly-language programmer would write by hand. Best of all, a program written in a high-level language can be compiled and executed on a number of different machines, whereas assembly code is highly machine specific. Even though optimizing compilers are available, being able to read and understand assembly code is an important skill for serious programmers. By invoking the compiler with appropriate flags, the compiler will generate a file showing its output in assembly code. Assembly code is very close to the actual machine code that computers execute. Its main feature is that it is in a more readable textual format, compared to the binary format of object code. By reading this assembly code, we can understand the optimization capabilities of the compiler and analyze the underlying inefficiencies in the code. As we will experience in Chapter 5, programmers seeking to maximize the performance of a critical section of code often try different variations of the source code, each time compiling and examining the generated assembly code to get a sense of how efficiently the program will run. Furthermore, there are times when the layer of abstraction provided by a high-level language hides information about the run-time behavior of a program that we need to understand. For example, when writing concurrent programs using a thread package, as covered in Chapter 11, it is important to know what type of storage is used to hold the different program variables. This information is visible at the assembly code level. The need for programmers to learn assembly code has shifted over the years from one of being able to write programs directly in assembly to one of being able to read and understand the code generated by optimizing compilers. In this chapter, we will learn the details of a particular assembly language and see how C programs get compiled into this form of machine code. Reading the assembly code generated by a compiler involves a different set of skills than writing assembly code by hand. We must understand the transformations typical 89 90 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS compilers make in converting the constructs of C into machine code. Relative to the computations expressed in the C code, optimizing compilers can rearrange execution order, eliminate unneeded computations, replace slow operations such as multiplication by shifts and adds, and even change recursive computations into iterative ones. Understanding the relation between source code and the generated assembly can often be a challenge—much like putting together a puzzle having a slightly different design than the picture on the box. It is a form of reverse engineering—trying to understand the process by which a system was created by studying the system and working backward. In this case, the system is a machine-generated, assembly-language program, rather than something designed by a human. This simplifies the task of reverse engineering, because the generated code follows fairly regular patterns, and we can run experiments, having the compiler generate code for many different programs. In our presentation, we give many examples and provide a number of exercises illustrating different aspects of assembly language and compilers. This is a subject matter where mastering the details is a prerequisite to understanding the deeper and more fundamental concepts. Spending time studying the examples and working through the exercises will be well worthwhile. We give a brief history of the Intel architecture. Intel processors have grown from rather primitive 16-bit processors in 1978 to the mainstream machines for today’s desktop computers. The architecture has grown correspondingly with new features added and the 16-bit architecture transformed to support 32-bit data and addresses. The result is a rather peculiar design with features that make sense only when viewed from a historical perspective. It is also laden with features providing backward compatibility that are not used by modern compilers and operating systems. We will focus on the subset of the features used by GCC and Linux. This allows us to avoid much of the complexity and arcane features of IA32. Our technical presentation starts a quick tour to show the relation between C, assembly code, and object code. We then proceed to the details of IA32, starting with the representation and manipulation of data and the implementation of control. We see how control constructs in C, such as if, while, and switch statements, are implemented. We then cover the implementation of procedures, including how the run-time stack supports the passing of data and control between procedures, as well as storage for local variables. Next, we consider how data structures such as arrays, structures, and unions are implemented at the machine level. With this background in machine-level programming, we can examine the problems of out of bounds memory references and the vulnerability of systems to buffer overflow attacks. We finish this part of the presentation with some tips on using the GDB debugger for examining the runtime behavior of a machinelevel program. We then move into material that is marked with a “*” and is intended for the truly dedicated machinelanguage enthusiasts. We give a presentation of IA32 support for floating-point code. This is a particularly arcane feature of IA32, and so we advise that only people determined to work with floating-point code attempt to study this section. We give a brief presentation of GCC’s support for embedding assembly code within C programs. In some applications, the programmer must drop down to assembly code to access low-level features of the machine. Embedded assembly is the best way to do this. 3.1 A Historical Perspective The Intel processor line has a long, evolutionary development. It started with one of the first single-chip, 16bit microprocessors, where many compromises had to be made due to the limited capabilities of integrated 3.1. A HISTORICAL PERSPECTIVE 91 circuit technology at the time. Since then it has grown to take advantage of technology improvements as well as to satisfy the demands for higher performance and for supporting more advanced operating systems. The following list shows the successive models of Intel processors, and some of their key features. We use the number of transistors required to implement the processors as an indication of how they have evolved in complexity (‘K’ denotes 1,000, and ‘M’ denotes 1,000,000). 8086: (1978, 29 K transistors). One of the first single-chip, 16-bit microprocessors. The 8088, a version of the 8086 with an 8-bit external bus, formed the heart of the original IBM personal computers. IBM contracted with then-tiny Microsoft to develop the MS-DOS operating system. The original models came with 32,768 bytes of memory and two floppy drives (no hard drive). Architecturally, the machines were limited to a 655,360-byte address space—addresses were only 20 bits long (1,048,576 bytes addressable), and the operating system reserved 393,216 bytes for its own use. 80286: (1982, 134 K transistors). Added more (and now obsolete) addressing modes. Formed the basis of the IBM PC-AT personal computer, the original platform for MS Windows. i386: (1985, 275 K transistors). Expanded the architecture to 32 bits. Added the flat addressing model used by Linux and recent versions of the Windows family of operating system. This was the first machine in the series that could support a Unix operating system. i486: (1989, 1.9 M transistors). Improved performance and integrated the floating-point unit onto the processor chip but did not change the instruction set. Pentium: (1993, 3.1 M transistors). Improved performance, but only added minor extensions to the instruction set. PentiumPro: (1995, 6.5 M transistors). Introduced a radically new processor design, internally known as the P6 microarchitecture. Added a class of “conditional move” instructions to the instruction set. Pentium/MMX: (1997, 4.5 M transistors). Added new class of instructions to the Pentium processor for manipulating vectors of integers. Each datum can be 1, 2, or 4-bytes long. Each vector totals 64 bits. Pentium II: (1997, 7 M transistors). Merged the previously separate PentiumPro and Pentium/MMX lines by implementing the MMX instructions within the P6 microarchitecture. Pentium III: (1999, 8.2 M transistors). Introduced yet another class of instructions for manipulating vectors of integer or floating-point data. Each datum can be 1, 2, or 4 bytes, packed into vectors of 128 bits. Later versions of this chip went up to 24 M transistors, due to the incorporation of the level-2 cache on chip. Pentium 4: (2001, 42 M transistors). Added 8-byte integer and floating-point formats to the vector instructions, along with 144 new instructions for these formats. Intel shifted away from Roman numerals in their numbering convention. Each successive processor has been designed to be backward compatible—able to run code compiled for any earlier version. As we will see, there are many strange artifacts in the instruction set due to this evolutionary heritage. Intel now calls its instruction set IA32, for “Intel Architecture 32-bit.” The processor line is also referred to by the colloquial name “x86,” reflecting the processor naming conventions up through the i486. 92 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Aside: Why not the i586? Intel discontinued their numeric naming convention, because they were not able to obtain trademark protection for their CPU numbers. The U. S. Trademark office does not allow numbers to be trademarked. Instead, they coined the name “Pentium” using the the Greek root word penta as an indication that this was their fifth generation machine. Since then, they have used variants of this name, even though the PentiumPro is a sixth generation machine (hence the internal name P6), and the Pentium 4 is a seventh generation machine. Each new generation involves a major change in the processor design. End Aside. Over the years, several companies have produced processors that are compatible with Intel processors, capable of running the exact same machine-level programs. Chief among these is AMD. For years, AMD’s strategy was to run just behind Intel in technology, producing processors that were less expensive although somewhat lower in performance. More recently, AMD has produced some of the highest performing processors for IA32. They were the first to the break the 1-gigahertz clock speed barrier for a commercially available microprocessor. Although we will talk about Intel processors, our presentation holds just as well for the compatible processors produced by Intel’s rivals. Much of the complexity of IA32 is not of concern to those interested in programs for the Linux operating system as generated by the GCC compiler. The memory model provided in the original 8086 and its extensions in the 80286 are obsolete. Instead, Linux uses what is referred to as flat addressing, where the entire memory space is viewed by the programmer as a large array of bytes. As we can see in the list of developments, a number of formats and instructions have been added to IA32 for manipulating vectors of small integers and floating-point numbers. These features were added to allow improved performance on multimedia applications, such as image processing, audio and video encoding and decoding, and three-dimensional computer graphics. Unfortunately, current versions of GCC will not generate any code that uses these new features. In fact, in its default invocations GCC assumes it is generating code for an i386. The compiler makes no attempt to exploit the many extensions added to what is now considered a very old architecture. 3.2 Program Encodings Suppose we write a C program as two files p1.c and p2.c. We would then compile this code using a Unix command line: unix> gcc -O2 -o p p1.c p2.c The command gcc indicates the GNU C compiler GCC. Since this is the default compiler on Linux, we could also invoke it as simply cc. The flag -O2 instructs the compiler to apply level-two optimizations. In general, increasing the level of optimization makes the final program run faster, but at a risk of increased compilation time and difficulties running debugging tools on the code. Level-two optimization is a good compromise between optimized performance and ease of use. All code in this book was compiled with this optimization level. This command actually invokes a sequence of programs to turn the source code into executable code. First, the C preprocessor expands the source code to include any files specified with #include commands and to expand any macros. Second, the compiler generates assembly code versions of the two source files having names p1.s and p2.s. Next, the assembler converts the assembly code into binary object code files p1.o 3.2. PROGRAM ENCODINGS 93 and p2.o. Finally, the linker merges these two object files along with code implementing standard Unix library functions (e.g., printf) and generates the final executable file. Linking is described in more detail in Chapter 7. 3.2.1 Machine-Level Code The compiler does most of the work in the overall compilation sequence, transforming programs expressed in the relatively abstract execution model provided by C into the very elementary instructions that the processor executes. The assembly code-representation is very close to machine code. Its main feature is that it is in a more readable textual format, as compared to the binary format of object code. Being able to understand assembly code and how it relates to the original C code is a key step in understanding how computers execute programs. The assembly programmer’s view of the machine differs significantly from that of a C programmer. Parts of the processor state are visible that are normally hidden from the C programmer: ¯ ¯ ¯ ¯ The program counter ( called %eip) indicates the address in memory of the next instruction to be executed. The integer register file contains eight named locations storing 32-bit values. These registers can hold addresses (corresponding to C pointers) or integer data. Some registers are used to keep track of critical parts of the program state, while others are used to hold temporary data, such as the local variables of a procedure. The condition code registers hold status information about the most recently executed arithmetic instruction. These are used to implement conditional changes in the control flow, such as is required to implement if or while statements. The floating-point register file contains eight locations for storing floating-point data. Whereas C provides a model where objects of different data types can be declared and allocated in memory, assembly code views the memory as simply a large, byte-addressable array. Aggregate data types in C such as arrays and structures are represented in assembly code as contiguous collections of bytes. Even for scalar data types, assembly code makes no distinctions between signed or unsigned integers, between different types of pointers, or even between pointers and integers. The program memory contains the object code for the program, some information required by the operating system, a run-time stack for managing procedure calls and returns, and blocks of memory allocated by the user, (for example, by using the malloc library procedure). The program memory is addressed using virtual addresses. At any given time, only limited subranges of virtual addresses are considered valid. For example, although the 32-bit addresses of IA32 potentially span a 4-gigabyte range of address values, a typical program will only have access to a few megabytes. The operating system manages this virtual address space, translating virtual addresses into the physical addresses of values in the actual processor memory. A single machine instruction performs only a very elementary operation. For example, it might add two numbers stored in registers, transfer data between memory and a register, or conditionally branch to a new 94 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS instruction address. The compiler must generate sequences of such instructions to implement program constructs such as arithmetic expression evaluation, loops, or procedure calls and returns. 3.2.2 Code Examples Suppose we write a C code file code.c containing the following procedure definition: 1 2 3 4 5 6 7 8 int accum = 0; int sum(int x, int y) { int t = x + y; accum += t; return t; } To see the assembly code generated by the C compiler, we can use the “-S” option on the command line: unix> gcc -O2 -S code.c This will cause the compiler to generate an assembly file code.s and go no further. (Normally it would then invoke the assembler to generate an object code file). The assembly-code file contains various declarations including the set of lines: sum: pushl %ebp movl %esp,%ebp movl 12(%ebp),%eax addl 8(%ebp),%eax addl %eax,accum movl %ebp,%esp popl %ebp ret Each indented line in the above code corresponds to a single machine instruction. For example, the pushl instruction indicates that the contents of register %ebp should be pushed onto the program stack. All information about local variable names or data types has been stripped away. We still see a reference to the global variable accum, since the compiler has not yet determined where in memory this variable will be stored. If we use the ’-c’ command line option, GCC will both compile and assemble the code: unix> gcc -O2 -c code.c This will generate an object code file code.o that is in binary format and hence cannot be viewed directly. Embedded within the 852 bytes of the file code.o is a 19 byte sequence having hexadecimal representation: 55 89 e5 8b 45 0c 03 45 08 01 05 00 00 00 00 89 ec 5d c3 3.2. PROGRAM ENCODINGS 95 This is the object code corresponding to the assembly instructions listed above. A key lesson to learn from this is that the program actually executed by the machine is simply a sequence of bytes encoding a series of instructions. The machine has very little information about the source code from which these instructions were generated. Aside: How do I find the byte representation of a program? First we used a disassembler (to be described shortly) to determine that the code for sum is 19 bytes long. Then we ran the GNU debugging tool GDB on file code.o and gave it the command: (gdb) x/19xb sum telling it to examine (abbreviated ‘x’) 19 hex-formatted (also abbreviated ‘x’) bytes (abbreviated ‘b’). You will find that GDB has many useful features for analyzing machine-level programs, as will be discussed in Section 3.12. End Aside. To inspect the contents of object code files, a class of programs known as disassemblers can be invaluable. These programs generate a format similar to assembly code from the object code. With Linux systems, the program OBJDUMP (for “object dump”) can serve this role given the ‘-d’ command line flag: unix> objdump -d code.o The result is (where we have added line numbers on the left and annotations on the right): Disassembly of function sum in file code.o 1 2 3 4 5 6 7 8 9 10 00000000 <sum>: Offset Bytes Equivalent assembly language 0: 1: 3: 6: 9: f: 11: 12: 13: 55 89 8b 03 01 89 5d c3 90 e5 45 0c 45 08 05 00 00 00 00 ec push mov mov add add mov pop ret nop %ebp %esp,%ebp 0xc(%ebp),%eax 0x8(%ebp),%eax %eax,0x0 %ebp,%esp %ebp On the left we see the 19 hexadecimal byte values listed in the byte sequence earlier, partitioned into groups of 1 to 5 bytes each. Each of these groups is a single instruction, with the assembly language equivalent shown on the right. Several features are worth noting: ¯ ¯ IA32 instructions can range in length from 1 to 15 bytes. The instruction encoding is designed so that commonly used instructions and ones with fewer operands require a smaller number of bytes than do less common ones or ones with more operands. The instruction format is designed in such a way that from a given starting position, there is a unique decoding of the bytes into machine instructions. For example, only the instruction pushl %ebp can start with byte value 55. 96 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS ¯ ¯ ¯ The disassembler determines the assembly code based purely on the byte sequences in the object file. It does not require access to the source or assembly-code versions of the program. The disassembler uses a slightly different naming convention for the instructions than does our example, it has omitted the suffix ‘l’ from many of the instructions. GAS. In Compared to the assembly code in code.s we also see an additional nop instruction at the end. This instruction will never be executed (it comes after the procedure return instruction), nor would it have any effect if it were (hence the name nop, short for “no operation” and commonly spoken as “no op”). The compiler inserted this instruction as a way to pad the space used to store the procedure. Generating the actual executable code requires running a linker on the set of object code files, one of which must contain a function main. Suppose in file main.c we had the function: 1 2 3 4 int main() { return sum(1, 3); } Then we could generate an executable program test as follows: unix> gcc -O2 -o prog code.o main.c The file prog has grown to 11,667 bytes, since it contains not just the code for our two procedures but also information used to start and terminate the program as well as to interact with the operating system. We can also disassemble the file prog: unix> objdump -d prog The disassembler will extract various code sequences, including the following: Disassembly of function sum in executable file prog 1 2 3 4 5 6 7 8 9 10 080483b4 <sum>: 80483b4: 55 80483b5: 89 e5 80483b7: 8b 45 0c 80483ba: 03 45 08 80483bd: 01 05 64 94 04 08 80483c3: 89 ec 80483c5: 5d 80483c6: c3 80483c7: 90 push mov mov add add mov pop ret nop %ebp %esp,%ebp 0xc(%ebp),%eax 0x8(%ebp),%eax %eax,0x8049464 %ebp,%esp %ebp Note that this code is almost identical to that generated by the disassembly of code.c. One main difference is that the addresses listed along the left are different—the linker has shifted the location of this code to a different range of addresses. A second difference is that the linker has finally determined the location for storing global variable accum. On line 5 of the disassembly for code.o the address of accum was still listed as 0. In the disassembly of prog, the address has been set to 0x8049444. This is shown in the assembly code rendition of the instruction. It can also be seen in the last four bytes of the instruction, listed from least-significant to most as 44 94 04 08. 3.2. PROGRAM ENCODINGS 97 3.2.3 A Note on Formatting The assembly code generated by GCC is somewhat difficult to read. It contains some information with which we need not be concerned. On the other hand, it does not provide any description of the program or how it works. For example, suppose file simple.c contains the code: 1 2 3 4 5 6 int simple(int *xp, int y) { int t = *xp + y; *xp = t; return t; } when GCC is run with the ‘-S’ flag it generates the following file for simple.s. .file "simple.c" .version "01.01" gcc2_compiled.: .text .align 4 .globl simple .type simple,@function simple: pushl %ebp movl %esp,%ebp movl 8(%ebp),%eax movl (%eax),%edx addl 12(%ebp),%edx movl %edx,(%eax) movl %edx,%eax movl %ebp,%esp popl %ebp ret .Lfe1: .size simple,.Lfe1-simple .ident "GCC: (GNU) 2.95.3 20010315 (release)" The file contains more information than we really require. All of the lines beginning with ‘.’ are directives to guide the assembler and linker. We can generally ignore these. On the other hand, there are no explanatory remarks about what the instructions do or how they relate to the source code. To provide a clearer presentation of assembly code, we will show it in a form that includes line numbers and explanatory annotations. For our example, an annotated version would appear as follows: 1 2 3 4 simple: pushl %ebp movl %esp,%ebp movl 8(%ebp),%eax Save frame pointer Create new frame pointer Get xp 98 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS C declaration char short int unsigned long int unsigned long char * float double long double Intel Data Type Byte Word Double Word Double Word Double Word Double Word Double Word Single Precision Double Precision Extended Precision GAS suffix b w l l l l l s l t Size (Bytes) 1 2 4 4 4 4 4 4 8 10/12 Figure 3.1: Sizes of standard data types 5 6 7 8 9 10 11 movl addl movl movl movl popl ret (%eax),%edx 12(%ebp),%edx %edx,(%eax) %edx,%eax %ebp,%esp %ebp Retrieve *xp Add y to get t Store t at *xp Set t as return value Reset stack pointer Reset frame pointer Return We typically show only the lines of code relevant to the point being discussed. Each line is numbered on the left for reference and annotated on the right by a brief description of the effect of the instruction and how it relates to the computations of the original C code. This is a stylized version of the way assembly-language programmers format their code. 3.3 Data Formats Due to its origins as a 16-bit architecture that expanded into a 32-bit one, Intel uses the term “word” to refer to a 16-bit data type. Based on this, they refer to 32-bit quantities as “double words.” They refer to 64-bit quantities as “quad words.” Most instructions we will encounter operate on bytes or double words. Figure 3.1 shows the machine representations used for the primitive data types of C. Note that most of the common data types are stored as double words. This includes both regular and long int’s, whether or not they are signed. In addition, all pointers (shown here as char *) are stored as 4-byte double words. Bytes are commonly used when manipulating string data. Floating-point numbers come in three different forms: single-precision (4-byte) values, corresponding to C data type float; double-precision (8-byte) values, corresponding to C data type double; and extended-precision (10-byte) values. G CC uses the data type long double to refer to extended-precision floating-point values. It also stores them as 12byte quantities to improve memory system performance, as will be discussed later. Although the ANSI C standard includes long double as a data type, they are implemented for most combinations of compiler and machine using the same 8-byte format as ordinary double. The support for extended precision is 3.4. ACCESSING INFORMATION 31 %eax %ecx %edx %ebx %esi %edi %esp %ebp %ax %cx %dx %ax %si %di %sp %bp Stack Pointer Frame Pointer 15 %ah %ch %dh %bh 87 %al %cl %dl %bl 0 99 Figure 3.2: Integer Registers. All eight registers can be accessed as either 16 bits (word) or 32 bits (double word). The two low-order bytes of the first four registers can be accessed independently. unique to the combination of GCC and IA32. As the table indicates, every operation in GAS has a single-character suffix denoting the size of the operand. For example, the mov (move data) instruction has 3 variants: movb (move byte), movw (move word), and movl (move double word). The suffix ‘l’ is used for double words, since on many machines 32-bit quantities are referred to as “long words,” a holdover from an era when 16-bit word sizes were standard. Note that GAS uses the suffix ‘l’ to denote both a 4-byte integer as well as an 8-byte double-precision floating-point number. This causes no ambiguity, since floating point involves an entirely different set of instructions and registers. 3.4 Accessing Information An IA32 central processing unit (CPU) contains a set of eight registers storing 32-bit values. These registers are used to store integer data as well as pointers. Figure 3.2 diagrams the eight registers. Their names all begin with %e, but otherwise they have peculiar names. With the original 8086, the registers were 16-bits and each had a specific purpose. The names were chosen to reflect these different purposes. With flat addressing, the need for specialized registers is greatly reduced. For the most part, the first 6 registers can be considered general-purpose registers with no restrictions placed on their use. We said “for the most part,” because some instructions use fixed registers as sources and/or destinations. In addition, within procedures there are different conventions for saving and restoring the first three registers (%eax, %ecx, and %edx), than for the next three (%ebx, %edi, and %esi). This will be discussed in Section 3.7. The final two 100 Type Immediate Register Memory Memory Memory Memory Memory Memory Memory Memory Memory Form $ÁÑÑ CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Operand Value ÁÑÑ Ê Å Ñ ÁÑÑ Å ÑÊ Å Ñ ÁÑÑ · Ê Å ÑÊ ·Ê Å Ñ ÁÑÑ · Ê Å ÑÊ ¡× Å Ñ ÁÑÑ · Ê Å ÑÊ ·Ê Å Ñ ÁÑÑ · Ê Name Immediate Register Absolute Indirect Base + Displacement Indexed Indexed Scaled Indexed Scaled Indexed Scaled Indexed Scaled Indexed ÁÑÑ () ÁÑÑ ( ) (,) ÁÑÑ ( , ) (, ,×) ÁÑÑ (, ,×) ( , , ×) ÁÑÑ ( , ,×) · Ê ¡× · ¡× Ê ¡× Figure 3.3: Operand Forms. Operands can denote immediate (constant) values, register values, or values from memory. The scaling factor × must be either 1, 2, 4, or 8. registers (%ebp and %esp) contain pointers to important places in the program stack. They should only be altered according to the set of standard conventions for stack management. As indicated in Figure 3.2, the low-order two bytes of the first four registers can be independently read or written by the byte operation instructions. This feature was provided in the 8086 to allow backward compatibility to the 8008 and 8080—two 8-bit microprocessors that date back to 1974. When a byte instruction updates one of these single-byte “register elements,” the remaining three bytes of the register do not change. Similarly, the low-order 16 bits of each register can be read or written by word operation instructions. This feature stems from IA32’s evolutionary heritage as a 16-bit microprocessor. 3.4.1 Operand Specifiers Most instructions have one or more operands, specifying the source values to reference in performing an operation and the destination location into which to place the result. IA32 supports a number of operand forms (Figure 3.3). Source values can be given as constants or read from registers or memory. Results can be stored in either registers or memory. Thus, the different operand possibilities can be classified into three types. The first type, immediate, is for constant values. With GAS, these are written with a ‘$’ followed by an integer using standard C notation, such as, $-577 or $0x1F. Any value that fits in a 32-bit word can be used, although the assembler will use one or two-byte encodings when possible. The second type, register, denotes the contents of one of the registers, either one of the eight 32-bit registers (e.g., %eax) for a double-word operation, or one of the eight single-byte register elements (e.g., %al) for a byte operation. In our figure, we use the notation to denote an arbitrary register , and indicate its value with the reference Ê , viewing the set of registers as an array Ê indexed by register identifiers. The third type of operand is a memory reference, in which we access some memory location according to a computed address, often called the effective address. As the table shows, there are many different addressing modes allowing different forms of memory references. The most general form is shown at the bottom of the table with syntax ÁÑÑ ( , ,×). Such a reference has four components: an immediate offset ÁÑÑ , a base 3.4. ACCESSING INFORMATION Instruction movl movw movb movsbl movzbl pushl popl Effect Description Move Double Word Move Word Move Byte Move Sign-Extended Byte Move Zero-Extended Byte Push Pop · 101 Ë, Ë, Ë, Ë, Ë, Ë Ë Ò ÜØ Ò ´Ë µ ÖÓ ÜØ Ò ´Ë µ Ê %esp Ê %esp Å Ñ Ê %esp Ë Å Ñ Ê %esp ; Ê %esp Ê %esp Ë Ë Ë ; Figure 3.4: Data Movement Instructions. register , an index register , and a scale factor ×, where × must be 1, 2, 4, or 8. The effective address is then computed as ÁÑÑ · Ê ·Ê ¡ × This general form is often seen when referencing elements of arrays. The other forms are simply special cases of this general form where some of the components are omitted. As we will see, the more complex addressing modes are useful when referencing array and structure elements. Practice Problem 3.1: Assume the following values are stored at the indicated memory addresses and registers: Address 0x100 0x104 0x108 0x10C Value 0xFF 0xAB 0x13 0x11 Register %eax %ecx %edx Value 0x100 0x1 0x3 Fill in the following table showing the values for the indicated operands Operand %eax 0x104 $0x108 (%eax) 4(%eax) 9(%eax,%edx) 260(%ecx,%edx) 0xFC(,%ecx,4) (%eax,%edx,4) Value 102 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS 3.4.2 Data Movement Instructions Among the most heavily used instructions are those that perform data movement. The generality of the operand notation allows a simple move instruction to perform what in many machines would require a number of instructions. Figure 3.4 lists the important data movement instructions. The most common is the movl instruction for moving double words. The source operand designates a value that is immediate, stored in a register, or stored in memory. The destination operand designates a location that is either a register or a memory address. IA32 imposes the restriction that a move instruction cannot have both operands refer to memory locations. Copying a value from one memory location to another requires two instructions—the first to load the source value into a register, and the second to write this register value to the destination. The following are some examples of movl instructions showing the five possible combinations of source and destination types. Recall that the source operand comes first and the destination second. 1 2 3 4 5 movl movl movl movl movl $0x4050,%eax %ebp,%esp (%edi,%ecx),%eax $-17,(%esp) %eax,-12(%ebp) Immediate--Register Register--Register Memory--Register Immediate--Memory Register--Memory The movb instruction is similar, except that it moves just a single byte. When one of the operands is a register, it must be one of the eight single-byte register elements illustrated in Figure 3.2. Similarly, the movw instruction moves two bytes. When one of its operands is a register, it must be one of the eight two-byte register elements shown in Figure 3.2. Both the movsbl and the movzbl instruction serve to copy a byte and to set the remaining bits in the destination. The movsbl instruction takes a single-byte source operand, performs a sign extension to 32 bits (i.e., it sets the high-order 24 bits to the most significant bit of the source byte), and copies this to a double-word destination. Similarly, the movzbl instruction takes a single-byte source operand, expands it to 32 bits by adding 24 leading zeros, and copies this to a double-word destination. Aside: Comparing byte movement instructions. Observe that the three byte movement instructions movb, movsbl, and movzbl differ from each other in subtle ways. Here is an example: Assume initially that %dh = 8D, %eax %eax %eax %eax = 98765432 = 9876548D = FFFFFF8D = 0000008D 1 2 3 movb %dh,%al movsbl %dh,%eax movzbl %dh,%eax In these examples, all set the low-order byte of register %eax to the second byte of %edx. The movb instruction does not change the other three bytes. The movsbl instruction sets the other three bytes to either all ones or all zeros depending on the high-order bit of the source byte. The movzbl instruction sets the other three bytes to all zeros in any case. End Aside. The final two data movement operations are used to push data onto and pop data from the program stack. As we will see, the stack plays a vital role in the handling of procedure calls. Both the pushl and the popl instructions take a single operand—the data source for pushing and the data destination for popping. The 3.4. ACCESSING INFORMATION code/asm/exchange.c 1 2 3 4 5 6 7 1 2 3 4 5 103 movl movl movl movl movl 8(%ebp),%eax 12(%ebp),%edx (%eax),%ecx %edx,(%eax) %ecx,%eax Get xp Get y Get x at *xp Store y at *xp Set x as return value int exchange(int *xp, int y) { int x = *xp; *xp = y; return x; } code/asm/exchange.c (a) C code (b) Assembly code Figure 3.5: C and Assembly Code for Exchange Routine Body. The stack set-up and completion portions have been omitted. program stack is stored in some region of memory. The stack grows downward such that the top element of the stack has the lowest address of all stack elements. The stack pointer %esp holds the address of this lowest stack element. Pushing a double-word value onto the stack therefore involves first decrementing the stack pointer by 4 and then writing the value at the new top of stack address. Therefore, the instruction pushl %ebp has equivalent behavior to the following pair of instructions: subl $4,%esp movl %ebp,(%esp) except that the pushl instruction is encoded in the object code as a single byte, whereas the pair of instruction shown above requires a total of 6 bytes. Popping a double word involves reading from the top of stack location and then incrementing the stack pointer by 4. Therefore the instruction popl %eax is equivalent to the following pair of instructions: movl (%esp),%eax addl $4,%esp 3.4.3 Data Movement Example New to C? Function exchange (Figure 3.5) provides a good illustration of the use of pointers in C. Argument xp is a pointer to an integer, while y is an integer itself. The statement int x = *xp; indicates that we should read the value stored in the location designated by xp and store it as a local variable named x. This read operation is known as pointer dereferencing. The C operator * performs pointer dereferencing. The statement *xp = y; 104 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS does the reverse—it writes the value of parameter y at the location designated by xp. This also a form of pointer dereferencing (and hence the operator *), but it indicates a write operation since it is on the left hand side of the assignment statement. Here is an example of exchange in action: int a = 4; int b = exchange(&a, 3); printf("a = %d, b = %d\n", a, b); This code will print a = 3, b = 4 The C operator (called the “address of” operator) & creates a pointer, in this case to the location holding local variable a. Function exchange then overwrote the value stored in a with 3 but returned 4 as the function value. Observe how by passing a pointer to exchange, it could modify data held at some remote location. End As an example of code that uses data movement instructions, consider the data exchange routine shown in Figure 3.5, both as C code and as assembly code generated by GCC. We omit the portion of the assembly code that allocates space on the run-time stack on procedure entry and deallocates it prior to return. The details of this set-up and completion code will be covered when we discuss procedure linkage. The code we are left with is called the “body.” When the body of the procedure starts execution, procedure parameters xp and y are stored at offsets 8 and 12 relative to the address in register %ebp. Instructions 1 and 2 then move these parameters into registers %eax and %edx. Instruction 3 dereferences xp and stores the value in register %ecx, corresponding to program value x. Instruction 4 stores y at xp. Instruction 5 moves x to register %eax. By convention, any function returning an integer or pointer value does so by placing the result in register %eax, and so this instruction implements line 6 of the C code. This example illustrates how the movl instruction can be used to read from memory to a register (instructions 1 to 3), to write from a register to memory (instruction 4), and to copy from one register to another (instruction 5). Two features about this assembly code are worth noting. First, we see that what we call “pointers” in C are simply addresses. Dereferencing a pointer involves putting that pointer in a register, and then using this register in an indirect memory reference. Second, local variables such as x are often kept in registers rather than stored in memory locations. Register access is much faster than memory access. Practice Problem 3.2: You are given the following information. A function with prototype void decode1(int *xp, int *yp, int *zp); is compiled into assembly code. The body of the code is as follows: 1 2 3 movl 8(%ebp),%edi movl 12(%ebp),%ebx movl 16(%ebp),%esi 3.5. ARITHMETIC AND LOGICAL OPERATIONS Instruction leal Ë, incl decl negl notl addl Ë, subl Ë, imull Ë , xorl Ë, orl Ë, andl Ë, sall , shll , sarl , shrl , Effect Description Load Effective Address Increment Decrement Negate Complement Add Subtract Multiply Exclusive-Or Or And Left Shift Left Shift (same as sall) Arithmetic Right Shift Logical Right Shift 105 &Ë +1 -1 ˜ +Ë -Ë *Ë ˆË |Ë &Ë << << >> >> Figure 3.6: Integer Arithmetic Operations. The Load Effective Address leal is commonly used to perform simple arithmetic. The remaining ones are more standard unary or binary operations. Note the nonintuitive ordering of the operands with GAS. 4 5 6 7 8 9 movl movl movl movl movl movl (%edi),%eax (%ebx),%edx (%esi),%ecx %eax,(%ebx) %edx,(%esi) %ecx,(%edi) Parameters xp, yp, and zp are stored at memory locations with offsets 8, 12, and 16, respectively, relative to the address in register %ebp. Write C code for decode1 that will have an effect equivalent to the assembly code above. You can test your answer by compiling your code with the -S switch. Your compiler may generate code that differs in the usage of registers or the ordering of memory references, but it should still be functionally equivalent. 3.5 Arithmetic and Logical Operations Figure 3.6 lists some of the double-word integer operations, divided into four groups. Binary operations have two operands, while unary operations have one operand. These operands are specified using the same notation as described in Section 3.4. With the exception of leal, each of these instructions has a counterpart that operates on words (16 bits) and on bytes. The suffix ‘l’ is replaced by ‘w’ for word operations and ‘b’ for the byte operations. For example, addl becomes addw or addb. 106 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS 3.5.1 Load Effective Address The Load Effective Address leal instruction is actually a variant of the movl instruction. Its first operand appears to be a memory reference, but instead of reading from the designated location, the instruction copies the effective address to the destination. We indicate this computation in Figure 3.6 using the C address operator &Ë . This instruction can be used to generate pointers for later memory references. In addition, it can be used to compactly describe common arithmetic operations. For example, if register %edx contains value Ü, then the instruction leal 7(%edx,%edx,4), %eax will set register %eax to Ü · . The destination operand must be a register. Practice Problem 3.3: Suppose register %eax holds value Ü and %ecx holds value Ý . Fill in the table below with formulas indicating the value that will be stored in register %edx for each of the following assembly code instructions. Expression leal 6(%eax), %edx leal (%eax,%ecx), %edx leal (%eax,%ecx,4), %edx leal 7(%eax,%eax,8), %edx leal 0xA(,$ecx,4), %edx leal 9(%eax,%ecx,2), %edx Result 3.5.2 Unary and Binary Operations Operations in the second group are unary operations, with the single operand serving as both source and destination. This operand can be either a register or a memory location. For example, the instruction incl (%esp) causes the element on the top of the stack to be incremented. This syntax is reminiscent of the C increment (++) and decrement operators (--). The third group consists of binary operations, where the second operand is used as both a source and a destination. This syntax is reminiscent of the C assignment operators such as +=. Observe, however, that the source operand is given first and the destination second. This looks peculiar for noncommutative operations. For example, the instruction subl %eax,%edx decrements register %edx by the value in %eax. The first operand can be either an immediate value, a register, or a memory location. The second can be either a register or a memory location. As with the movl instruction, however, the two operands cannot both be memory locations. Practice Problem 3.4: Assume the following values are stored at the indicated memory addresses and registers: Address 0x100 0x104 0x108 0x10C Value 0xFF 0xAB 0x13 0x11 Register %eax %ecx %edx Value 0x100 0x1 0x3 3.5. ARITHMETIC AND LOGICAL OPERATIONS Fill in the following table showing the effects of the following instructions, both in terms of the register or memory location that will be updated and the resulting value. Instruction addl %ecx,(%eax) subl %edx,4(%eax) imull $16,(%eax,%edx,4) incl 8(%eax) decl %ecx subl %edx,%eax Destination Value 107 3.5.3 Shift Operations The final group consists of shift operations, where the shift amount is given first, and the value to shift is given second. Both arithmetic and logical right shifts are possible. The shift amount is encoded as a single byte, since only shifts amounts between 0 and 31 are allowed. The shift amount is given either as an immediate or in the single-byte register element %cl. As Figure 3.6 indicates, there are two names for the left shift instruction: sall and shll. Both have the same effect, filling from the right with 0s. The right shift instructions differ in that sarl performs an arithmetic shift (fill with copies of the sign bit), whereas shrl performs a logical shift (fill with 0s). Practice Problem 3.5: Suppose we want to generate assembly code for the following C function: int shift_left2_rightn(int x, int n) { x <<= 2; x >>= n; return x; } The following is a portion of the assembly code that performs the actual shifts and leaves the final value in register %eax. Two key instructions have been omitted. Parameters x and n are stored at memory locations with offsets 8 and 12, respectively, relative to the address in register %ebp. 1 2 3 4 movl 12(%ebp),%ecx movl 8(%ebp),%eax _____________ _____________ Get x Get n x <<= 2 x >>= n Fill in the missing instructions, following the annotations on the right. The right shift should be performed arithmetically. 108 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS code/asm/arith.c 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 10 11 int arith(int x, int y, int z) { int t1 = x+y; int t2 = z*48; int t3 = t1 & 0xFFFF; int t4 = t2 * t3; return t4; } code/asm/arith.c movl 12(%ebp),%eax movl 16(%ebp),%edx addl 8(%ebp),%eax leal (%edx,%edx,2),%edx sall $4,%edx andl $65535,%eax imull %eax,%edx movl %edx,%eax Get y Get z Compute t1 = x+y Compute z*3 Compute t2 = z*48 Compute t3 = t1&0xFFFF Compute t4 = t2*t3 Set t4 as return val (a) C code (b) Assembly code Figure 3.7: C and Assembly Code for Arithmetic Routine Body. The stack set-up and completion portions have been omitted. 3.5.4 Discussion With the exception of the right shift operations, none of the instructions distinguish between signed and unsigned operands. Two’s complement arithmetic has the same bit-level behavior as unsigned arithmetic for all of the instructions listed. Figure 3.7 shows an example of a function that performs arithmetic operations and its translation into assembly. As before, we have omitted the stack set-up and completion portions. Function arguments x, y, and z are stored in memory at offsets 8, 12, and 16 relative to the address in register %ebp, respectively. Instruction 3 implements the expression x+y, getting one operand y from register %eax (which was fetched by instruction 1) and the other directly from memory. Instructions 4 and 5 perform the computation z*48, first using the leal instruction with a scaled-indexed addressing mode operand to compute ´Þ · ¾Þ µ ¿Þ , and then shifting this value left 4 bits to compute ¾ ¡¿Þ Þ . The C compiler often generates combinations of add and shift instructions to perform multiplications by constant factors, as was discussed in Section 2.3.6 (page 63). Instruction 6 performs the AND operation and instruction 7 performs the final multiplication. Then instruction 8 moves the return value into register %eax. In the assembly code of Figure 3.7, the sequence of values in register %eax correspond to program values y, t1, t3, and t4 (as the return value). In general, compilers generate code that uses individual registers for multiple program values and that move program values among the registers. Practice Problem 3.6: In the compilation of the following loop: for (i = 0; i < n; i++) v += i; we find the following assembly code line: 3.5. ARITHMETIC AND LOGICAL OPERATIONS Instruction imull Ë mull Ë cltd idivl Ë divl Effect Ê %edx Ê Ê %edx Ê Ê %edx Ê Ê %edx Ê %eax Ê %edx Ê %eax 109 Description Signed Full Multiply Unsigned Full Multiply Convert to Quad Word Signed Divide Unsigned Divide Ë %eax %eax %eax Ê %edx Ê %edx Ê %edx Ê %edx Ë Ê Ê Ê Ê Ë¢Ê Ë¢Ê %eax %eax Ò ÜØ Ò ´Ê %eax µ %eax ÑÓ Ë ; %eax ¤ Ë %eax ÑÓ Ë ; %eax ¤ Ë Figure 3.8: Special Arithmetic Operations. These operations provide full 64-bit multiplication and division, for both signed and unsigned numbers. The pair of registers %edx and %eax are viewed as forming a single 64-bit quad word. xorl %edx,%edx Explain why this instruction would be there, even though there are no EXCLUSIVE - OR operators in our C code. What operation in the C program does this instruction implement? 3.5.5 Special Arithmetic Operations Figure 3.8 describes instructions that support generating the full 64-bit product of two 32-bit numbers, as well as integer division. The imull instruction listed in Figure 3.6 is known as the “two-operand” multiply instruction. It generates a 32-bit product from two 32-bit operands, implementing the operations *u and *t¿¾ described in ¿¾ Sections 2.3.4 and 2.3.5 (pages 61 and 62). Recall that when truncating the product to 32 bits, both unsigned multiply and two’s complement multiply have the same bit-level behavior. IA32 also provides two different “one-operand” multiply instructions to compute the full 64-bit product of two 32-bit values—one for unsigned (mull), and one for two’s complement (imull) multiplication. For both of these, one argument must be in register %eax, and the other is given as the instruction source operand. The product is then stored in registers %edx (high-order 32 bits) and %eax (low-order 32 bits). Note that although the name imull is used for two distinct multiplication operations, the assembler can tell which one is intended by counting the number of operands. As an example, suppose we have signed numbers x and y stored at positions and ½¾ relative to %ebp, and we want to store their full 64-bit product as 8 bytes on top of the stack. The code would proceed as follows: x at %ebp+8, y at %ebp+12 1 2 3 4 movl 8(%ebp),%eax imull 12(%ebp) pushl %edx pushl %eax Put x in %eax Multiply by y Push high-order 32 bits Push low-order 32 bits Observe that the order in which we push the two registers is correct for a little-endian machine in which the stack grows toward lower addresses, i.e., the low-order bytes of the product will have lower addresses than the high-order bytes. 110 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Our earlier table of arithmetic operations (Figure 3.6) does not list any division or modulus operations. These operations are provided by the single-operand divide instructions similar to the single-operand multiply instructions. The signed division instruction idivl takes as dividend the 64-bit quantity in registers %edx (high-order 32 bits) and %eax (low-order 32 bits). The divisor is given as the instruction operand. The instructions store the quotient in register %eax and the remainder in register %edx. The cltd1 instruction can be used to form the 64-bit dividend from a 32-bit value stored in register %eax. This instruction sign extends %eax into %edx. As an example, suppose we have signed numbers x and y stored in positions and ½¾ relative to %ebp, and we want to store values x/y and x%y on the stack. The code would proceed as follows: x at %ebp+8, y at %ebp+12 1 2 3 4 5 movl 8(%ebp),%eax cltd idivl 12(%ebp) pushl %eax pushl %edx Put x in %eax Sign extend into %edx Divide by y Push x / y Push x % y The divl instruction performs unsigned division. Typically register %edx is set to 0 beforehand. 3.6 Control Up to this point, we have considered ways to access and operate on data. Another important part of program execution is to control the sequence of operations that are performed. The default for statements in C as well as for assembly code is to have control flow sequentially, with statements or instructions executed in the order they appear in the program. Some constructs in C, such as conditionals, loops, and switches, allow the control to flow in nonsequential order, with the exact sequence depending on the values of program data. Assembly code provides lower-level mechanisms for implementing nonsequential control flow. The basic operation is to jump to a different part of the program, possibly contingent on the result of some test. The compiler must generate instruction sequences that build upon these low-level mechanisms to implement the control constructs of C. In our presentation, we first cover the machine-level mechanisms and then show how the different control constructs of C are implemented with them. 3.6.1 Condition Codes In addition to the integer registers, the CPU maintains a set of single-bit condition code registers describing attributes of the most recent arithmetic or logical operation. These registers can then be tested to perform conditional branches. The most useful condition codes are: CF: Carry Flag. The most recent operation generated a carry out of the most significant bit. Used to detect overflow for unsigned operations. This instruction is called cdq in the Intel documentation, one of the few cases where the GAS name for an instruction bears no relation to the Intel name. 1 3.6. CONTROL ZF: Zero Flag. The most recent operation yielded zero. SF: Sign Flag. The most recent operation yielded a negative value. 111 OF: Overflow Flag. The most recent operation caused a two’s complement overflow—either negative or positive. For example, suppose we used the addl instruction to perform the equivalent of the C expression t=a+b, where variables a, b, and t are of type int. Then the condition codes would be set according to the following C expressions: CF: ZF: SF: OF: (unsigned t) < (unsigned a) (t == 0) (t < 0) (a < 0 == b < 0) && (t < 0 != a < 0) Unsigned overflow Zero Negative Signed overflow The leal instruction does not alter any condition codes, since it is intended to be used in address computations. Otherwise, all of the instructions listed in Figure 3.6 cause the condition codes to be set. For the logical operations, such as xorl, the carry and overflow flags are set to 0. For the shift operations, the carry flag is set to the last bit shifted out, while the overflow flag is set to 0. In addition to the operations of Figure 3.6, two operations (having 8, 16, and 32-bit forms) set conditions codes without altering any other registers: Instruction cmpb ˾ , ˽ testb ˾ , ˽ cmpw ˾ , ˽ testw ˾ , ˽ cmpl ˾ , ˽ testl ˾ , ˽ Based on ˽ - ˾ ˽ & ˾ ˽ - ˾ ˽ & ˾ ˽ - ˾ ˽ & ˾ Description Compare bytes Test byte Compare words Test word Compare double words Test double word The cmpb, cmpw, and cmpl instructions set the condition codes according to the difference of their two operands. With GAS format, the operands are listed in reverse order, making the code difficult to read. These instructions set the zero flag if the two operands are equal. The other flags can be used to determine ordering relations between the two operands. The testb, testw, and testl instructions set the zero and negative flags based on the AND of their two operands. Typically, the same operand is repeated (e.g., testl %eax,%eax to see whether %eax is negative, zero, or positive), or one of the operands is a mask indicating which bits should be tested. 3.6.2 Accessing the Condition Codes Rather than reading the condition codes directly, the two most common methods of accessing them are to set an integer register or to perform a conditional branch based on some combination of condition codes. The different set instructions described in Figure 3.9 set a single byte to 0 or to 1 depending on some combination of the conditions codes. The destination operand is either one of the eight single-byte register 112 Instruction sete setne sets setns setg setge setl setle seta setae setb setbe CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Synonym setz setnz Effect ZF ˜ ZF SF ˜ SF ˜ ´SF ˆ OFµ & ˜ZF ˜ ´SF ˆ OFµ SF ˆ OF ´SF ˆ OFµ | ZF ˜ CF & ˜ZF ˜ CF CF CF & ˜ZF Set Condition Equal / Zero Not Equal / Not Zero Negative Nonnegative Greater (Signed >) Greater or Equal (Signed >=) Less (Signed <) Less or Equal (Signed <=) Above (Unsigned >) Above or Equal (Unsigned >=) Below (Unsigned <) Below or Equal (Unsigned <=) setnle setnl setnge setng setnbe setnb setnae setna Figure 3.9: The set Instructions. Each instruction sets a single byte to 0 or 1 based on some combination of the condition codes. Some instructions have “synonyms,” i.e., alternate names for the same machine instruction. elements (Figure 3.2) or a memory location where the single byte is to be stored. To generate a 32-bit result, we must also clear the high-order 24 bits. A typical instruction sequence for a C predicate such as a<b is therefore as follows Note: a is in %edx, b is in %eax Compare a:b Set low order byte of %eax to 0 or 1 Set remaining bytes of %eax to 0 1 2 3 cmpl %eax,%edx setl %al movzbl %al,%eax using the movzbl instruction to clear the high-order three bytes. For some of the underlying machine instructions, there are multiple possible names, which we list as “synonyms.” For example both “setg” (for “SET-Greater”) and “setnle” (for “SET-Not-Less-or-Equal”) refer to the same machine instruction. Compilers and disassemblers make arbitrary choices of which names to use. Although all arithmetic operations set the condition codes, the descriptions of the different set commands apply to the case where a comparison instruction has been executed, setting the condition codes according to the computation t=a-b. For example, consider the sete, or “Set when equal” instruction. When a b, we will have t ¼, and hence the zero flag indicates equality. Similarly, consider testing a signed comparison with the setl, or “Set when less,” instruction. When a and b are in two’s complement form, then for a b we will have a b ¼ if the true difference were computed. When there is no overflow, this would be indicated by having the sign flag set. When there is positive overflow, because a b is a large positive number, however, we will have t ¼. When there is negative overflow, because a b is a small negative number, we will have t ¼. In either case, the sign flag will indicate the opposite of the sign of the true difference. Hence, the E XCLUSIVE -O R of the overflow and sign bits provides a test for whether a b. The other signed comparison tests are based on 3.6. CONTROL other combinations of SF ˆ OF and ZF. 113 For the testing of unsigned comparisons, the carry flag will be set by the cmpl instruction when the integer difference a b of the unsigned arguments a and b would be negative, that is, when (unsigned) a < (unsigned) b. Thus, these tests use combinations of the carry and zero flags. Practice Problem 3.7: In the following C code, we have replaced some of the comparison operators with “__” and omitted the data types in the casts. 1 2 3 4 5 6 7 8 9 10 char ctest(int a, int { char t1 = a char t2 = b char t3 = ( )c char t4 = ( )a char t5 = c char t6 = a return t1 + t2 + t3 } b, int c) __ b; __ ( ) a; __ ( ) a; __ ( ) c; __ b; __ 0; + t4 + t5 + t6; For the original C code, GCC generates the following assembly code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 movl 8(%ebp),%ecx movl 12(%ebp),%esi cmpl %esi,%ecx setl %al cmpl %ecx,%esi setb -1(%ebp) cmpw %cx,16(%ebp) setge -2(%ebp) movb %cl,%dl cmpb 16(%ebp),%dl setne %bl cmpl %esi,16(%ebp) setg -3(%ebp) testl %ecx,%ecx setg %dl addb -1(%ebp),%al addb -2(%ebp),%al addb %bl,%al addb -3(%ebp),%al addb %dl,%al movsbl %al,%eax Get a Get b Compare Compute Compare Compute Compare Compute a:b t1 b:a t2 c:a t3 Compare a:c Compute t4 Compare c:b Compute t5 Test a Compute t4 Add t2 to t1 Add t3 to t1 Add t4 to t1 Add t5 to t1 Add t6 to t1 Convert sum from char to int Based on this assembly code, fill in the missing parts (the comparisons and the casts) in the C code. 114 Instruction jmp Label jmp *Operand je Label jne Label js Label jns Label jg Label jge Label jl Label jle Label ja Label jae Label jb Label jbe Label CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Synonym Jump Condition 1 1 ZF ˜ZF SF ˜SF ˜´SF ˆ OFµ & ˜ZF ˜´SF ˆ OFµ SF ˆ OF ´SF ˆ OFµ | ZF ˜CF & ˜ZF ˜CF CF CF & ˜ZF Description Direct Jump Indirect Jump Equal / Zero Not Equal / Not Zero Negative Nonnegative Greater (Signed >) Greater or Equal (Signed >=) Less (Signed <) Less or Equal (Signed <=) Above (Unsigned >) Above or Equal (Unsigned >=) Below (Unsigned <) Below or Equal (Unsigned <=) jz jnz jnle jnl jnge jng jnbe jnb jnae jna Figure 3.10: The jump Instructions. These instructions jump to a labeled destination when the jump condition holds. Some instructions have “synonyms,” alternate names for the same machine instruction. 3.6.3 Jump Instructions and their Encodings Under normal execution, instructions follow each other in the order they are listed. A jump instruction can cause the execution to switch to a completely new position in the program. These jump destinations are generally indicated by a label. Consider the following assembly code sequence: 1 2 3 4 5 xorl %eax,%eax jmp .L1 movl (%eax),%edx .L1: popl %edx Set %eax to 0 Goto .L1 Null pointer dereference The instruction jmp .L1 will cause the program to skip over the movl instruction and instead resume execution with the popl instruction. In generating the object code file, the assembler determines the addresses of all labeled instructions and encodes the jump targets (the addresses of the destination instructions) as part of the jump instructions. The jmp instruction jumps unconditionally. It can be either a direct jump, where the jump target is encoded as part of the instruction, or an indirect jump, where the jump target is read from a register or a memory location. Direct jumps are written in assembly by giving a label as the jump target, e.g., the label “.L1” in the code above. Indirect jumps are written using ‘*’ followed by an operand specifier using the same syntax as used for the movl instruction. As examples, the instruction jmp *%eax uses the value in register %eax as the jump target, while 3.6. CONTROL jmp *(%eax) 115 reads the jump target from memory, using the value in %eax as the read address. The other jump instructions either jump or continue executing at the next instruction in the code sequence depending on some combination of the condition codes. Note that the names of these instructions and the conditions under which they jump match those of the set instructions. As with the set instructions, some of the underlying machine instructions have multiple names. Conditional jumps can only be direct. Although we will not concern ourselves with the detailed format of object code, understanding how the targets of jump instructions are encoded will become important when we study linking in Chapter 7. In addition, it helps when interpreting the output of a disassembler. In assembly code, jump targets are written using symbolic labels. The assembler, and later the linker, generate the proper encodings of the jump targets. There are several different encodings for jumps, but some of the most commonly used ones are PC-relative. That is, they encode the difference between the address of the target instruction and the address of the instruction immediately following the jump. These offsets can be encoded using one, two, or four bytes. A second encoding method is to give an “absolute” address, using four bytes to directly specify the target. The assembler and linker select the appropriate encodings of the jump destinations. As an example, the following fragment of assembly code was generated by compiling a file silly.c. It contains two jumps: the jle instruction on line 1 jumps forward to a higher address, while the jg instruction on line 8 jumps back to a lower one. 1 2 3 4 5 6 7 8 9 10 jle .L4 .p2align 4,,7 .L5: movl %edx,%eax sarl $1,%eax subl %eax,%edx testl %edx,%edx jg .L5 .L4: movl %edx,%eax If <, goto dest2 Aligns next instruction to multiple of 8 dest1: If >, goto dest1 dest2: Note that line 2 is a directive to the assembler that causes the address of the following instruction to begin on a multiple of 16, but leaving a maximum of 7 wasted bytes. This directive is intended to allow the processor to make optimal use of the instruction cache memory. The disassembled version of the “.o” format generated by the assembler is as follows: 1 2 3 4 5 6 7 8 8: a: 10: 12: 15: 17: 19: 1b: 7e 8d 89 c1 29 85 7f 89 11 b6 00 00 00 00 d0 f8 01 c2 d2 f5 d0 jle lea mov sar sub test jg mov 1b <silly+0x1b> 0x0(%esi),%esi %edx,%eax $0x1,%eax %eax,%edx %edx,%edx 10 <silly+0x10> %edx,%eax Target = dest2 Added nops dest1: Target = dest1 dest2: The “lea 0x0(%esi),%esi” instruction in line 2 has no real effect. It serves as a 6-byte nop so that the next instruction (line 3) has a starting address that is a multiple of 16. 116 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS In the annotations generated by the disassembler on the right, the jump targets are indicated explicitly as 0x1b for instruction 1 and 0x10 for instruction 7. Looking at the byte encodings of the instructions, however, we see that the target of jump instruction 1 is encoded (in the second byte) as 0x11 (decimal 17). Adding this to 0xa (decimal 10), the address of the following instruction, we get jump target address 0x1b (decimal 27), the address of instruction 8. Similarly, the target of jump instruction 7 is encoded as 0xf5 (decimal ½½) using a single-byte, two’s complement representation. Adding this to 0x1b (decimal 27), the address of instruction 8, we get 0x10 (decimal 16), the address of instruction 3. The following shows the disassembled version of the program after linking: 1 2 3 4 5 6 7 8 80483c8: 80483ca: 80483d0: 80483d2: 80483d5: 80483d7: 80483d9: 80483db: 7e 8d 89 c1 29 85 7f 89 11 b6 00 00 00 00 d0 f8 01 c2 d2 f5 d0 jle lea mov sar sub test jg mov 80483db <silly+0x1b> 0x0(%esi),%esi %edx,%eax $0x1,%eax %eax,%edx %edx,%edx 80483d0 <silly+0x10> %edx,%eax The instructions have been relocated to different addresses, but the encodings of the jump targets in lines 1 and 7 remain unchanged. By using a PC-relative encoding of the jump targets, the instructions can be compactly encoded (requiring just two bytes), and the object code can be shifted to different positions in memory without alteration. Practice Problem 3.8: In the following excerpts from a disassembled binary, some of the information has been replaced by X’s. Determine the following information about these instructions. A. What is the target of the jbe instruction below? 8048d1c: 8048d1e: 76 da eb 24 jbe jmp XXXXXXX 8048d44 B. What is the address of the mov instruction? XXXXXXX: XXXXXXX: eb 54 c7 45 f8 10 00 jmp mov 8048d44 $0x10,0xfffffff8(%ebp) C. In the following, the jump target is encoded in PC-relative form as a 4-byte, two’s complement number. The bytes are listed from least significant to most, reflecting the little endian byte ordering of IA32. What is the address of the jump target? 8048902: 8048907: e9 cb 00 00 00 90 jmp nop XXXXXXX D. Explain the relation between the annotation on the right and the byte coding on the left. Both lines are part of the encoding of the jmp instruction. 80483f0: 80483f5: ff 25 e0 a2 04 08 jmp *0x804a2e0 3.6. CONTROL 117 To implement the control constructs of C, the compiler must use the different types of jump instructions we have just seen. We will go through the most common constructs, starting from simple conditional branches, and then considering loops and switch statements. 3.6.4 Translating Conditional Branches Conditional statements in C are implemented using combinations of conditional and unconditional jumps. For example, Figure 3.11 shows the C code for a function that computes the absolute value of the difference of two numbers (a). G CC generates the assembly code shown as (c). We have created a version in C, called gotodiff (b), that more closely follows the control flow of this assembly code. It uses the goto statement in C, which is similar to the unconditional jump of assembly code. The statement goto less on line 6 causes a jump to the label less on line 8, skipping the statement on line 7. Note that using goto statements is generally considered a bad programming style, since their use can make code very difficult to read and debug. We use them in our presentation as a way to construct C programs that describe the control flow of assembly-code programs. We call such C programs “goto code.” The assembly code implementation first compares the two operands (line 3), setting the condition codes. If the comparison result indicates that x is less than y, it then jumps to a block of code that computes x-y (line 9). Otherwise it continues with the execution of code that computes y-x (lines 5 and 6). In both cases the computed result is stored in register %eax, and ends up at line 10, at which point it executes the stack completion code (not shown). The general form of an if-else statement in C is given by the if-else statement following template: if (test-expr) then-statement else else-statement where test-expr is an integer expression that evaluates either to 0 (interpreted as meaning “false”) or to a nonzero value (interpreted as meaning “true”). Only one of the two branch statements (then-statement or else-statement) is executed. For this general form, the assembly implementation typically follows the form shown below, where we use C syntax to describe the control flow: t = test-expr; if (t) goto true; else-statement goto done; true: then-statement done: 118 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS code/asm/abs.c 1 2 3 4 5 6 7 code/asm/abs.c 1 2 3 4 5 6 7 8 9 10 11 12 13 int absdiff(int x, int y) { if (x < y) return y - x; else return x - y; } code/asm/abs.c int gotodiff(int x, int y) { int rval; if (x < y) goto less; rval = x - y; goto done; less: rval = y - x; done: return rval; } code/asm/abs.c (a) Original C code. (b) Equivalent goto version of (a). 1 2 3 4 5 6 7 8 9 10 movl 8(%ebp),%edx movl 12(%ebp),%eax cmpl %eax,%edx jl .L3 subl %eax,%edx movl %edx,%eax jmp .L5 .L3: subl %edx,%eax .L5: Get x Get y Compare x:y If <, goto less: Compute y-x Set as return value Goto done: less: Compute x-y as return value done: Begin completion code (c) Generated assembly code. Figure 3.11: Compilation of Conditional Statements C procedure absdiff (a) contains an if-else statement. The generated assembly code is shown (c), along with a C procedure gotodiff (b) that mimics the control flow of the assembly code. The stack set-up and completion portions of the assembly code have been omitted 3.6. CONTROL 119 That is, the compiler generates separate blocks of code for then-statement and else-statement. It inserts conditional and unconditional branches to make sure the correct block is executed. Practice Problem 3.9: When given the following C code: code/asm/simple-if.c 1 2 3 4 5 void cond(int a, int *p) { if (p && a > 0) *p += a; } code/asm/simple-if.c GCC generates the following assembly code. movl 8(%ebp),%edx movl 12(%ebp),%eax testl %eax,%eax je .L3 testl %edx,%edx jle .L3 addl %edx,(%eax) .L3: 1 2 3 4 5 6 7 8 A. Write a goto version in C that performs the same computation and mimics the control flow of the assembly code, in the style shown in Figure 3.11(b). You might find it helpful to first annotate the assembly code as we have done in our examples. B. Explain why the assembly code contains two conditional branches, even though the C code has only one if statement. 3.6.5 Loops C provides several looping constructs, namely while, for, and do-while. No corresponding instructions exist in assembly. Instead, combinations of conditional tests and jumps are used to implement the effect of loops. Interestingly, most compilers generate loop code based on the do-while form of a loop, even though this form is relatively uncommon in actual programs. Other loops are transformed into do-while form and then compiled into machine code. We will study the translation of loops as a progression, starting with do-while and then working toward ones with more complex implementations. Do-While Loops The general form of a do-while statement is as follows: 120 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS do body-statement while (test-expr); The effect of the loop is to repeatedly execute body-statement, evaluate test-expr and continue the loop if the evaluation result is nonzero. Observe that body-statement is executed at least once. Typically, the implementation of do-while has the following general form: loop: body-statement t = test-expr; if (t) goto loop; As an example, Figure 3.12 shows an implementation of a routine to compute the Òth element in the Fibonacci sequence using a do-while loop. This sequence is defined by the recurrence: ½ ¾ Ò ½ ½ Ò ¾ · Ò ¿ Ò ¿ For example, the first ten elements of the sequence are 1, 1, 2, 3, 5, 8, 13, 21, 34, and 55. To implement this using a do-while loop, we have started the sequence with values ¼ ¼ and ½ ½, rather than with ½ and ¾ . The assembly code implementing the loop is also shown, along with a table showing the correspondence between registers and program values. In this example, body-statement consists of lines 8 through 11, assigning values to t, val, and nval, along with the incrementing of i. These are implemented by lines 2 through 5 of the assembly code. The expression i < n comprises test-expr. This is implemented by line 6 and by the test condition of the jump instruction on line 7. Once the loop exits, val is copy to register %eax as the return value (line 8). Creating a table of register usage, such as we have shown in Figure 3.12(b) is a very helpful step in analyzing an assembly language program, especially when loops are present. Practice Problem 3.10: For the following C code: 1 2 3 4 5 6 int dw_loop(int x, int y, int n) { do { x += n; y *= n; n--; 3.6. CONTROL 121 code/asm/fib.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 int fib_dw(int n) { int i = 0; int val = 0; int nval = 1; do { int t = val + nval; val = nval; nval = t; i++; } while (i < n); return val; } code/asm/fib.c (a) C code. 1 2 3 4 5 6 7 8 Register Usage Register Variable Initially %ecx i 0 %esi n n %ebx val 0 %edx nval 1 %eax t – .L6: leal (%edx,%ebx),%eax movl %edx,%ebx movl %eax,%edx incl %ecx cmpl %esi,%ecx jl .L6 movl %ebx,%eax loop: Compute t = val + nval copy nval to val Copy t to nval Increment i Compare i:n If less, goto loop Set val as return value (b) Corresponding assembly language code. Figure 3.12: C and Assembly Code for Do-While Version of Fibonacci Program. Only the code inside the loop is shown. 122 7 8 9 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS } while ((n > 0) & (y < n)); /* Note use of bitwise ’&’ */ return x; } generates the following assembly code: Initially x, y, and n are at offsets 8, 12, and 16 from %ebp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 GCC movl 8(%ebp),%esi movl 12(%ebp),%ebx movl 16(%ebp),%ecx .p2align 4,,7 Inserted to optimize cache performance .L6: imull %ecx,%ebx addl %ecx,%esi decl %ecx testl %ecx,%ecx setg %al cmpl %ecx,%ebx setl %dl andl %edx,%eax testb $1,%al jne .L6 A. Make a table of register usage, similar to the one shown in Figure 3.12(b). B. Identify test-expr and body-statement in the C code, and the corresponding lines in the assembly code. C. Add annotations to the assembly code describing the operation of the program, similar to those shown in Figure 3.12(b). While Loops The general form of a while statement is as follows: while (test-expr) body-statement It differs from do-while in that test-expr is evaluated and the loop is potentially terminated before the first execution of body-statement. A direct translation into a form using goto’s would be: 3.6. CONTROL loop: t = test-expr; if (!t) goto done; body-statement goto loop; done: 123 This translation requires two control statements within the inner loop—the part of the code that is executed the most. Instead, most C compilers transform the code into a do-while loop by using a conditional branch to skip the first execution of the body if needed: if (!test-expr) goto done; do body-statement while (test-expr); done: This, in turn, can be transformed into goto code as: t = test-expr; if (!t) goto done; loop: body-statement t = test-expr; if (t) goto loop; done: As an example, Figure 3.13 shows an implementation of the Fibonacci sequence function using a while loop (a). Observe that this time we have started the recursion with elements ½ (val) and ¾ (nval). The adjacent C function fib_w_goto (b) shows how this code has been translated into assembly. The assembly code in (c) closely follows the C code shown in fib_w_goto. The compiler has performed several interesting optimizations, as can be seen in the goto code (b). First, rather than using variable i as a loop variable and comparing it to n on each iteration, the compiler has introduced a new loop variable that we call “nmi”, since relative to the original code, its value equals Ò . This allows the compiler to use only three registers for loop variables, compared to four otherwise. Second, it has optimized the initial test condition (i < n) into (val < n), since the initial values of both i and val are 1. By this means, the compiler has totally eliminated variable i. Often the compiler can make use of the initial values of the variables to optimize the initial test. This can make deciphering the assembly code tricky. Third, for 124 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS code/asm/fib.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 code/asm/fib.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 int fib_w(int n) { int i = 1; int val = 1; int nval = 1; while (i < n) { int t = val+nval; val = nval; nval = t; i++; } return val; } code/asm/fib.c int fib_w_goto(int n) { int val = 1; int nval = 1; int nmi, t; if (val >= n) goto done; nmi = n-1; loop: t = val+nval; val = nval; nval = t; nmi--; if (nmi) goto loop; done: return val; } code/asm/fib.c 17 18 19 20 21 (a) C code. 1 2 3 4 5 6 7 8 9 10 11 12 13 (b) Equivalent goto version of (a). movl 8(%ebp),%eax movl $1,%ebx movl $1,%ecx cmpl %eax,%ebx jge .L9 leal -1(%eax),%edx .L10: leal (%ecx,%ebx),%eax movl %ecx,%ebx movl %eax,%ecx decl %edx jnz .L10 .L9: Get n Set val to 1 Set nval to 1 Compare val:n If >= goto done: nmi = n-1 loop: Compute t = nval+val Set val to nval Set nval to t Decrement nmi if != 0, goto loop: done: Register Usage Register Variable Initially %edx nmi n-1 %ebx val 1 %ecx nval 1 (c) Corresponding assembly language code. Figure 3.13: C and Assembly Code for While Version of Fibonacci. The compiler has performed a number of optimizations, including replacing the value denoted by variable i with one we call nmi. 3.6. CONTROL 125 successive executions of the loop we are assured that Ò, and so the compiler can assume that nmi is nonnegative. As a result, it can test the loop condition as nmi != 0 rather than nmi >= 0. This saves one instruction in the assembly code. Practice Problem 3.11: For the following C code: 1 2 3 4 5 6 7 8 9 10 11 int loop_while(int a, int b) { int i = 0; int result = a; while (i < 256) { result += a; a -= b; i += b; } return result; } generates the following assembly code: Initially a and b are at offsets 8 and 12 from %ebp GCC 1 2 3 4 5 6 7 8 9 10 11 movl 8(%ebp),%eax movl 12(%ebp),%ebx xorl %ecx,%ecx movl %eax,%edx .p2align 4,,7 .L5: addl %eax,%edx subl %ebx,%eax addl %ebx,%ecx cmpl $255,%ecx jle .L5 A. Make a table of register usage within the loop body, similar to the one shown in Figure 3.13(c). B. Identify test-expr and body-statement in the C code, and the corresponding lines in the assembly code. What optimizations has the C compiler performed on the initial test? C. Add annotations to the assembly code describing the operation of the program, similar to those shown in Figure 3.13(c). D. Write a goto version (in C) of the function that has similar structure to the assembly code, as was done in Figure 3.13(b). 126 For Loops CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS The general form of a for loop is as follows: for (init-expr; test-expr; update-expr) body-statement The C language standard states that the behavior of such a loop is identical to the following code using a while loop: init-expr; while (test-expr) body-statement update-expr; That is, the program first evaluates the initialization expression init-expr. It then enters a loop where it first evaluates the test condition test-expr, exiting if the test fails, then executes the body of the loop bodystatement, and finally evaluates the update expression update-expr. The compiled form of this code then is based on the transformation from while to do-while described previously, first giving a do-while form: init-expr; if (!test-expr) goto done; do body-statement update-expr; while (test-expr); done: This, in turn, can be transformed into goto code as: 3.6. CONTROL init-expr; t = test-expr; if (!t) goto done; loop: body-statement update-expr; t = test-expr; if (t) goto loop; done: 127 As an example, the following code shows an implementation of the Fibonacci function using a for loop: code/asm/fib.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 int fib_f(int n) { int i; int val = 1; int nval = 1; for (i = 1; i < n; i++) { int t = val+nval; val = nval; nval = t; } return val; } code/asm/fib.c The transformation of this code into the while loop form gives code identical to that for the function fib_w shown in Figure 3.13. In fact, GCC generates identical assembly code for the two functions. Practice Problem 3.12: The following assembly code: Initially x, y, and n are offsets 8, 12, and 16 from %ebp 1 2 3 4 5 6 movl 8(%ebp),%ebx movl 16(%ebp),%edx xorl %eax,%eax decl %edx js .L4 movl %ebx,%ecx 128 7 8 9 10 11 12 13 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS imull 12(%ebp),%ecx .p2align 4,,7 Inserted to optimize cache performance .L6: addl %ecx,%eax subl %ebx,%edx jns .L6 .L4: was generated by compiling C code that had the following overall form 1 2 3 4 5 6 7 8 9 int loop(int x, int y, int n) { int result = 0; int i; for (i = ____; i ____ ; i = ___ ) { result += _____ ; } return result; } Your task is to fill in the missing parts of the C code to get a program equivalent to the generated assembly code. Recall that the result of the function is returned in register %eax. To solve this problem, you may need to do a little bit of guessing about register usage and then see whether that guess makes sense. A. Which registers hold program values result and i? B. What is the initial value of i? C. What is the test condition on i? D. How does i get updated? E. The C expression describing how to increment result in the loop body does not change value from one iteration of the loop to the next. The compiler detected this and moved its computation to before the loop. What is the expression? F. Fill in all the missing parts of the C code. 3.6.6 Switch Statements Switch statements provide a multi-way branching capability based on the value of an integer index. They are particularly useful when dealing with tests where there can be a large number of possible outcomes. Not only do they make the C code more readable, they also allow an efficient implementation using a data structure called a jump table. A jump table is an array where entry is the address of a code segment implementing the action the program should take when the switch index equals . The code performs an array reference into the jump table using the switch index to determine the target for a jump instruction. The advantage of using a jump table over a long sequence of if-else statements is that the time taken to perform the switch is independent of the number of switch cases. G CC selects the method of translating a switch statement based on the number of cases and the sparsity of the case values. Jump tables are used when there are a number of cases (e.g., four or more) and they span a small range of values. 3.6. CONTROL 129 code/asm/switch.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 code/asm/switch.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 int switch_eg(int x) { int result = x; switch (x) { case 100: result *= 13; break; case 102: result += 10; /* Fall through */ case 103: result += 11; break; case 104: case 106: result *= result; break; default: result = 0; } return result; } code/asm/switch.c /* Next line is not legal C */ code *jt[7] = { loc_A, loc_def, loc_B, loc_C, loc_D, loc_def, loc_D }; int switch_eg_impl(int x) { unsigned xi = x - 100; int result = x; if (xi > 6) goto loc_def; /* Next goto is not legal C */ goto jt[xi]; loc_A: /* Case 100 */ result *= 13; goto done; loc_B: /* Case 102 */ result += 10; /* Fall through */ loc_C: /* Case 103 */ result += 11; goto done; loc_D: /* Cases 104, 106 */ result *= result; goto done; loc_def: /* Default case*/ result = 0; done: return result; } code/asm/switch.c (a) Switch statement. (b) Translation into extended C. Figure 3.14: Switch Statement Example with Translation into Extended C. The translation shows the structure of jump table jt and how it is accessed. Such tables and accesses are not actually allowed in C. 130 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Set up the jump table access 1 2 3 4 leal -100(%edx),%eax cmpl $6,%eax ja .L9 jmp *.L10(,%eax,4) Case 100 Compute xi = x-100 Compare xi:6 if >, goto done Goto jt[xi] 5 6 7 8 .L4: leal (%edx,%edx,2),%eax leal (%edx,%eax,4),%edx jmp .L3 Case 102 loc A: Compute 3*x Compute x+4*3*x Goto done 9 10 .L5: addl $10,%edx Case 103 loc B: result += 10, Fall through 11 12 13 .L6: addl $11,%edx jmp .L3 Cases 104, 106 loc C: result += 11 Goto done 14 15 16 .L8: imull %edx,%edx jmp .L3 Default case loc D: result *= result Goto done 17 18 .L9: xorl %edx,%edx Return result loc def: result = 0 19 20 .L3: movl %edx,%eax done: Set result as return value Figure 3.15: Assembly Code for Switch Statement Example in Figure 3.14. 3.6. CONTROL 131 Figure 3.14(a) shows an example of a C switch statement. This example has a number of interesting features, including case labels that do not span a contiguous range (there are no labels for cases 101 and 105), cases with multiple labels (cases 104 and 106), and cases that “fall through” to other cases (case 102), because the code for the case does not end with a break statement. Figure 3.15 shows the assembly code generated when compiling switch_eg. The behavior of this code is shown using an extended form of C as the procedure switch_eg_impl in Figure 3.14(b). We say “extended” because C does not provide the necessary constructs to support this style of jump table, and hence our code is not legal C. The array jt contains 7 entries, each of which is the address of a block of code. We extend C with a data type code for this purpose. Lines 1 to 4 set up the jump table access. To make sure that values of x that are either less than 100 or greater than 106 cause the computation specified by the default case, the code generates an unsigned value xi equal to x-100. For values of x between 100 and 106, xi will have values 0 through 6. All other values will be greater than 6, since negative values of x-100 will wrap around to be very large unsigned numbers. The code therefore uses the ja (unsigned greater) instruction to jump to code for the default case when xi is greater than 6. Using jt to indicate the jump table, the code then performs a jump to the address at entry xi in this table. Note that this form of goto is not legal C. Instruction 4 implements the jump to an entry in the jump table. Since it is an indirect jump, the target is read from memory. The effective address of the read is determined by adding the base address specified by label .L10 to the scaled (by 4 since each jump table entry is 4 bytes) value of variable xi (in register %eax). In the assembly code, the jump table is indicated by the following declarations, to which we have added comments: 1 2 3 4 5 6 7 8 9 10 .section .rodata .align 4 .L10: .long .L4 .long .L9 .long .L5 .long .L6 .long .L8 .long .L9 .long .L8 Align address to multiple of 4 Case Case Case Case Case Case Case 100: 101: 102: 103: 104: 105: 106: loc_A loc_def loc_B loc_C loc_D loc_def loc_D These declarations state that within the segment of the object code file called “.rodata” (for “Read-Only Data”), there should be a sequence of seven “long” (4-byte) words, where the value of each word is given by the instruction address associated with the indicated assembly code labels (e.g., .L4). Label .L10 marks the start of this allocation. The address associated with this label serves as the base for the indirect jump (instruction 4). The code blocks starting with labels loc_A through loc_D and loc_def in switch_eg_impl (Figure 3.14(b)) implement the five different branches of the switch statement. Observe that the block of code labeled loc_def will be executed either when x is outside the range 100 to 106 (by the initial range checking) or when it equals either 101 or 105 (based on the jump table). Note how the code for the block labeled loc_B falls through to the block labeled loc_C. 132 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Practice Problem 3.13: In the following C function, we have omitted the body of the switch statement. In the C code, the case labels did not span a contiguous range, and some cases had multiple labels. int switch2(int x) { int result = 0; switch (x) { /* Body of switch statement omitted */ } return result; } In compiling the function, GCC generates the following assembly code for the initial part of the procedure and for the jump table. Variable x is initially at offset 8 relative to register %ebp. 1 2 3 4 5 Setting up jump table access movl 8(%ebp),%eax Retrieve x Jump table for switch2 1 2 3 4 5 6 7 8 addl $2,%eax cmpl $6,%eax ja .L10 jmp *.L11(,%eax,4) .L11: .long .long .long .long .long .long .long .L4 .L10 .L5 .L6 .L8 .L8 .L9 From this determine: A. What were the values of the case labels in the switch statement body? B. What cases had multiple labels in the C code? 3.7 Procedures A procedure call involves passing both data (in the form of procedure parameters and return values) and control from one part of the code to another. In addition, it must allocate space for the local variables of the procedure on entry and deallocate them on exit. Most machines, including IA32, provide only simple instructions for transferring control to and from procedures. The passing of data and the allocation and deallocation of local variables is handled by manipulating the program stack. 3.7.1 Stack Frame Structure IA32 programs make use of the program stack to support procedure calls. The stack is used to pass procedure arguments, to store return information, to save registers for later restoration, and for local storage. The portion of the stack allocated for a single procedure call is called a stack frame. Figure 3.16 diagrams the general structure of a stack frame. The topmost stack frame is delimited by two pointers, with register %ebp serving as the frame pointer, and register %esp serving as the stack pointer. The stack pointer can move while the procedure is executing, and hence most information is accessed relative to the frame pointer. 3.7. PROCEDURES 133 Stack Bottom +4n+4 Passed Arg. n • • • +8 Frame Pointer %ebp +4 -4 Passed Arg. 1 Return Address Saved %ebp Saved Registers Increasing Address Locals and Temporaries Stack Pointer %esp Argument Build Area Stack Top Figure 3.16: Stack Frame Structure. The stack is used for passing arguments, for storing return information, for saving registers, and for local storage. • • • Caller’s Frame Current Frame 134 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Suppose procedure P (the caller) calls procedure Q (the callee). The arguments to Q are contained within the stack frame for P. In addition, when P calls Q, the return address within P where the program should resume execution when it returns from Q is pushed on the stack, forming the end of P’s stack frame. The stack frame for Q starts with the saved value of the frame pointer (i.e., %ebp). followed by copies of any other saved register values. Procedure Q also uses the stack for any local variables that cannot be stored in registers. This can occur for the following reasons: ¯ ¯ ¯ There are not enough registers to hold all of the local data. Some of the local variables are arrays or structures and hence must be accessed by array or structure references. The address operator ‘&’ is applied to one of the local variables, and hence we must be able to generate an address for it. Finally, Q will use the stack frame for storing arguments to any procedures it calls. As described earlier, the stack grows toward lower addresses and the stack pointer %esp points to the top element of the stack. Data can be stored on and retrieved from the stack using the pushl and popl instructions. Space for data with no specified initial value can be allocated on the stack by simply decrementing the stack pointer by an appropriate amount. Similarly, space can be deallocated by incrementing the stack pointer. 3.7.2 Transferring Control The instructions supporting procedure calls and returns are as follows: Instruction call Label call *Operand leave ret Description Procedure Call Procedure Call Prepare stack for return Return from call The call instruction has a target indicating the address of the instruction where the called procedure starts. Like jumps, a call can either be direct or indirect. In assembly code, the target of a direct call is given as a label, while the target of an indirect call is given by a * followed by an operand specifier having the same syntax as is used for the operands of the movl instruction (Figure 3.3). The effect of a call instruction is to push a return address on the stack and jump to the start of the called procedure. The return address is the address of the instruction immediately following the call in the program, so that execution will resume at this location when the called procedure returns. The ret instruction pops an address off the stack and jumps to this location. The proper use of this instruction is to have prepared the stack so that the stack pointer points to the place where the preceding call instruction stored its return address. The leave instruction can be used to prepare the stack for returning. It is equivalent to the following code sequence: 3.7. PROCEDURES 1 2 135 Set stack pointer to beginning of frame Restore saved %ebp and set stack ptr to end of caller’s frame movl %ebp, %esp popl %ebp Alternatively, this preparation can be performed by an explicit sequence of move and pop operations. Register %eax is used for returning the value of any function that returns an integer or pointer. Practice Problem 3.14: The following code fragment occurs often in the compiled version of library routines: 1 2 3 call next next: popl %eax A. To what value does register %eax get set? B. Explain why there is no matching ret instruction to this call. C. What useful purpose does this code fragment serve? 3.7.3 Register Usage Conventions The set of program registers acts as a single resource shared by all of the procedures. Although only one procedure can be active at a given time, we must make sure that when one procedure (the caller) calls another (the callee), the callee does not overwrite some register value that the caller planned to use later. For this reason, IA32 adopts a uniform set of conventions for register usage that must be respected by all procedures, including those in program libraries. By convention, registers %eax, %edx, and %ecx are classified as caller save registers. When procedure Q is called by P, it can overwrite these registers without destroying any data required by P. On the other hand, registers %ebx, %esi, and %edi are classified as callee save registers. This means that Q must save the values of any of these registers on the stack before overwriting them, and restore them before returning, because P (or some higher level procedure) may need these values for its future computations. In addition, registers %ebp and %esp must be maintained according to the conventions described here. Aside: Why the names “callee save” and “caller save?” Consider the following scenario: int P() { int x = f(); Q(); return x; } /* Some computation */ Procedure P wants the value it has computed for x to remain valid across the call to Q. If x is in a caller save register, then P (the caller) must save the value before calling P and restore it after Q returns. If x is in a callee save register, and Q (the callee) wants to use this register, then Q must save the value before using the register and restore it before returning. In either case, saving involves pushing the register value onto the stack, while restoring involves popping from the stack back to the register. End Aside. 136 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS As an example, consider the following code: 1 2 3 4 5 6 7 int P(int x) { int y = x*x; int z = Q(y); return y + z; } Procedure P computes y before calling Q, but it must also ensure that the value of y is available after Q returns. It can do this by one of two means: ¯ ¯ Store the value of y in its own stack frame before calling Q. When Q returns, it can then retrieve the value of y from the stack. Store the value of y in a callee save register. If Q, or any procedure called by Q, wants to use this register, it must save the register value in its stack frame and restore the value before it returns. Thus, when Q returns to P, the value of y will be in the callee save register, either because the register was never altered or because it was saved and restored. GCC Most commonly, and reads. uses the latter convention, since it tends to reduce the total number of stack writes Practice Problem 3.15: The following code sequence occurs right near the beginning of the assembly code generated by for a C procedure: 1 2 3 4 5 6 7 8 9 GCC pushl %edi pushl %esi pushl %ebx movl 24(%ebp),%eax imull 16(%ebp),%eax movl 24(%ebp),%ebx leal 0(,%eax,4),%ecx addl 8(%ebp),%ecx movl %ebx,%edx We see that just three registers (%edi, %esi, and %ebx) are saved on the stack. The program then modifies these and three other registers (%eax, %ecx, and %edx). At the end of the procedure, the values of registers %edi, %esi, and %ebx are restored using popl instructions, while the other three are left in their modified states. Explain this apparently inconsistency in the saving and restoring of register states. 3.7. PROCEDURES 137 code/asm/swapadd.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 int swap_add(int *xp, int *yp) { int x = *xp; int y = *yp; *xp = y; *yp = x; return x + y; } int caller() { int arg1 = 534; int arg2 = 1057; int sum = swap_add(&arg1, &arg2); int diff = arg1 - arg2; return sum * diff; } code/asm/swapadd.c Figure 3.17: Example of Procedure Definition and Call. 3.7.4 Procedure Example As an example, consider the C procedures defined in Figure 3.17. Figure 3.18 shows the stack frames for the two procedures. Observe that swap_add retrieves its arguments from the stack frame for caller. These locations are accessed relative to the frame pointer in register %ebp. The numbers along the left of the frames indicate the address offsets relative to the frame pointer. The stack frame for caller includes storage for local variables arg1 and arg2, at positions and relative to the frame pointer. These variables must be stored on the stack, since we must generate addresses for them. The following assembly code from the compiled version of caller shows how it calls swap_add. Calling code in caller 1 2 3 4 5 leal -4(%ebp),%eax pushl %eax leal -8(%ebp),%eax pushl %eax call swap_add Compute &arg2 Push &arg2 Compute &arg1 Push &arg1 Call the swap_add function Observe that this code computes the addresses of local variables arg2 and arg1 (using the leal instruction) and pushes them on the stack. It then calls swap_add. The compiled code for swap_add has three parts: the “setup,” where the stack frame is initialized; the “body,” where the actual computation of the procedure is performed; and the “finish,” where the stack state 138 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Stack Frame for caller %ebp 0 -4 -8 - 12 %esp - 16 Stack Frame for caller • • • +12 +8 +4 %ebp %esp 0 -4 yp (= &arg2) xp (= &arg1) Return Address Saved %ebp Saved %ebx Stack Frame for swap_add Saved %ebp arg2 arg1 &arg2 &arg1 Figure 3.18: Stack Frames for caller and swap add. Procedure swap add retrieves its arguments from the stack frame for caller. is restored and the procedure returns. The following is the setup code for swap_add. Recall that the call instruction will already push the return address on the stack. Setup code in swap_add 1 2 3 4 swap_add: pushl %ebp movl %esp,%ebp pushl %ebx Save old %ebp Set %ebp as frame pointer Save %ebx Procedure swap_add requires register %ebx for temporary storage. Since this is a callee save register, it pushes the old value on the stack as part of the stack frame setup. The following is the body code for swap_add: Body code in swap_add 1 2 3 4 5 6 7 movl movl movl movl movl movl addl 8(%ebp),%edx 12(%ebp),%ecx (%edx),%ebx (%ecx),%eax %eax,(%edx) %ebx,(%ecx) %ebx,%eax Get xp Get yp Get x Get y Store y at *xp Store x at *yp Set return value = x+y This code retrieves its arguments from the stack frame for caller. Since the frame pointer has shifted, the locations of these arguments has shifted from positions ½¾ and ½ relative to the old value of %ebp to positions ·½¾ and · relative to new value of %ebp. Observe that the sum of variables x and y is stored in register %eax to be passed as the returned value. The following is the finishing code for swap_add: Finishing code in swap_add 1 2 3 4 popl %ebx movl %ebp,%esp popl %ebp ret Restore %ebx Restore %esp Restore %ebp Return to caller 3.7. PROCEDURES 139 This code simply restores the values of the three registers %ebx, %esp, and %ebp, and then executes the ret instruction. Note that instructions F2 and F3 could be replaced by a single leave instruction. Different versions of GCC seem to have different preferences in this regard. The following code in caller comes immediately after the instruction calling swap_add: 1 movl %eax,%edx Resume here Upon return from swap_add, procedure caller will resume execution with this instruction. Observe that this instruction copies the return value from %eax to a different register. Practice Problem 3.16: Given the following C function: 1 2 3 4 5 6 int proc(void) { int x,y; scanf("%x %x", &y, &x); return x-y; } generates the following assembly code proc: pushl %ebp movl %esp,%ebp subl $24,%esp addl $-4,%esp leal -4(%ebp),%eax pushl %eax leal -8(%ebp),%eax pushl %eax pushl $.LC0 Pointer to string "%x %x" call scanf Diagram stack frame at this point GCC 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 movl movl subl movl movl popl ret -8(%ebp),%eax -4(%ebp),%edx %eax,%edx %edx,%eax %ebp,%esp %ebp Assume that procedure proc starts executing with the following register values: Register %esp %ebp Value 0x800040 0x800060 140 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS code/asm/fib.c 1 2 3 4 5 6 7 8 9 10 int fib_rec(int n) { int prev_val, val; if (n <= 2) return 1; prev_val = fib_rec(n-2); val = fib_rec(n-1); return prev_val + val; } code/asm/fib.c Figure 3.19: C Code for Recursive Fibonacci Program. Suppose proc calls scanf (line 12), and that scanf reads values 0x46 and 0x53 from the standard input. Assume that the string "%x %x" is stored at memory location 0x300070. A. What value does %ebp get set to on line 3? B. At what addresses are local variables x and y stored? C. What is the value of %esp at line 11? D. Draw a diagram of the stack frame for proc right after scanf returns. Include as much information as you can about the addresses and the contents of the stack frame elements. E. Indicate the regions of the stack frame that are not used by proc (these wasted areas are allocated to improve the cache performance). 3.7.5 Recursive Procedures The stack and linkage conventions described in the previous section allow procedures to call themselves recursively. Since each call has its own private space on the stack, the local variables of the multiple outstanding calls do not interfere with one another. Furthermore, the stack discipline naturally provides the proper policy for allocating local storage when the procedure is called and deallocating it when it returns. Figure 3.19 shows the C code for a recursive Fibonacci function. (Note that this code is very inefficient—we intend it to be an illustrative example, not a clever algorithm). The complete assembly code is shown as well in Figure 3.20. Although there is a lot of code, it is worth studying closely. The set-up code (lines 2 to 6) creates a stack frame containing the old version of %ebp, 16 unused bytes,2 and saved values for the callee save registers %esi and %ebx, as diagrammed on the left side of Figure 3.21. It then uses register %ebx to hold the procedure parameter n (line 7). In the event of a terminal condition, the code jumps to line 22, where the return value is set to 1. 2 It is unclear why the C compiler allocates so much unused storage on the stack for this function. 3.7. PROCEDURES 141 1 2 3 4 5 6 fib_rec: Setup code pushl %ebp movl %esp,%ebp subl $16,%esp pushl %esi pushl %ebx Body code Save old %ebp Set %ebp as frame Allocate 16 bytes Save %esi (offset Save %ebx (offset pointer on stack -20) -24) 7 8 9 10 11 12 13 14 15 16 17 18 19 20 movl 8(%ebp),%ebx cmpl $2,%ebx jle .L24 addl $-12,%esp leal -2(%ebx),%eax pushl %eax call fib_rec movl %eax,%esi addl $-12,%esp leal -1(%ebx),%eax pushl %eax call fib_rec addl %esi,%eax jmp .L25 Terminal condition Get n Compare n:2 if <=, goto terminate Allocate 12 bytes on stack Compute n-2 Push as argument Call fib_rec(n-2) Store result in %esi Allocate 12 bytes to stack Compute n-1 Push as argument Call fib_rec(n-1) Compute val+nval Go to done 21 22 .L24: movl $1,%eax Finishing code terminate: Return value 1 23 24 25 26 27 28 29 .L25: leal popl popl movl popl ret done: -24(%ebp),%esp %ebx %esi %ebp,%esp %ebp Set stack to offset -24 Restore %ebx Restore %esi Restore stack pointer Restore %ebp Return Figure 3.20: Assembly Code for the Recursive Fibonacci Program in Figure 3.19. 142 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS • • • +8 +4 %ebp 0 n Return Address Saved %ebp Unused -20 -24 Saved %esi Saved %ebx Unused %esp After set up -40 n-2 Before first recursive call • • • +8 +4 %ebp 0 n Return Address Saved %ebp Unused -20 %esp -24 Saved %esi Saved %ebx Stack Frame for calling procedure Stack Frame for fib_rec Figure 3.21: Stack Frame for Recursive Fibonacci Function. State of frame is shown after initial set up (left), and just before the first recursive call (right). For the nonterminal condition, instructions 10 to 12 set up the first recursive call. This involves allocating 12 bytes on the stack that are never used, and then pushing the computed value n-2. At this point, the stack frame will have the form shown on the right side of Figure 3.21. It then makes the recursive call, which will trigger a number of calls that allocate stack frames, perform operations on local storage, and so on. As each call returns, it deallocates any stack space and restores any modified callee save registers. Thus, when we return to the current call at line 14 we can assume that register %eax contains the value returned by the recursive call, and that register %ebx contains the value of function parameter n. The returned value (local variable prev_val in the C code) is stored in register %esi (line 14). By using a callee save register, we can be sure that this value will still be available after the second recursive call. Instructions 15 to 17 set up the second recursive call. Again it allocates 12 bytes that are never used, and pushes the value of n-1. Following this call (line 18), the computed result will be in register %eax, and we can assume that the result of the previous call is in register %esi. These are added to give the return value (instruction 19). The completion code restores the registers and deallocates the stack frame. It starts (line 24) by setting the stack frame to the location of the saved value of %ebx. Observe that by computing this stack position relative to the value of %ebp, the computation will be correct regardless of whether or not the terminal condition was reached. 3.8 Array Allocation and Access Arrays in C are one means of aggregating scalar data into larger data types. C uses a particularly simple implementation of arrays, and hence the translation into machine code is fairly straightforward. One unusual feature of C is that one can generate pointers to elements within arrays and perform arithmetic with these 3.8. ARRAY ALLOCATION AND ACCESS pointers. These are translated into address computations in assembly code. 143 Optimizing compilers are particularly good at simplifying the address computations used by array indexing. This can make the correspondence between the C code and its translation into machine code somewhat difficult to decipher. 3.8.1 Basic Principles For data type Ì and integer constant Æ , the declaration Ì A[Æ ]; has two effects. First, it allocates a contiguous region of Ä ¡ Æ bytes in memory, where Ä is the size (in bytes) of data type Ì . Let us denote the starting location as ÜA . Second, it introduces an identifier A that can be used as a pointer to the beginning of the array. The value of this pointer will be ÜA . The array elements can be accessed using an integer index ranging between ¼ and Æ ½. Array element will be stored at address ÜA · Ä ¡ . As examples, consider the following declarations: char A[12]; char *B[8]; double C[6]; double *D[5]; These declarations will generate arrays with the following parameters: Array A B C D Element Size 1 4 8 4 Total Size 12 32 48 20 Start Address ÜA ÜB ÜC ÜD Element ÜA · ÜB · ÜC · ÜD · Array A consists of 12 single-byte (char) elements. Array C consists of 6 double-precision floating-point values, each requiring 8 bytes. B and D are both arrays of pointers, and hence the array elements are 4 bytes each. The memory referencing instructions of IA32 are designed to simplify array access. For example, suppose E is an array of int’s, and we wish to compute E[i] where the address of E is stored in register %edx and i is stored in register %ecx. Then the instruction: movl (%edx,%ecx,4),%eax will perform the address computation ÜE · , read that memory location, and store the result in register %eax. The allowed scaling factors of 1, 2, 4, and 8 cover the sizes of the primitive data types. Practice Problem 3.17: Consider the following declarations: 144 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS short S[7]; short *T[3]; short **U[6]; long double V[8]; long double *W[4]; Fill in the following table describing the element size, the total size, and the address of element for each of these arrays. Array S T U V W Element Size Total Size Start Address ÜS ÜT ÜU ÜV ÜW Element 3.8.2 Pointer Arithmetic C allows arithmetic on pointers, where the computed value is scaled according to the size of the data type referenced by the pointer. That is, if p is a pointer to data of type Ì , and the value of p is Üp , then the expression p+i has value Üp · Ä ¡ where Ä is the size of data type Ì . The unary operators & and * allow the generation and dereferencing of pointers. That is, for an expression Expr denoting some object, &Expr is a pointer giving the address of the object. For an expression AddrExpr denoting an address, *Addr-Expr gives the value at that address. The expressions Expr and *&Expr are therefore equivalent. The array subscripting operation can be applied to both arrays and pointers. The array reference A[i] is identical to the expression *(A+i). It computes the address of the th array element and then accesses this memory location. Expanding on our earlier example, suppose the starting address of integer array E and integer index i are stored in registers %edx and %ecx, respectively. The following are some expressions involving E. We also show an assembly code implementation of each expression, with the result being stored in register %eax. Expression E E[0] E[i] &E[2] E+i-1 *(&E[i]+i) &E[i]-E Type int * int int int * int * int int Value Å Å Ñ ÜE · ÜE · ÜE · Å Ñ ÜE · · ÜE Ñ ÜE movl movl movl leal leal movl movl Assembly Code %edx,%eax (%edx),%eax (%edx,%ecx,4),%eax 8(%edx),%eax -4(%edx,%ecx,4),%eax (%edx,%ecx,8),%eax %ecx,%eax In these examples, the leal instruction is used to generate an address, while movl is used to reference memory (except in the first case, where it copies an address). The final example shows that one can compute the difference of two pointers within the same data structure, with the result divided by the size of the data type. 3.8. ARRAY ALLOCATION AND ACCESS Practice Problem 3.18: Suppose the address of short integer array S and integer index i are stored in registers %edx and %ecx, respectively. For each of the following expressions, give its type, a formula for its value, and an assembly code implementation. The result should be stored in register %eax if it a pointer and register element %ax if it is a short integer. Expression S+1 S[3] &S[i] S[4*i+1] S+i-5 Type Value Assembly Code 145 3.8.3 Arrays and Loops Array references within loops often have very regular patterns that can be exploited by an optimizing compiler. For example, the function decimal5 shown in Figure 3.22(a) computes the integer represented by an array of 5 decimal digits. In converting this to assembly code, the compiler generates code similar to that shown in Figure 3.22(b) as C function decimal5_opt. First, rather than using a loop index i, it uses pointer arithmetic to step through successive array elements. It computes the address of the final array element and uses a comparison to this address as the loop test. Finally, it can use a do-while loop since there will be at least one loop iteration. The assembly code shown in Figure 3.22(c) shows a further optimization to avoid the use of an integer multiply instruction. In particular, it uses leal (line 5) to compute 5*val as val+4*val. It then uses leal with a scaling factor of 2 (line 7) to scale to 10*val. Aside: Why avoid integer multiply? In older models of the IA32 processor, the integer multiply instruction took as many as 30 clock cycles, and so compilers try to avoid it whenever possible. In the most recent models it requires only 3 clock cycles, and therefore these optimizations are not warranted. End Aside. 3.8.4 Nested Arrays The general principles of array allocation and referencing hold even when we create arrays of arrays. For example, the declaration: int A[4][3]; is equivalent to the declaration: typedef int row3_t[3]; row3_t A[4]; 146 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS code/asm/decimal5.c 1 2 3 4 5 6 7 8 9 10 code/asm/decimal5.c 1 2 3 4 5 6 7 8 9 10 11 12 int decimal5(int *x) { int i; int val = 0; for (i = 0; i < 5; i++) val = (10 * val) + x[i]; return val; } code/asm/decimal5.c int decimal5_opt(int *x) { int val = 0; int *xend = x + 4; do { val = (10 * val) + *x; x++; } while (x <= xend); return val; } code/asm/decimal5.c (a) Original C code (b) Equivalent pointer code Body code 1 2 3 4 5 6 7 8 9 10 movl 8(%ebp),%ecx xorl %eax,%eax leal 16(%ecx),%ebx .L12: leal (%eax,%eax,4),%edx movl (%ecx),%eax leal (%eax,%edx,2),%eax addl $4,%ecx cmpl %ebx,%ecx jbe .L12 Get base addr of array x val = 0; xend = x+4 (16 bytes = 4 double words) loop: Compute 5*val Compute *x Compute *x + 2*(5*val) x++ Compare x:xend if <=, goto loop: (c) Corresponding assembly code. Figure 3.22: C and Assembly Code for Array Loop Example. The compiler generates code similar to the pointer code shown in decimal5 opt. 3.8. ARRAY ALLOCATION AND ACCESS 147 Data type row3_t is defined to be an array of three integers. Array A contains four such elements, each requiring 12 bytes to store the three integers. The total array size is then ¡ ¡ ¿ bytes. Array A can also be viewed as a two-dimensional array with four rows and three columns, referenced as A[0][0] through A[3][2]. The array elements are ordered in memory in “row major” order, meaning all elements of row 0, followed by all elements of row 1, and so on. Element A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] A[2][0] A[2][1] A[2][2] A[3][0] A[3][1] A[3][2] ÜA ÜA · ÜA · ÜA · ½¾ ÜA · ½ ÜA · ¾¼ ÜA · ¾ ÜA · ¾ ÜA · ¿¾ ÜA · ¿ ÜA · ¼ ÜA · Address This ordering is a consequence of our nested declaration. Viewing A as an array of four elements, each of which is an array of three int’s, we first have A[0] (i.e., row 0), followed by A[1], and so on. To access elements of multidimensional arrays, the compiler generates code to compute the offset of the desired element and then uses a movl instruction using the start of the array as the base address and the (possibly scaled) offset as an index. In general, for an array declared as: Ì D[Ê][ ]; As an example, consider the ¢ ¿ integer array A defined earlier. Suppose register %eax contains ÜA , that %edx holds i, and %ecx holds j. Then array element A[i][j] can be copied to register %eax by the following code: A in %eax, i in %edx, j in %ecx 1 2 3 4 array element D[i][j] is at memory address ÜD · Ä´ ¡ · µ , where Ä is the size of data type Ì in bytes. sall leal leal movl $2,%ecx (%edx,%edx,2),%edx (%ecx,%edx,4),%edx (%eax,%edx),%eax j*4 i*3 j * 4 + i * 12 Read Å Ñ ÜA · ´¿ ¡ ·µ Practice Problem 3.19: Consider the source code below, where M and N are constants declared with #define. 1 int mat1[M][N]; 148 2 3 4 5 6 7 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS int mat2[N][M]; int sum_element(int i, int j) { return mat1[i][j] + mat2[j][i]; } In compiling this program, GCC generates the following assembly code: 1 2 3 4 5 6 7 8 9 movl movl leal leal subl addl sall movl addl 8(%ebp),%ecx 12(%ebp),%eax 0(,%eax,4),%ebx 0(,%ecx,8),%edx %ecx,%edx %ebx,%eax $2,%eax mat2(%eax,%ecx,4),%eax mat1(%ebx,%edx,4),%eax Use your reverse engineering skills to determine the values of M and N based on this assembly code. 3.8.5 Fixed Size Arrays The C compiler is able to make many optimizations for code operating on multi-dimensional arrays of fixed size. For example, suppose we declare data type fix_matrix to be ½ ¢ ½ arrays of integers as follows: 1 2 #define N 16 typedef int fix_matrix[N][N]; The code in Figure 3.23(a) computes element of the product of matrices A and B. The C compiler generates code similar to that shown in Figure 3.23(b). This code contains a number of clever optimizations. It recognizes that the loop will access the elements of array A as A[i][0], A[i][1], . . . , A[i][15] in sequence. These elements occupy adjacent positions in memory starting with the address of array element A[i][0]. The program can therefore use a pointer variable Aptr to access these successive locations. The loop will access the elements of array B as B[0][k], B[1][k], . . . , B[15][k] in sequence. These elements occupy positions in memory starting with the address of array element B[0][k] and spaced 64 bytes apart. The program can therefore use a pointer variable Bptr to access these successive locations. In C, this pointer is shown as being incremented by 16, although in fact the actual pointer is incremented by ¡½ . Finally, the code can use a simple counter to keep track of the number of iterations required. We have shown the C code fix_prod_ele_opt to illustrate the optimizations made by the C compiler in generating the assembly. The actual assembly code for the loop is shown below. Aptr is in %edx, Bptr in %ecx, result in %esi, cnt in %ebx loop: Compute t = *Aptr 1 2 .L23: movl (%edx),%eax 3.8. ARRAY ALLOCATION AND ACCESS 149 code/asm/array.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #define N 16 typedef int fix_matrix[N][N]; /* Compute i,k of fixed matrix product */ int fix_prod_ele (fix_matrix A, fix_matrix B, { int j; int result = 0; for (j = 0; j < N; j++) result += A[i][j] * B[j][k]; return result; } code/asm/array.c int i, int k) (a) Original C code code/asm/array.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* Compute i,k of fixed matrix product */ int fix_prod_ele_opt(fix_matrix A, fix_matrix B, int i, int k) { int *Aptr = &A[i][0]; int *Bptr = &B[0][k]; int cnt = N - 1; int result = 0; do { result += (*Aptr) * (*Bptr); Aptr += 1; Bptr += N; cnt--; } while (cnt >= 0); return result; } code/asm/array.c (b) Optimized C code. Figure 3.23: Original and Optimized Code to Compute Element of Matrix Product for Fixed Length Arrays. The compiler performs these optimizations automatically. 150 3 4 5 6 7 8 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS imull (%ecx),%eax addl %eax,%esi addl $64,%ecx addl $4,%edx decl %ebx jns .L23 Compute v = *Bptr * t Add v result Add 64 to Bptr Add 4 to Aptr Decrement cnt if >=, goto loop Note that in the above code, all pointer increments are scaled by a factor of 4 relative to the C code. Practice Problem 3.20: The following C code sets the diagonal elements of a fixed-size array to val 1 2 3 4 5 6 7 /* Set all diagonal elements to val */ void fix_set_diag(fix_matrix A, int val) { int i; for (i = 0; i < N; i++) A[i][i] = val; } When compiled GCC generates the following assembly code: 1 2 3 4 5 6 7 8 9 10 movl 12(%ebp),%edx movl 8(%ebp),%eax movl $15,%ecx addl $1020,%eax .p2align 4,,7 .L50: movl %edx,(%eax) addl $-68,%eax decl %ecx jns .L50 Added to optimize cache performance Create a C code program fix_set_diag_opt that uses optimizations similar to those in the assembly code, in the same style as the code in Figure 3.23(b). 3.8.6 Dynamically Allocated Arrays C only supports multidimensional arrays where the sizes (with the possible exception of the first dimension) are known at compile time. In many applications, we require code that will work for arbitrary size arrays that have been dynamically allocated. For these we must explicitly encode the mapping of multidimensional arrays into one-dimensional ones. We can define a data type var_matrix as simply an int *: typedef int *var_matrix; To allocate and initialize storage for an Ò ¢ Ò array of integers, we use the Unix library function calloc: 3.8. ARRAY ALLOCATION AND ACCESS 1 2 3 4 151 var_matrix new_var_matrix(int n) { return (var_matrix) calloc(sizeof(int), n * n); } The calloc function (documented as part of ANSI C [30, 37]) takes two arguments: the size of each array element and the number of array elements required. It attempts to allocate space for the entire array. If successful, it initializes the entire region of memory to 0s and returns a pointer to the first byte. If insufficient space is available, it returns null. New to C? In C, storage on the heap (a pool of memory available for storing data structures) is allocated using the library function malloc or its cousin calloc. Their effect is similar to that of the new operation in C++ and Java. Both C and C++ require the program to explictly free allocated space using the free function. In Java, freeing is performed automatically by the run-time system via a process called garbage collection, as will be discussed in Chapter 10. End We can then use the indexing computation of row-major ordering to determine the position of element of the matrix as ¡ Ò · : 1 2 3 4 int var_ele(var_matrix A, int i, int j, int n) { return A[(i*n) + j]; } This referencing translates into the following assembly code: 1 2 3 4 5 movl 8(%ebp),%edx movl 12(%ebp),%eax imull 20(%ebp),%eax addl 16(%ebp),%eax movl (%edx,%eax,4),%eax Get A Get i Compute n*i Compute n*i + j Get A[i*n + j] Comparing this code to that used to index into a fixed-size array, we see that the dynamic version is somewhat more complex. It must use a multiply instruction to scale by Ò, rather than a series of shifts and adds. In modern processors, this multiplication does not incur a significant performance penalty. In many cases, the compiler can simplify the indexing computations for variable-sized arrays using the same principles as we saw for fixed-size ones. For example, Figure 3.24(a) shows C code to compute element of the product of two variable-sized matrices A and B. In Figure 3.24(b) we show an optimized version derived by reverse engineering the assembly code generated by compiling the original version. The compiler is able to eliminate the integer multiplications i*n and j*n by exploiting the sequential access pattern resulting from the loop structure. In this case, rather than generating a pointer variable Bptr, the compiler creates an integer variable we call nTjPk, for “n Times j Plus k,” since its value equals n*j+k relative to the original code. Initially nTjPk equals k, and it is incremented by n on each iteration. The assembly code for the loop is shown below. The registers values are: %edx holds cnt, %ebx holds Aptr, %ecx holds nTjPk, and %esi holds result. 152 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS code/asm/array.c 1 2 3 4 5 6 7 8 9 10 11 12 13 typedef int *var_matrix; /* Compute i,k of variable matrix product */ int var_prod_ele(var_matrix A, var_matrix B, int i, int k, int n) { int j; int result = 0; for (j = 0; j < n; j++) result += A[i*n + j] * B[j*n + k]; return result; } code/asm/array.c (a) Original C code code/asm/array.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* Compute i,k of variable matrix product */ int var_prod_ele_opt(var_matrix A, var_matrix B, int i, int k, int n) { int *Aptr = &A[i*n]; int nTjPk = n; int cnt = n; int result = 0; if (n <= 0) return result; do { result += (*Aptr) * B[nTjPk]; Aptr += 1; nTjPk += n; cnt--; } while (cnt); return result; } code/asm/array.c (b) Optimized C code Figure 3.24: Original and Optimized Code to Compute Element of Matrix Product for Variable Length Arrays. The compiler performs these optimizations automatically. 3.9. HETEROGENEOUS DATA STRUCTURES 1 2 3 4 5 6 7 8 9 153 loop: .L37: movl 12(%ebp),%eax movl (%ebx),%edi addl $4,%ebx imull (%eax,%ecx,4),%edi addl %edi,%esi addl 24(%ebp),%ecx decl %edx jnz .L37 Get B Get *Aptr Increment Aptr Multiply by B[nTjPk] Add to result Add n to nTjPk Decrement cnt If cnt <> 0, goto loop Observe that in the above code, variables B and n must be retrieved from memory on each iteration. This is an example of register spilling. There are not enough registers to hold all of the needed temporary data, and hence the compiler must keep some local variables in memory. In this case the compiler chose to spill variables B and n because they are read only—they do not change value within the loop. Spilling is a common problem for IA32, since the processor has so few registers. 3.9 Heterogeneous Data Structures C provides two mechanisms for creating data types by combining objects of different types. Structures, declared using the keyword struct, aggregate multiple objects into a single one. Unions, declared using the keyword union, allow an object to be referenced using any of a number of different types. 3.9.1 Structures The C struct declaration creates a data type that groups objects of possibly different types into a single object. The different components of a structure are referenced by names. The implementation of structures is similar to that of arrays in that all of the components of a structure are stored in a contiguous region of memory, and a pointer to a structure is the address of its first byte. The compiler maintains information about each structure type indicating the byte offset of each field. It generates references to structure elements using these offsets as displacements in memory referencing instructions. New to C? The struct data type constructor is the closest thing C provides to the objects of C++ and Java. It allows the programmer to keep information about some entity in a single data structure, and reference that information with names. For example, a graphics program might represent a rectangle as a structure: struct rect { int llx; int lly; int color; int width; int height; }; /* /* /* /* /* X coordinate of lower-left corner */ Y coordinate of lower-left corner */ Coding of color */ Width (in pixels) */ Height (in pixels) */ We could declare a variable r of type struct rect and set its field values as follows: 154 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS struct rect r; r.llx = r.lly = 0; r.color = 0xFF00FF; r.width = 10; r.height = 20; where the expression r.llx selects field llx of structure r. It is common to pass pointers to structures from one place to another rather than copying them. For example, the following function computes the area of a rectangle, where a pointer to the rectange struct is passed to the function: int area(struct rect *rp) { return (*rp).width * (*rp).height; } The expression (*rp).width dereferences the pointer and selects the width field of the resulting structure. Parentheses are required, because the compiler would interpret the expression *rp.width as *(rp.width), which is not valid. This combination of dereferencing and field selection is so common that C provides an alternative notation using ->. That is, rp->width is equivalent to the expression (*rp).width. For example, we could write a function that rotates a rectangle left by 90 degrees as void rotate_left(struct rect *rp) { /* Exchange width and height */ int t = rp->height; rp->height = rp->width; rp->width = t; } The objects of C++ and Java are more elaborate than structures in C, in that they also associate a set of methods with an object that can be invoked to perform computation. In C, we would simply write these as ordinary functions, such as the functions area and rotate_left shown above. End As an example, consider the following structure declaration: struct rec { int i; int j; int a[3]; int *p; }; This structure contains four fields: two 4-byte int’s, an array consisting of three 4-byte int’s, and a 4-byte integer pointer, giving a total of 24 bytes: Offset Contents 0 i 4 j 8 a[0] 20 a[1] a[2] p 3.9. HETEROGENEOUS DATA STRUCTURES 155 Observe that array a is embedded within the structure. The numbers along the top of the diagram give the byte offsets of the fields from the beginning of the structure. To access the fields of a structure, the compiler generates code that adds the appropriate offset to the address of the structure. For example, suppose variable r of type struct rec * is in register %edx. Then the following code copies element r->i to element r->j: 1 2 movl (%edx),%eax movl %eax,4(%edx) Get r->i Store in r->j Since the offset of field i is 0, the address of this field is simply the value of r. To store into field j, the code adds offset 4 to the address of r. To generate a pointer to an object within a structure, we can simply add the field’s offset to the structure address. For example, we can generate the pointer &(r->a[1]) by adding offset · ¡ ½ ½¾. For pointer r in register %edx and integer variable i in register %eax, we can generate the pointer value &(r->a[i]) with the single instruction: r in %eax, i in %edx 1 leal 8(%eax,%edx,4),%ecx %ecx = &r->a[i] As a final example, the following code implements the statement: r->p = &r->a[r->i + r->j]; starting with r in register %edx: 1 2 3 4 movl addl leal movl 4(%edx),%eax (%edx),%eax 8(%edx,%eax,4),%eax %eax,20(%edx) Get r->j Add r->i Compute &r->[r->i + r->j] Store in r->p As these examples show, the selection of the different fields of a structure is handled completely at compile time. The machine code contains no information about the field declarations or the names of the fields. Practice Problem 3.21: Consider the following structure declaration. struct prob { int *p; struct { int x; int y; } s; struct prob *next; }; This declaration illustrates that one structure can be embedded within another, just as arrays can be embedded within structures, and arrays can be embedded within arrays. The following procedure (with some expressions omitted) operates on this structure: 156 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS void sp_init(struct prob *sp) { sp->s.x = ________; sp->p = ________; sp->next = ________; } A. What are the offsets (in bytes) of the following fields: p: s.x: s.y: next: B. How many total bytes does the structure require? C. The compiler generates the following assembly code for the body of sp_init: 1 2 3 4 5 6 movl movl movl leal movl movl 8(%ebp),%eax 8(%eax),%edx %edx,4(%eax) 4(%eax),%edx %edx,(%eax) %eax,12(%eax) Based on this, fill in the missing expressions in the code for sp_init. 3.9.2 Unions Unions provide a way to circumvent the type system of C, allowing a single object to be referenced according to multiple types. The syntax of a union declaration is identical to that for structures, but its semantics are very different. Rather than having the different fields reference different blocks of memory, they all reference the same block. Consider the following declarations: struct S3 { char c; int i[2]; double v; }; union U3 { char c; int i[2]; double v; }; The offsets of the fields, as well as the total size of data types S3 and U3, are: 3.9. HETEROGENEOUS DATA STRUCTURES Type S3 U3 c 0 0 i 4 0 v 12 0 Size 20 8 157 (We will see shortly why i has offset 4 in S3 rather than 1). For pointer p of type union U3 *, references p->c, p->i[0], and p->v would all reference the beginning of the data structure. Observe also that the overall size of a union equals the maximum size of any of its fields. Unions can be useful in several contexts. However, they can also lead to nasty bugs, since they bypass the safety provided by the C type system. One application is when we know in advance that the use of two different fields in a data structure will be mutually exclusive. Then declaring these two fields as part of a union rather than a structure will reduce the total space allocated. For example, suppose we want to implement a binary tree data structure where each leaf node has a double data value, while each internal node has pointers to two children, but no data. If we declare this as: struct NODE { struct NODE *left; struct NODE *right; double data; }; then every node requires 16 bytes, with half the bytes wasted for each type of node. On the other hand, if we declare a node as: union NODE { struct { union NODE *left; union NODE *right; } internal; double data; }; then every node will require just 8 bytes. If n is a pointer to a node of type union NODE *, we would reference the data of a leaf node as n->data, and the children of an internal node as n->internal.left and n->internal.right. With this encoding, however, there is no way to determine whether a given node is a leaf or an internal node. A common method is to introduce an additional tag field: struct NODE { int is_leaf; union { struct { struct NODE *left; struct NODE *right; } internal; double data; } info; }; 158 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS where the field is_leaf is 1 for a leaf node and is 0 for an internal node. This structure requires a total of 12 bytes: 4 for is_leaf, and either 4 each for info.internal.left and info.internal.right, or 8 for info.data. In this case, the savings gain of using a union is small relative to the awkwardness of the resulting code. For data structures with more fields, the savings can be more compelling. Unions can also be used to access the bit patterns of different data types. For example, the following code returns the bit representation of a float as an unsigned: 1 2 3 4 5 6 7 8 9 unsigned float2bit(float f) { union { float f; unsigned u; } temp; temp.f = f; return temp.u; }; In this code we store the argument in the union using one data type, and access it using another. Interestingly, the code generated for this procedure is identical to that for the procedure: 1 2 3 4 unsigned copy(unsigned u) { return u; } The body of both procedures is just a single instruction: 1 movl 8(%ebp),%eax This demonstrates the lack of type information in assembly code. The argument will be at offset 8 relative to %ebp regardless of whether it is a float or an unsigned. The procedure simply copies its argument as the return value without modifying any bits. When using unions combining data types of different sizes, byte ordering issues can become important. For example suppose we write a procedure that will create an 8-byte double using the bit patterns given by two 4-byte unsigned’s: 1 2 3 4 5 6 7 8 9 10 11 double bit2double(unsigned word0, unsigned word1) { union { double d; unsigned u[2]; } temp; temp.u[0] = word0; temp.u[1] = word1; return temp.d; } 3.9. HETEROGENEOUS DATA STRUCTURES 159 On a little-endian machine such as IA32, argument word0 will become the low-order four bytes of d, while word1 will become the high-order four bytes. On a big-endian machine, the role of the two arguments will be reversed. Practice Problem 3.22: Consider the following union declaration. union ele { struct { int *p; int y; } e1; struct { int x; union ele *next; } e2; }; This declaration illustrates that structures can be embedded within unions. The following procedure (with some expressions omitted) operates on link list having these unions as list elements: void proc (union ele *up) { up->__________ = *(up->__________) - up->__________; } A. What would be the offsets (in bytes) of the following fields: e1.p: e1.y: e2.x: e2.next: B. How many total bytes would the structure require? C. The compiler generates the following assembly code for the body of proc: 1 2 3 4 5 6 7 8 movl movl movl movl movl movl subl movl 8(%ebp),%eax 4(%eax),%edx (%edx),%ecx %ebp,%esp (%eax),%eax (%ecx),%ecx %eax,%ecx %ecx,4(%edx) Based on this, fill in the missing expressions in the code for proc. [Hint: Some union references can have ambiguous interpretations. These ambiguities get resolved as you see where the references lead. There is only one answer that does not perform any casting and does not violate any type constraints.] 160 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS 3.10 Alignment Many computer systems place restrictions on the allowable addresses for the primitive data types, requiring that the address for some type of object must be a multiple of some value (typically 2, 4, or 8). Such alignment restrictions simplify the design of the hardware forming the interface between the processor and the memory system. For example, suppose a processor always fetches 8 bytes from memory with an address that must be a multiple of 8. If we can guarantee that any double will be aligned to have its address be a multiple of 8, then the value can be read or written with a single memory operation. Otherwise, we may need to perform two memory accesses, since the object might be split across two 8-byte memory blocks. The IA32 hardware will work correctly regardless of the alignment of data. However, Intel recommends that data be aligned to improve memory system performance. Linux follows an alignment policy where 2-byte data types (e.g., short) must have an address that is a multiple of 2, while any larger data types (e.g., int, int *, float, and double) must have an address that is a multiple of 4. Note that this requirement means that the least significant bit of the address of an object of type short must equal 0. Similarly, any object of type int, or any pointer, must be at an address having the low-order two bits equal to 0. Aside: Alignment with Microsoft Windows. Microsoft Windows requires a stronger alignment requirement—any -byte (primitive) object must have an address that is a multiple of . In particular, it requires that the address of a double be a multiple of 8. This requirement enhances the memory performance at the expense of some wasted space. The design decision made in Linux was probably good for the i386, back when memory was scarce and memory busses were only 4 bytes wide. With modern processors, Microsoft’s alignment is a better design decision. The command line flag -malign-double causes GCC on Linux to use 8-byte alignment for data of type double. This will lead to improved memory performance, but it can cause incompatibilities when linking with library code that has been compiled assuming a 4-byte alignment. End Aside. Alignment is enforced by making sure that every data type is organized and allocated in such a way that every object within the type satisfies its alignment restrictions. The compiler places directives in the assembly code indicating the desired alignment for global data. For example, the assembly code declaration of the jump table on page 131 contains the following directive on line 2: .align 4 This ensures that the data following it (in this case the start of the jump table) will start with an address that is a multiple of 4. Since each table entry is 4 bytes long, the successive elements will obey the 4-byte alignment restriction. Library routines that allocate memory, such as malloc, must be designed so that they return a pointer that satisfies the worst-case alignment restriction for the machine it is running on, typically 4 or 8. For code involving structures, the compiler may need to insert gaps in the field allocation to ensure that each structure element satisfies its alignment requirement. The structure then has some required alignment for its starting address. For example, consider the structure declaration: struct S1 { 3.10. ALIGNMENT int i; char c; int j; }; 161 Suppose the compiler used the minimal 9-byte allocation, diagrammed as follows: Offset Contents 0 i 4 c 5 j Then it would be impossible to satisfy the 4-byte alignment requirement for both fields i (offset 0) and j (offset 5). Instead, the compiler inserts a 3-byte gap (shown below as “XXX”) between fields c and j: Offset Contents 0 i 4 c 5 XXX 8 j so that j has offset 8, and the overall structure size is 12 bytes. Furthermore, the compiler must ensure that any pointer p of type struct S1 * satisfies a 4-byte alignment. Using our earlier notation, let pointer p have value Üp . Then Üp must be a multiple of 4. This guarantees that both p->i (address Üp ) and p->j (address Üp · ) will satisfy their 4-byte alignment requirements. In addition, the compiler may need to add padding to the end of the structure so that each element in an array of structures will satisfy its alignment requirement. For example, consider the following structure declaration: struct S2 { int i; int j; char c; }; If we pack this structure into 9 bytes, we can still satisfy the alignment requirements for fields i and j by making sure that the starting address of the structure satisfies a 4-byte alignment requirement. Consider, however, the following declaration: struct S2 d[4]; With the 9-byte allocation, it is not possible to satisfy the alignment requirement for each element of d, because these elements will have addresses Üd , Üd · , Üd · ½ , and Üd · ¾ . Instead the compiler will allocate 12 bytes for structure S1, with the final 3 bytes being wasted space: Offset Contents 0 i 4 j 8 c ·¾ 9 XXX , and Üd · ¿ . As long as Üd is a That way the elements of d will have addresses Üd , Üd · ½¾, Üd multiple of 4, all of the alignment restrictions will be satisfied. 162 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Practice Problem 3.23: For each of the following structure declarations, determine the offset of each field, the total size of the structure, and its alignment requirement under Linux/IA32. A. struct P1 { int i; char c; int j; char d; }; B. struct P2 { int i; char c; char d; int j; }; C. struct P3 { short w[3]; char c[3] }; D. struct P4 { short w[3]; char *c[3] }; E. struct P3 { struct P1 a[2]; struct P2 *p }; 3.11 Putting it Together: Understanding Pointers Pointers are a central feature of the C programming language. They provide a uniform way to provide remote access to data structures. Pointers are a source of confusion for novice programmers, but the underlying concepts are fairly simple. The code in Figure 3.25 lets us illustrate a number of these concepts. ¯ Every pointer has a type. This type indicates what kind of object the pointer points to. In our example code, we see the following pointer types: Pointer Type int * union uni * Object Type int union uni Pointers xp, ip[0], ip[1] up Note in the above table, that we indicate the type of the pointer itself, as well as the type of the object it points to. In general, if the object has type Ì , then the pointer has type *Ì . The special void * type represents a generic pointer. For example, the malloc function returns a generic pointer, which is converted to a typed pointer via a cast (line 21). ¯ ¯ Every pointer has a value. This value is an address of some object of the designated type. The special NULL (0) value indicates that the pointer does not point anywhere. We will see the values of our pointers shortly. Pointers are created with the & operator. This operator can be applied to any C expression that is categorized as an lvalue, meaning an expression that can appear on the left side of an assignment. Examples include variables and the elements of structures, unions, and arrays. In our example code, we see this operator being applied to global variable g (line 24), to structure element s.v (line 32), to union element up->v (line 33), and to local variable x (line 42). Pointers are dereferenced with the * operator. The result is a value having the type associated with the pointer. We see dereferencing applied to both ip and *ip (line 29), to ip[1] (line 31), and xp (line 35). In addition, the expression up->v (line 33) both derefences pointer up and selects field v. ¯ 3.11. PUTTING IT TOGETHER: UNDERSTANDING POINTERS 163 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 struct str { int t; char v; }; union uni { int t; char v; } u; int g = 15; /* Example Structure */ /* Example Union */ void fun(int* xp) { void (*f)(int*) = fun; /* f is a function pointer */ /* Allocate structure on stack */ struct str s = {1,’a’}; /* Initialize structure */ /* Allocate union from heap */ union uni *up = (union uni *) malloc(sizeof(union uni)); /* Locally declared array */ int *ip[2] = {xp, &g}; up->v = s.v+1; printf("ip = %p, *ip = %p, **ip = %d\n", ip, *ip, **ip); printf("ip+1 = %p, ip[1] = %p, *ip[1] = %d\n", ip+1, ip[1], *ip[1]); printf("&s.v = %p, s.v = ’%c’\n", &s.v, s.v); printf("&up->v = %p, up->v = ’%c’\n", &up->v, up->v); printf("f = %p\n", f); if (--(*xp) > 0) f(xp); /* Recursive call of fun */ } int test() { int x = 2; fun(&x); return x; } Figure 3.25: Code Illustrating Use of Pointers in C. In C, pointers can be generated to any data type. 164 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS ¯ ¯ Arrays and pointers are closely related. The name of an array can be referenced (but not updated) as if it were a pointer variable. Array referencing (e.g., a[3]) has the exact same effect as pointer arithmetic and dereferencing (e.g., *(a+3)). We can see this in line 29, where we print the pointer value of array ip, and reference its first (element 0) entry as *ip. Pointers can also point to functions. This provides a powerful capability for storing and passing references to code, which can be invoked in some other part of the program. We see this with variable f (line 15), which is declared to be a variable that points to a function taking an int * as argument and returning void. The assignment makes f point to fun. When we later apply f (line 36), we are making a recursive call. New to C? The syntax for declaring function pointers is especially difficult for novice programmers to understand. For a declaration such as void (*f)(int*); it helps to read it starting from the inside (starting with “f”) and working outward. Thus, we see that f is a pointer, as indicated by “(*f).” It is a pointer to a function that has a single int * as an argument as indicated by “(*f)(int*).” Finally, we see that it is a pointer to a function that takes an int * as an argument and returns void. The parentheses around *f are required, because otherwise the declaration: void *f(int*); would be read as: (void *) f(int*); That is, it would be interpreted as a function prototype, declaring a function f that has an int * as its argument and returns a void *. Kernighan & Ritchie [37, Sect. 5.12] present a very helpful tutorial on reading C declarations. End Our code contains a number of calls to printf, printing some of the pointers (using directive %p) and values. When executed, it generates the following output: 1 2 3 4 5 6 7 8 9 10 ip ip+1 &s.v &up->v f ip ip+1 &s.v &up->v f = = = = = = = = = = 0xbfffefa8, 0xbfffefac, 0xbfffefb4, 0x8049760, 0x8048414 0xbfffef68, 0xbfffef6c, 0xbfffef74, 0x8049770, 0x8048414 *ip ip[1] s.v up->v *ip ip[1] s.v up->v = 0xbfffefe4, **ip =2 ip[0] = xp. *xp = x = 2 = 0x804965c, *ip[1] = 15 ip[1] = &g. g = 15 = ’a’ s in stack frame = ’b’ up points to area in heap f points to code for fun = 0xbfffefe4, **ip =1 ip in new frame, x = 1 = 0x804965c, *ip[1] = 15 ip[1] same as before = ’a’ s in new frame = ’b’ up points to new area in heap f points to code for fun 3.12. LIFE IN THE REAL WORLD: USING THE GDB DEBUGGER 165 We see that the function is executed twice—first by the direct call from test (line 42), and second by the indirect, recursive call (line 36). We can see that the printed values of the pointers all correspond to addresses. Those starting with 0xbfffef point to locations on the stack, while the rest are part of the global storage (0x804965c), part of the executable code (0x8048414), or locations on the heap (0x8049760 and 0x8049770). Array ip is instantiated twice—once for each call to fun. The second value (0xbfffef68) is smaller than the first (0xbfffefa8), because the stack grows downward. The contents of the array, however, are the same in both cases. Element 0 (*ip) is a pointer to variable x in the stack frame for test. Element 1 is a pointer to global variable g. We can see that structure s is instantiated twice, both times on the stack, while the union pointed to by variable up is allocated on the heap. Finally, variable f is a pointer to function fun. In the disassembled code, we find the following as the initial code for fun: 1 2 3 4 5 08048414 <fun>: 8048414: 55 8048415: 89 e5 8048417: 83 ec 1c 804841a: 57 push mov sub push %ebp %esp,%ebp $0x1c,%esp %edi The value 0x8048414 printed for pointer f is exactly the address of the first instruction in the code for fun. New to C? Other languages, such as Pascal, provide two different ways to pass parameters to procedures—by value (identified in Pascal by keyword var), where the caller provides the actual parameter value, and by reference, where the caller provides a pointer to the value. In C, all parameters are passed by value, but we can simulate the effect of a reference parameter by explicitly generating a pointer to a value and passing this pointer to a procedure. We saw this in function fun (Figure 3.25) with the parameter xp. With the initial call fun(&x) (line 42), the function is given a reference to local variable x in test. This variable is decremented by each call to fun (line 35), causing the recursion to stop after two calls. C++ reintroduced the concept of a reference parameter, but many feel this was a mistake. End 3.12 Life in the Real World: Using the G DB Debugger The GNU debugger GDB provides a number of useful features to support the run-time evaluation and analysis of machine-level programs. With the examples and exercises in this book, we attempt to infer the behavior of a program by just looking at the code. Using GDB, it becomes possible to study the behavior by watching the program in action, while having considerable control over its execution. Figure 3.26 shows examples of some GDB commands that help when working with machine-level, IA32 programs. It is very helpful to first run OBJDUMP to get a disassembled version of the program. Our examples were based on running GDB on the file prog, described and disassembled on page 96. We would start GDB with the command line: unix> gdb prog 166 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Command Starting and Stopping quit run kill Breakpoints break sum break *0x80483c3 delete 1 delete Execution stepi stepi 4 nexti continue finish Examining code disas disas sum disas 0x80483b7 disas 0x80483b7 0x80483c7 print /x $eip Examining data print $eax print /x $eax print /t $eax print 0x100 print /x 555 print /x ($ebp+8) print *(int *) 0xbffff890 print *(int *) ($ebp+8) x/2w 0xbffff890 x/20b sum Useful information info frame info registers help Effect Exit GDB Run your program (give command line arguments here) Stop your program Set breakpoint at entry to function sum Set breakpoint at address 0x80483c3 Delete breakpoint 1 Delete all breakpoints Execute one instruction Execute four instructions Like stepi, but proceed through function calls Resume execution Run until current function returns Disassemble current function Disassemble function sum Disassemble function around address 0x80483b7 Disassemble code within specified address range Print program counter in hex Print contents of %eax in decimal Print contents of %eax in hex Print contents of %eax in binary Print decimal representation of 0x100 Print hex representation of 555 Print contents of %ebp plus 8 in hex Print integer at address 0xbffff890 Print integer at address %ebp + 8 Examine two (4-byte) words starting at address 0xbffff890 Examine first 20 bytes of function sum Information about current stack frame Values of all the registers Get information about GDB Figure 3.26: Example G DB Commands. These examples illustrate some of the ways GDB supports debugging of machine-level programs. 3.13. OUT-OF-BOUNDS MEMORY REFERENCES AND BUFFER OVERFLOW 167 The general scheme is to set breakpoints near points of interest in the program. These can be set to just after the entry of a function, or at a program address. When one of the breakpoints is hit during program execution, the program will halt and return control to the user. From a breakpoint, we can examine different registers and memory locations in various formats. We can also single-step the program, running just a few instructions at a time, or we can proceed to the next breakpoint. As our examples suggests, GDB has an obscure command syntax, but the online help information (invoked within GDB with the help command) overcomes this shortcoming. 3.13 Out-of-Bounds Memory References and Buffer Overflow We have seen that C does not perform any bounds checking for array references, and that local variables are stored on the stack along with state information such as register values and return pointers. This combination can lead to serious program errors, where the state stored on the stack gets corrupted by a write to an outof-bounds array element. When the program then tries to reload the register or execute a ret instruction with this corrupted state, things can go seriously wrong. A particularly common source of state corruption is known as buffer overflow. Typically some character array is allocated on the stack to hold a string, but the size of the string exceeds the space allocated for the array. This is demonstrated by the following program example. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* Implementation of library function gets() */ char *gets(char *s) { int c; char *dest = s; while ((c = getchar()) != ’\n’ && c != EOF) *dest++ = c; *dest++ = ’\0’; /* Terminate String */ if (c == EOF) return NULL; return s; } /* Read input line and write it back */ void echo() { char buf[4]; /* Way too small! */ gets(buf); puts(buf); } The above code shows an implementation of the library function gets to demonstrate a serious problem with this function. It reads a line from the standard input, stopping when either a terminating newline character or some error condition is encountered. It copies this string to the location designated by argument s, and terminates the string with a null character. We show the use of gets in the function echo, which simply reads a line from standard input and echos it back to standard output. 168 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Stack Frame for caller Return Address %ebp Saved %ebp [3] [2] [1] [0] buf Stack Frame for echo Figure 3.27: Stack Organization for echo Function. Character array buf is just below part of the saved state. An out-of-bounds write to buf can corrupt the program state. The problem with gets is that it has no way to determine whether sufficient space has been allocated to hold the entire string. In our echo example, we have purposely made the buffer very small—just four characters long. Any string longer than three characters will cause an out-of-bounds write. Examining a portion of the assembly code for echo shows how the stack is organized. 1 2 3 4 5 6 7 8 9 echo: pushl %ebp movl %esp,%ebp subl $20,%esp pushl %ebx addl $-12,%esp leal -4(%ebp),%ebx pushl %ebx call gets Save %ebp on stack Allocate space on stack Save %ebx Allocate more space on stack Compute buf as %ebp-4 Push buf on stack Call gets We can see in this example that the program allocates a total of 32 bytes (lines 4 and 6) for local storage. However, the location of character array buf is computed as just four bytes below %ebp (line 7). Figure 3.27 shows the resulting stack structure. As can be seen, any write to buf[4] through buf[7] will cause the saved value of %ebp to be corrupted. When the program later attempts to restore this as the frame pointer, all subsequent stack references will be invalid. Any write to buf[8] through buf[11] will cause the return address to be corrupted. When the ret instruction is executed at the end of the function, the program will “return” to the wrong address. As this example illustrates, buffer overflow can cause a program to seriously misbehave. Our code for echo is simple but sloppy. A better version involves using the function fgets, which includes as an argument a count on the maximum number bytes to read. Homework problem 3.37 asks you to write an echo function that can handle an input string of arbitrary length. In general, using gets or any function that can overflow storage is considered a bad programming practice. The C compiler even produces the following error message when compiling a file containing a call to gets: “the gets function is dangerous and should not be used.” 3.13. OUT-OF-BOUNDS MEMORY REFERENCES AND BUFFER OVERFLOW 169 code/asm/bufovf.c 1 2 3 4 5 6 7 8 9 10 11 12 /* This is very low quality code. It is intended to illustrate bad programming practices. See Practice Problem 3.24. */ char *getline() { char buf[8]; char *result; gets(buf); result = malloc(strlen(buf)); strcpy(result, buf); return(result); } code/asm/bufovf.c C Code 1 2 3 4 5 6 7 8 9 10 08048524 <getline>: 8048524: 55 8048525: 89 e5 8048527: 83 ec 10 804852a: 56 804852b: 53 Diagram stack at this point push mov sub push push add lea push call %ebp %esp,%ebp $0x10,%esp %esi %ebx $0xfffffff4,%esp 0xfffffff8(%ebp),%ebx %ebx 80483ac <_init+0x50> 804852c: 804852f: 8048532: 8048533: 83 c4 f4 8d 5d f8 53 e8 74 fe ff ff gets Modify diagram to show values at this point Disassembly up through call to gets Figure 3.28: C and Disassembled Code for Problem 3.24. 170 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Practice Problem 3.24: Figure 3.28 shows a (low quality) implementation of a function that reads a line from standard input, copies the string to newly allocated storage, and returns a pointer to the result. Consider the following scenario. Procedure getline is called with the return address equal to 0x8048643, register %ebp equal to 0xbffffc94, register %esi equal to 0x1, and register %ebx equal to 0x2. You type in the string “012345678901.” The program terminates with a segmentation fault. You run GDB and determine that the error occurs during the execution of the ret instruction of getline. A. Fill in the diagram below indicating as much as you can about the stack just after executing the instruction at line 6 in the disassembly. Label the quantities stored on the stack (e.g., “Return Address”) on the right, and their hexadecimal values (if known) within the box. Each box represents four bytes. Indicate the position of %ebp. +-------------+ | 08 04 86 43 | +-------------+ | | +-------------+ | | +-------------+ | | +-------------+ | | +-------------+ | | +-------------+ | | +-------------+ | | +-------------+ Return Address B. Modify your diagram to show the effect of the call to gets (line 10). C. To what address does the program attempt to return? D. What register(s) have corrupted value(s) when getline returns? E. Besides the potential for buffer overflow, what two other things are wrong with the code for getline? A more pernicious use of buffer overflow is to get a program to perform a function that it would otherwise be unwilling to do. This is one of the most common methods to attack the security of a system over a computer network. Typically, the program is fed with a string that contains the byte encoding of some executable code, called the exploit code, plus some extra bytes that overwrite the return pointer with a pointer to the code in the buffer. The effect of executing the ret instruction is then to jump to the exploit code. In one form of attack, the exploit code then uses a system call to start up a shell program, providing the attacker with a range of operating system functions. In another form, the exploit code performs some otherwise unauthorized task, repairs the damage to the stack, and then executes ret a second time, causing an (apparently) normal return to the caller. 3.13. OUT-OF-BOUNDS MEMORY REFERENCES AND BUFFER OVERFLOW 171 As an example, the famous Internet worm of November, 1988 used four different ways to gain access to many of the computers across the Internet. One was a buffer overflow attack on the finger daemon fingerd, which serves requests by the FINGER command. By invoking FINGER with an appropriate string, the worm could make the daemon at a remote site have a buffer overflow and execute code that gave the worm access to the remote system. Once the worm gained access to a system, it would replicate itself and consume virtually all of the machine’s computing resources. As a consequence, hundreds of machines were effectively paralyzed until security experts could determine how to eliminate the worm. The author of the worm was caught and prosecuted. He was sentenced to three years probation, 400 hours of community service, and a $10,500 fine. Even to this day, however, people continue to find security leaks in systems that leave them vulnerable to buffer overflow attacks. This highlights the need for careful programming. Any interface to the external environment should be made “bullet proof” so that no behavior by an external agent can cause the system to misbehave. Aside: Worms and viruses Both worms and viruses are pieces of code that attempt to spread themselves among computers. As described by Spafford [69], a worm is a program that can run by itself and can propagate a fully working version of itself to other machines. A virus is a piece of code that adds itself to other programs, including operating systems. It cannot run independently. In the popular press, the term “virus” is used to refer to a variety of different strategies for spreading attacking code among systems, and so you will hear people saying “virus” for what more properly should be called a “worm.” End Aside. In Problem 3.38, you can gain first-hand experience at mounting a buffer overflow attack. Note that we do not condone using this or any other method to gain unauthorized access to a system. Breaking into computer systems is like breaking into a building—it is a criminal act even when the perpetrator does not have malicious intent. We give this problem for two reasons. First, it requires a deep understanding of machine-language programming, combining such issues as stack organization, byte ordering, and instruction encoding. Second, by demonstrating how buffer overflow attacks work, we hope you will learn the importance of writing code that does not permit such attacks. Aside: Battling Microsoft via buffer overflow In July, 1999, Microsoft introduced an instant messaging (IM) system whose clients were compatible with the popular AOL IM servers. This allowed Microsoft IM users to chat with AOL IM users. However, one month later, Microsoft IM users were suddenly and mysteriously unable to chat with AOL users. Microsoft released updated clients that restored service to the AOL IM system, but within days these clients no longer worked either. AOL had, possibly unintentionally, written client code that was vulnerable to a buffer overflow attack. Their server applied such an attack on client code when a user logged in to determine whether the client was running AOL code or someone else’s. The AOL exploit code sampled a small number of locations in the memory image of the client, packed them into a network packet, and sent them back to the server. If the server did not receive such a packet, or if the packet it received did not match the expected “footprint” of the AOL client, then the server assumed the client was not an AOL client and denied it access. So if other IM clients, such as Microsoft’s, wanted access to the AOL IM servers, they would not only have to incorporate the buffer overflow bug that existed in AOL’s clients, but they would also have to have identical binary code and data in the appropriate memory locations. But as soon as they matched these locations and distributed new versions of their client programs to customers, AOL could simply change its exploit code to sample different locations in the client’s memory image. This was clearly a war that the non-AOL clients could never win! The entire episode had a number of unusuals twists and turns. Information about the client bug and AOL’s exploitation of it first came out when someone posing to be an independent consultant by the name of Phil Bucking sent 172 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS a description via email to Richard Smith, a noted security expert. Smith did some tracing and determined that the email actually originated from within Microsoft. Later Microsoft admitted that one of its employees had sent the email [48]. On the other side of the controversy, AOL never admitted to the bug nor their exploitation of it, even though conclusive evidence was made public by Geoff Chapell of Australia. So, who violated which code of conduct in this incident? First, AOL had no obligation to open its IM system to non-AOL clients, so they were justified in blocking Microsoft. On the other hand, using buffer overflows is a tricky business. A small bug would have crashed the client computers, and it made the systems more vulnerable to attacks by external agents (although there is no evidence that this occurred). Microsoft would have done well to publicly announce AOL’s intentional use of buffer overflow. However, their Phil Bucking subterfuge was clearly the wrong way to spread this information, from both an ethical and a public relations point of view. End Aside. 3.14 *Floating-Point Code The set of instructions for manipulating floating-point values is one least elegant features of the IA32 architecture. In the original Intel machines, floating point was performed by a separate coprocessor, a unit with its own registers and processing capabilities that executes a subset of the instructions. This coprocessor was implemented as a separate chip named the 8087, 80287, and i387, to accompany the processor chips 8086, 80286, and i386, respectively. During these product generations, chip capacity was insufficient to include both the main processor and the floating-point coprocessor on a single chip. In addition, lower-budget machines would omit floating-point hardware and simply perform the floating-point operations (very slowly!) in software. Since the i486, floating point has been included as part of the IA32 CPU chip. The original 8087 coprocessor was introduced to great acclaim in 1980. It was the first single-chip floatingpoint unit (FPU), and the first implementation of what is now known as IEEE floating point. Operating as a coprocessor, the FPU would take over the execution of floating-point instructions after they were fetched by the main processor. There was minimal connection between the FPU and the main processor. Communicating data from one processor to the other required the sending processor to write to memory and the receiving one to read it. Artifacts of that design remain in the IA32 floating-point instruction set today. In addition, the compiler technology of 1980 was much less sophisticated than it is today. Many features of IA32 floating point make it a difficult target for optimizing compilers. 3.14.1 Floating-Point Registers The floating-point unit contains eight floating-point registers, but unlike normal registers, these are treated as a shallow stack. The registers are identified as %st(0), %st(1), and so on, up to %st(7), with %st(0) being the top of the stack. When more than eight values are pushed onto the stack, the ones at the bottom simply disappear. Rather than directly indexing the registers, most of the arithmetic instructions pop their source operands from the stack, compute a result, and then push the result onto the stack. Stack architectures were considered a clever idea in the 1970s, since they provide a simple mechanism for evaluating arithmetic instructions, and they allow a very dense coding of the instructions. With advances in compiler technology and with the memory required to encode instructions no longer considered a critical resource, these properties are no longer important. Compiler writers would be much happier with a larger, conventional set of floating-point registers. 3.14. *FLOATING-POINT CODE Aside: Other stack-based languages. Stack-based interpreters are still commonly used as an intermediate representation between a high-level language and its mapping onto an actual machine. Other examples of stack-based evaluators include Java byte code, the intermediate format generated by Java compilers, and the Postscript page formatting language. End Aside. 173 Having the floating-point registers organized as a bounded stack makes it difficult for compilers to use these registers for storing the local variables of a procedure that calls other procedures. For storing local integer variables, we have seen that some of the general purpose registers can be designated as callee saved and hence be used to hold local variables across a procedure call. Such a designation is not possible for an IA32 floating-point register, since its identity changes as values are pushed onto and popped from the stack. For a push operation causes the value in %st(0) to now be in %st(1). On the other hand, it might be tempting to treat the floating-point registers as a true stack, with each procedure call pushing its local values onto it. Unfortunately, this approach would quickly lead to a stack overflow, since there is room for only eight values. Instead, compilers generate code that saves every local floating-point value on the main program stack before calling another procedure and then retrieves them on return. This generates memory traffic that can degrade program performance. 3.14.2 Extended-Precision Arithmetic A second unusual feature of IA32 floating point is that the floating-point registers are all 80 bits wide. They encode numbers in an extended-precision format as described in Problem 2.49. It is similar to an IEEE floating-point format with a 15-bit exponent (i.e., ½ ) and a 63-bit fraction (i.e., Ò ¿). All single and double-precision numbers are converted to this format as they are loaded from memory into floating-point registers. The arithmetic is always performed in extended precision. Numbers are converted from extended precision to single or double-precision format as they are stored in memory. This extension to 80 bits for all register data and then contraction to a smaller format for all memory data has some undesirable consequences for programmers. It means that storing a value in memory and then retrieving it can change its value, due to rounding, underflow, or overflow. This storing and retrieving is not always visible to the C programmer, leading to some very peculiar results. The following example illustrates this property: code/asm/fcomp.c 1 2 3 4 5 6 7 8 9 10 11 12 double recip(int denom) { return 1.0/(double) denom; } void do_nothing() {} /* Just like the name says */ void test1(int denom) { double r1, r2; int t1, t2; 174 13 14 15 16 17 18 19 20 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS r1 = recip(denom); /* Stored in memory */ r2 = recip(denom); /* Stored in register */ t1 = r1 == r2; /* Compares register to memory */ do_nothing(); /* Forces register save to memory */ t2 = r1 == r2; /* Compares memory to memory */ printf("test1 t1: r1 %f %c= r2 %f\n", r1, t1 ? ’=’ : ’!’, r2); printf("test1 t2: r1 %f %c= r2 %f\n", r1, t2 ? ’=’ : ’!’, r2); } code/asm/fcomp.c Variables r1 and r2 are computed by the same function with the same argument. One would expect them to be identical. Furthermmore, both variables t1 and t2 are computing by evaluating the expression r1 == r2, and so we would expect them both to equal 1. There are no apparent hidden side effects—function recip does a straightforward reciprocal computation, and, as the name suggests, function do_nothing does nothing. When the file is compiled with optimization flag ‘-O2’ and run with argument 10, however, we get the following result: test1 t1: r1 0.100000 != r2 0.100000 test1 t2: r1 0.100000 == r2 0.100000 The first test indicates the two reciprocals are different, while the second indicates they are the same! This is certainly not what we would expect, nor what we want. The comments in the code provide a clue for why this outcome occurs. Function recip returns its result in a floating-point register. Whenever procedure test1 calls some function, it must store any value currently in a floating-point register onto the main program stack, converting from extended to double precision in the process. (We will see why this happens shortly). Before making the second call to recip, variable r1 is converted and stored as a double-precision number. After the second call, variable r2 has the extended-precision value returned by the function. In computing t1, the double-precision number r1 is compared to the extended-precision number r2. Since ¼ ½ cannot be represented exactly in either format, the outcome of the test is false. Before calling function do_nothing, r2 is converted and stored as a double-precision number. In computing t2, two double-precision numbers are compared, yielding true. This example demonstrates a deficiency of GCC on IA32 machines (the same result occurs for both Linux and Microsoft Windows). The value associated with a variable changes due to operations that are not visible to the programmer, such as the saving and restoring of floating-point registers. Our experiments with the Microsoft Visual C++ compiler indicate that it does not have this problem. There are several ways to overcome this problem, although none are ideal. One is to invoke GCC with the command line flag ‘-mno-fp-ret-in-387’ indicating that floating-point values should be returned on the main program stack rather than in a floating-point register. Function test1 will then show that both comparisons are true. This does not solve the problem—it just moves it to a different source of inconsistency. For example, consider the following variant, where we compute the reciprocal r2 directly rather than calling recip: code/asm/fcomp.c 3.14. *FLOATING-POINT CODE 1 2 3 4 5 6 7 8 9 10 11 12 13 175 void test2(int denom) { double r1, r2; int t1, t2; r1 = recip(denom); /* Stored in memory */ r2 = 1.0/(double) denom; /* Stored in register */ t1 = r1 == r2; /* Compares register to memory */ do_nothing(); /* Forces register save to memory */ t2 = r1 == r2; /* Compares memory to memory */ printf("test2 t1: r1 %f %c= r2 %f\n", r1, t1 ? ’=’ : ’!’, r2); printf("test2 t2: r1 %f %c= r2 %f\n", r1, t2 ? ’=’ : ’!’, r2); } code/asm/fcomp.c Once again we get t1 equal to 0—the double-precision value in memory computed by recip is compared to the extended-precision value computed directly. A second method is to disable compiler optimization. This causes the compiler to store every intermediate result on the main program stack, ensuring that all values are converted to double precision. However, this leads to a significant loss of performance. Aside: Why should we be concerned about these inconsistencies? As we will discuss in Chapter 5, one of the fundamental principles of optimizing compilers is that programs should produce the exact same results whether or not optimization is enabled. Unfortunately GCC does not satisfy this requirement for floating-point code. End Aside. Finally, we can have GCC use extended precision in all of its computations by declaring all of the variables to be long double as shown in the following code: code/asm/fcomp.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 long double recip_l(int denom) { return 1.0/(long double) denom; } void test3(int denom) { long double r1, r2; int t1, t2; r1 = recip_l(denom); /* Stored in memory r2 = recip_l(denom); /* Stored in register t1 = r1 == r2; /* Compares register to memory do_nothing(); /* Forces register save to memory t2 = r1 == r2; /* Compares memory to memory printf("test3 t1: r1 %f %c= r2 %f\n", (double) r1, t1 ? ’=’ : ’!’, (double) r2); */ */ */ */ */ 176 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Instruction load S storep D neg addp subp multp divp Effect Push value at S onto stack Pop top stack element and store at D Negate top stack element Pop top two stack elements; Push their sum Pop top two stack elements; Push their difference Pop top two stack elements; Push their product Pop top two stack elements; Push their ratio Figure 3.29: Hypothetical Stack Instruction Set. These instructions are used to illustrate stack-based expression evaluation 18 19 20 printf("test3 t2: r1 %f %c= r2 %f\n", (double) r1, t2 ? ’=’ : ’!’, (double) r2); } code/asm/fcomp.c The declaration long double is allowed as part of the ANSI C standard, although for most machines and compilers this declaration is equivalent to an ordinary double. For GCC on IA32 machines, however, it uses the extended-precision format for memory data as well as for floating point register data. This allows us to take full advantage of the wider range and greater precision provided by the extended-precision format while avoiding the anomalies we have seen in our earlier examples. Unfortunately, this solution comes at a price. G CC uses 12 bytes to store a long double, increasing memory consumption by 50%. (Although 10 bytes would suffice, it rounds this up to 12 to give a better alignment. The same allocation is used on both Linux and Windows machines). Transfering these longer data between registers and memory takes more time, too. Still, this is the best option for programs requiring very consistent numerical results. 3.14.3 Stack Evaluation of Expressions To understand how IA32 uses its floating-point registers as a stack, let us consider a more abstract version of stack-based evaluation. Assume we have an arithmetic unit that uses a stack to hold intermediate results, having the instruction set illustrated in Figure 3.29. For example, so-called RPN (for Reverse Polish Notation) pocket calculators provide this feature. In addition to the stack, this unit has a memory that can hold values we will refer to by names such as a, b, and x. As Figure 3.29 indicates, we can push memory values onto this stack with the load instruction. The storep operation pops the top element from the stack and stores the result in memory. A unary operation such as neg (negation) uses the top stack element as its argument and overwrites this element with the result. Binary operations such as addp and multp use the top two elements of the stack as their arguments. They pop both arguments off the stack and then push the result back onto the stack. We use the suffix ‘p’ with the store, add, subtract, multiply, and divide instructions to emphasize the fact that these instructions pop their operands. As an example, suppose we wish to evaluate the expression x = (a-b)/(-b+c). We could translate this expression into the following code. Alongside each line of code, we show the contents of the floating-point 3.14. *FLOATING-POINT CODE 177 register stack. In keeping with our earlier convention, we show the stack as growing downward, so the “top” of the stack is really at the bottom. 1 · %st(2) %st(1) %st(0) load c %st(0) 6 load a %st(1) 2 load b %st(0) 7 subp · %st(1) %st(0) 3 neg · %st(1) %st(0) 8 divp ´ · µ´ · µ %st(0) 4 addp %st(0) 9 storep x · %st(1) %st(0) load b As this example shows, there is a natural recursive procedure for converting an arithmetic expression into stack code. Our expression notation has four types of expressions having the following translation rules: 5 1. A variable reference of the form Î Ö . This is implemented with the instruction load Î Ö . 2. A unary operation of the form - ÜÔÖ . This is implemented by first generating the code for followed by a neg instruction. ÜÔÖ 3. A binary operation of the form ÜÔÖ ½ + ÜÔÖ ¾ , ÜÔÖ ½ - ÜÔÖ ¾ , ÜÔÖ ½ * ÜÔÖ ¾ , or ÜÔÖ ½ / ÜÔÖ ¾ . This is implemented by generating the code for ÜÔÖ ¾ , followed by the code for ÜÔÖ ½ , followed by an addp, subp, multp, or divp instruction. 4. An assignment of the form Î Ö = ÜÔÖ . This is implemented by first generating the code for ÜÔÖ , followed by the storep Î Ö instruction. As an example, consider the expression x = a-b/c. Since division has precedence over subtraction, this expression can be parenthesized as x = a-(b/c). The recursive procedure would therefore proceed as follows: 1. Generate code for ÜÔÖ a-(b/c): b/c: (a) Generate code for ÜÔÖ ¾ i. Generate code for ÜÔÖ ¾ c using the instruction load c. ii. Generate code for ÜÔÖ ½ b, using the instruction load b. iii. Generate instruction divp. (b) Generate code for ÜÔÖ ½ (c) Generate instruction subp. a, using the instruction load a. 178 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS 2. Generate instruction storep x. The overall effect is to generate the following stack code: %st(1) 1 load c %st(0) 4 load a %st(0) %st(1) 2 load b %st(0) 5 subp ´ µ %st(0) 3 divp Practice Problem 3.25: %st(0) 6 storep x Generate stack code for the expression x = a*b/c * -(a+b*c). Diagram the contents of the stack for each step of your code. Remember to follow the C rules for precedence and associativity. Stack evaluation becomes more complex when we wish to use the result of some computation multiple times. For example, consider the expression x = (a*b)*(-(a*b)+c). For efficiency, we would like to compute a*b only once, but our stack instructions do not provide a way to keep a value on the stack once it has been used. With the set of instructions listed in Figure 3.29, we would therefore need to store the intermediate result a+b in some memory location, say t, and retrieve this value for each use. This gives the following code: 1 load c %st(0) 7 neg ¡ ´ %st(1) µ %st(0) %st(1) 2 load b %st(0) %st(2) %st(1) 8 addp ¡ ´ µ· %st(0) 3 load a %st(0) 9 ¡ ´ load t ¡ µ· %st(1) %st(0) 4 multp ¡ %st(1) %st(0) 10 multp ¡ ¡ ¡ ´ ´ µ· µ %st(0) 5 storep t %st(0) 11 storep x %st(0) load t This approach has the disadvantage of generating additional memory traffic, even though the register stack has sufficient capacity to hold its intermediate results. The IA32 floating-point unit avoids this inefficiency 6 ¡ %st(1) 3.14. *FLOATING-POINT CODE Instruction flds Ö fldl Ö fldt Ö fildl Ö fld %st( ) Source Format Single double extended integer extended Source Location ÅÑ Ö ÅÑ Ö Å Ñ½¼ Ö ÅÑ Ö %st( ) 179 Figure 3.30: Floating-Point Load Instructions. All convert the operand to extended-precision format and push it onto the register stack. by introducing variants of the arithmetic instructions that leave their second operand on the stack, and that can use an arbitrary stack value as their second operand. In addition, it provides an instruction that can swap the top stack element with any other element. Although these extensions can be used to generate more efficient code, the simple and elegant algorithm for translating arithmetic expressions into stack code is lost. 3.14.4 Floating-Point Data Movement and Conversion Operations Floating-point registers are referenced with the notation %st( ), where denotes the position relative to the top of the stack. The value can range between 0 and 7. Register %st(0) is the top stack element, %st(1) is the second element, and so on. The top stack element can also be referenced as %st. When a new value is pushed onto the stack, the value in register %st(7) is lost. When the stack is popped, the new value in %st(7) is not predictable. Compilers must generate code that works within the limited capacity of the register stack. Figure 3.30 shows the set of instructions used to push values onto the floating-point register stack. The first group of these read from a memory location, where the argument Ö is a memory address given in one of the memory operand formats listed in Figure 3.3. These instructions differ by the presumed format of the source operand and hence the number of bytes that must be read from memory. We use the notation Å ÑÒ Ö to denote accessing of Ò bytes with starting address Ö . All of these instructions convert the operand to extended-precision format before pushing it onto the stack. The final load instruction fld is used to duplicate a stack value. That is, it pushes a copy of floating-point register %st( ) onto the stack. For example, the instruction fld %st(0) pushes a copy of the top stack element onto the stack. Figure 3.31 shows the instructions that store the top stack element either in memory or in another floatingpoint register. There are both “popping” versions that pop the top element off the stack, similar to the storep instruction for our hypothetical stack evaluator, as well as nonpopping versions that leave the source value on the top of the stack. As with the floating-point load instructions, different variants of the instruction generate different formats for the result and therefore store different numbers of bytes. The first group of these store the result in memory. The address is specified using any of the memory operand formats listed in Figure 3.3. The second group copies the top stack element to some other floating-point register. Practice Problem 3.26: Assume for the following code fragment that register %eax contains an integer variable x and that the top two stack elements correspond to variables a and b, respectively. Fill in the boxes to diagram the 180 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS Instruction fsts Ö fstps Ö fstl Ö fstpl Ö fstt Ö fstpt Ö fistl Ö fistpl Ö fst %st( ) fstp %st( ) Pop (Y/N) N Y N Y N Y N Y N Y Destination Format Single Single Double Double Extended Extended integer integer Extended Extended Destination Location ÅÑ Ö ÅÑ Ö ÅÑ Ö ÅÑ Ö Å Ñ½¼ Ö Å Ñ½¼ Ö ÅÑ Ö ÅÑ Ö %st( ) %st( ) Figure 3.31: Floating-Point Store Instructions. All convert from extended-precision format to the destination format. Instructions with suffix ‘ p’ pop the top element off the stack. stack contents after each instruction testl %eax,%eax %st(1) %st(0) jne L11 fstp %st(0) jmp L9 L11: %st(0) fstp %st(1) L9: %st(0) Write a C expression describing the contents of the top stack element at the end of this code sequence in terms of x, a and b. A final floating-point data movement operation allows the contents of two floating-point registers to be swapped. The instruction fxch %st( ) exchanges the contents of floating-point registers %st(0) and %st( ). The notation fxch written with no argument is equivalent to fxch %st(1), that is, swap the top two stack elements. 3.14. *FLOATING-POINT CODE Instruction fldz fld1 fabs fchs fcos fsin fsqrt fadd fsub fsubr fdiv fdivr fmul Computation ¼ ½ 181 ÇÔ ÇÔ Ó× ÇÔ × Ò ÇÔ ÔÇÔ ÇÔ ½ · ÇÔ ¾ ÇÔ ½ ÇÔ ¾ ÇÔ ¾ ÇÔ ½ ÇÔ ½ ÇÔ ¾ ÇÔ ¾ ÇÔ ½ ÇÔ ½ ¡ ÇÔ ¾ Figure 3.32: Floating-Point Arithmetic Operations. Each of the binary operations has many variants. Instruction fsubs Ö fsubl Ö fsubt Ö fisubl Ö fsub %st( ),%st fsub %st,%st( ) fsubp %st,%st( ) fsubp Operand 1 %st(0) %st(0) %st(0) %st(0) %st( ) %st(0) %st(0) %st(0) Operand 2 ÅÑ ÅÑ Å Ñ½¼ ÅÑ %st(0) %st( ) %st( ) %st(1) Ö Ö Ö Ö (Format) Single Double Extended integer Extended Extended Extended Extended Destination %st(0) %st(0) %st(0) %st(0) %st(0) %st( ) %st( ) %st(1) Pop %st(0) (Y/N) N N N N N N Y Y Figure 3.33: Floating-Point Subtraction Instructions. All store their results into a floating-point register in extended-precision format. Instructions with suffix ‘p’ pop the top element off the stack. 3.14.5 Floating-Point Arithmetic Instructions Figure 3.32 documents some of the most common floating-point arithmetic operations. Instructions in the first group have no operands. They push the floating-point representation of some numerical constant onto the stack. There are similar instructions for such constants as , , and ÐÓ ¾ ½¼. Instructions in the second group have a single operand. The operand is always the top stack element, similar to the neg operation of the hypothetical stack evaluator. They replace this element with the computed result. Instructions in the third group have two operands. For each of these instructions, there are many different variants for how the operands are specified, as will be discussed shortly. For noncommutative operations such as subtraction and division there is both a forward (e.g., fsub) and a reverse (e.g., fsubr) version, so that the arguments can be used in either order. In Figure 3.32 we show just a single form of the subtraction operation fsub. In fact, this operation comes in 182 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS many different variants, as shown in Figure 3.33. All compute the difference of two operands: ÇÔ ½ ÇÔ ¾ and store the result in some floating-point register. Beyond the simple subp instruction we considered for the hypothetical stack evaluator, IA32 has instructions that read their second operand from memory or from some floating-point register other than %st(1). In addition, there are both popping and nonpopping variants. The first group of instructions reads the second operand from memory, either in single-precision, double-precision, or integer format. It then converts this to extended-precision format, subtracts it from the top stack element, and overwrites the top stack element. These can be seen as a combination of a floating-point load following by a stack-based subtraction operation. The second group of subtraction instructions use the top stack element as one argument and some other stack element as the other, but they vary in the argument ordering, the result destination, and whether or not they pop the top stack element. Observe that the assembly code line fsubp is shorthand for fsubp %st,%st(1). This line corresponds to the subp instruction of our hypothetical stack evaluator. That is, it computes the difference between the top two stack elements, storing the result in %st(1), and then popping %st(0) so that the computed value ends up on the top of the stack. All of the binary operations listed in Figure 3.32 come in all of the variants listed for fsub in Figure 3.33. As an example, we can rewrite the code for the expression x = (a-b)*(-b+c) using the IA32 instructions. For exposition purposes we will still use symbolic names for memory locations and we assume these are double-precision values. 1 fldl b %st(0) 5 fsubl b · %st(1) %st(0) 2 fchs · %st(0) 6 fmulp ´ µ´ · µ %st(0) 3 faddl c %st(0) 7 fstpl x · %st(1) %st(0) fldl a As another example, we can write the code for the expression x = (a*b)+(-(a*b)+c) as follows. Observe how the instruction fld %st(0) is used to create two copies of a*b on the stack, avoiding the need to save the value in a temporary memory location. 4 1 fldl a %st(0) 4 fchs ¡ ´ ¡ ¡ %st(1) µ %st(0) 2 fmul b ¡ ¡ ¡ %st(0) 5 faddl c ¡ ´ ´ %st(1) µ· %st(0) %st(1) %st(0) 6 3 fld %st(0) fmulp ¡ ´ µ· µ ¡¡ %st(0) 3.14. *FLOATING-POINT CODE Practice Problem 3.27: Diagram the stack contents after each step of the following code: 183 1 fldl b %st(0) %st(1) %st(0) %st(1) %st(0) %st(1) %st(0) %st(1) %st(0) 2 fldl a 3 fmul %st(1),%st 4 fxch 5 fdivrl c 6 fsubrp %st(0) 7 fstp x Give an expression describing this computation. 3.14.6 Using Floating Point in Procedures Floating-point arguments are passed to a calling procedure on the stack, just as are integer arguments. Each parameter of type float requires 4 bytes of stack space, while each parameter of type double requires 8. For functions whose return values are of type float or double, the result is returned on the top of the floating-point register stack in extended-precision format. As an example, consider the following function 1 2 3 4 double funct(double a, float x, double b, int i) { return a*x - b/i; } Arguments a, x, b, and i will be at byte offsets 8, 16, 20, and 28 relative to %ebp, respectively, as diagrammed below: Offset Contents 8 a 16 x 20 b 28 i 184 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS The body of the generated code, and the resulting stack values are as follows: 1 fildl 28(%ebp) %st(0) 2 fdivrl 20(%ebp) %st(0) 3 flds 16(%ebp) Ü %st(1) %st(0) 4 fmull 8(%ebp) ¡Ü ¡Ü %st(1) %st(0) 5 fsubp %st,%st(1) Practice Problem 3.28: %st(0) For a function funct2 with arguments a, x, b, and i (and a different declaration than that of funct, the compiler generates the following code for the function body: 1 2 3 4 5 6 7 8 9 10 11 movl 8(%ebp),%eax fldl 12(%ebp) flds 20(%ebp) movl %eax,-4(%ebp) fildl -4(%ebp) fxch %st(2) faddp %st,%st(1) fdivrp %st,%st(1) fld1 flds 24(%ebp) faddp %st,%st(1) The returned value is of type double. Write C code for funct2. Be sure to correctly declare the argument types. 3.14.7 Testing and Comparing Floating-Point Values Similar to the integer case, determining the relative values of two floating-point numbers involves using a comparison instruction to set condition codes and then testing these condition codes. For floating point, however, the condition codes are part of the floating-point status word, a 16-bit register that contains various flags about the floating-point unit. This status word must be transferred to an integer word, and then the particular bits must be tested. 3.14. *FLOATING-POINT CODE Ordered fcoms fcoml fcom fcom fcomps fcompl fcomp fcomp fcompp Unordered fucoms fucoml fucom fucom fucomps fucompl fucomp fucomp fucompp 185 Addr Addr %st( ) Addr Addr %st( ) Addr Addr %st( ) Addr Addr %st( ) ÇÔ ¾ ÅÑ ÅÑ %st( ) %st(1) ÅÑ ÅÑ %st( ) %st(1) %st(1) Ö Ö Ö Ö Type Single Double Extended Extended Single Double Extended Extended Extended Number of Pops 0 0 0 0 1 1 1 1 2 Figure 3.34: Floating-Point Comparison Instructions. Ordered vs. unordered comparisons differ in their treatment of NaN’s. ÇÔ ½ ÇÔ ¾ Binary ¼¼¼¼¼¼¼¼ ¼¼¼¼¼¼¼½ ¼¼½¼¼¼¼¼ Unordered ¼¼½¼¼½¼½ Decimal 0 1 64 69 Figure 3.35: Encoded Results from Floating-Point Comparison. The results are encoded in the highorder byte of the floating-point status word after masking out all but bits 0, 2, and 6. There are a number of different floating-point comparison instructions as documented in Figure 3.34. All of them perform a comparison between operands ÇÔ ½ and ÇÔ ¾ , where ÇÔ ½ is the top stack element. Each line of the table documents two different comparison types: an ordered comparison used for comparisons such as and , and an unordered comparison used for equality comparisons. The two comparisons differ only in their treatment of NaN values, since there is no relative ordering between NaN’s and other values. For example, if variable x is a NaN and variable y is some other value, then both expressions x < y and x >= y should yield 0. The various forms of comparison instructions also differ in the location of operand ÇÔ ¾ , analogous to the different forms of floating-point load and floating-point arithmetic instructions. Finally, the various forms differ in the number of elements popped off the stack after the comparison is completed. Instructions in the first group shown in the table do not change the stack at all. Even for the case where one of the arguments is in memory, this value is not on the stack at the end. Operations in the second group pop element ÇÔ ½ off the stack. The final operation pops both ÇÔ ½ and ÇÔ ¾ off the stack. The floating-point status word is transferred to an integer register with the fnstsw instruction. The operand for this instruction is one of the 16-bit register identifiers shown in Figure 3.2, for example, %ax. The bits in the status word encoding the comparison results are in bit positions 0, 2, and 6 of the high-order byte of the status word. For example, if we use instruction fnstw %ax to transfer the status word, then the relevant bits will be in %ah. A typical code sequence to select these bits is then: 1 fnstsw %ax Store floating point status word in %ax 186 2 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS andb $69,%ah Mask all but bits 0, 2, and 6 Note that ½¼ has bit representation ¼¼½¼¼½¼½ , that is, it has 1s in the three relevant bit positions. Figure 3.35 shows the possible values of byte %ah that would result from this code sequence. Observe that there are only four possible outcomes for comparing operands ÇÔ ½ and ÇÔ ¾ : the first is either greater, less, equal, or incomparable to the second, where the latter outcome only occurs when one of the values is a Æ Æ . As an example, consider the following procedure: 1 2 3 4 int less(double x, double y) { return x < y; } The compiled code for the function body is shown below: 1 2 3 4 5 6 fldl 16(%ebp) fcompl 8(%ebp) fnstsw %ax andb $69,%ah sete %al movzbl %al,%eax Push y Compare y:x Store floating point status word in %ax Mask all but bits 0, 2, and 6 Test for comparison outcome of 0 (>) Copy low order byte to result, and set rest to 0 Practice Problem 3.29: Show how by inserting a single line of assembly code into the code sequence shown above you can implement the following function: 1 2 3 4 int greater(double x, double y) { return x > y; } This completes our coverage of assembly-level, floating-point programming with IA32. Even experienced programmers find this code arcane and difficult to read. The stack-based operations, the awkwardness of getting status results from the FPU to the main processor, and the many subtleties of floating-point computations combine to make the machine code lengthy and obscure. It is remarkable that the modern processors manufactured by Intel and its competitors can achieve respectable performance on numeric programs given the form in which they are encoded. 3.15 *Embedding Assembly Code in C Programs In the early days of computing, most programs were written in assembly code. Even large-scale operating systems were written without the help of high-level languages. This becomes unmanageable for programs of significant complexity. Since assembly code does not provide any form of type checking, it is very easy 3.15. *EMBEDDING ASSEMBLY CODE IN C PROGRAMS 187 to make basic mistakes, such as using a pointer as an integer rather than dereferencing the pointer. Even wors, writing in assembly code locks the entire program into a particular class of machine. Rewriting an assembly language program to run on a different machine can be as difficult as writing the entire program from scratch. Aside: Writing large programs in assembly code. Frederick Brooks, Jr., a pioneer in computer systems wrote a fascinating account of the development of OS/360, an early operating system for IBM machines [5] that still provides important object lessons today. He became a devoted believer in high-level languages for systems programming as a result of this effort. Surprisingly, however, there is an active group of programmers who take great pleasure in writing assembly code for IA32. The communicate with one another via the Internet news group comp.lang.asm.x86. Most of them write computer games for the DOS operating system. End Aside. Early compilers for higher-level programming languages did not generate very efficient code and did not provide access to the low-level object representations, as is often required by systems programmers. Programs requiring maximum performance or requiring access to object representations were still often written in assembly code. Nowadays, however, optimizing compilers have largely removed performance optimization as a reason for writing in assembly code. Code generated by a high quality compiler is generally as good or even better than what can be achieved manually. The C language has largely eliminated machine access as a reason for writing in assembly code. The ability to access low-level data representations through unions and pointer arithmetic, along with the ability to operate on bit-level data representations, provide sufficient access to the machine for most programmers. For example, almost every part of a modern operating system such as Linux is written in C. Nonetheless, there are times when writing in assembly code is the only option. This is especially true when implementing an operating system. For example, there are a number of special registers storing process state information that the operating system must access. There are either special instructions or special memory locations for performing input and output operations. Even for application programmers, there are some machine features, such as the values of the condition codes, that cannot be accessed directly in C. The challenge then is to integrate code consisting mainly of C with a small amount written in assembly language. One method is to write a few key functions in assembly code, using the same conventions for argument passing and register usage as are followed by the C compiler. The assembly functions are kept in a separate file, and the compiled C code is combined with the assembled assembly code by the linker. For example, if file p1.c contains C code and file p2.s contains assembly code, then the compilation command: unix> gcc -o p p1.c p2.s will cause file p1.c to be compiled, file p2.s to be assembled, and the resulting object code to be linked to form an executable program p. 3.15.1 Basic Inline Assembly With GCC, it is also possible to mix assembly with C code. Inline assembly allows the user to insert assembly code directly into the code sequence generated by the compiler. Features are provided to specify instruction operands and to indicate to the compiler which registers are being overwritten by the assembly instructions. 188 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS The resulting code is, of course, highly machine-dependent, since different types of machines do not have compatible machine instructions. The asm directive is also specific to GCC, creating an incompatibility with many other compilers. Nonetheless, this can be a useful way to keep the amount of machine-dependent code to an absolute minimum. Inline assembly is documented as part of the GCC information archive. Executing the command info gcc on any machine with GCC installed will give a hierarchical document reader. Inline assembly is documented by first following the link titled “C Extensions” and then the link titled “Extended Asm.” Unfortunately, the documentation is somewhat incomplete and imprecise. The basic form of inline assembly is to write code that looks like a procedure call: asm( code-string ); where code-string is an assembly code sequence given as a quoted string. The compiler will insert this string verbatim into the assembly code being generated, and hence the compiler-supplied and the usersupplied assembly will be combined. The compiler does not check the string for errors, and so the first indication of a problem might be an error report from the assembler. We illustrate the use of asm by an example where having access to the condition codes can be useful. Consider functions with the following prototypes: int ok_smul(int x, int y, int *dest); int ok_umul(unsigned x, unsigned y, unsigned *dest); Each is supposed to compute the product of arguments x and y and store the result in the memory location specified by argument dest. As return values, they should return 0 when the multiplication overflows and 1 when it does not. We have separate functions for signed and unsigned multiplication, since they overflow under different circumstances. Examining the documentation for the IA32 multiply instructions mul and imul, we see that both set the carry flag CF when they overflow. Examining Figure 3.9, we see that the instruction setae can be used to set the low-order byte of a register to 0 when this flag is set and to 1 otherwise. Thus, we wish to insert this instruction into the sequence generated by the compiler. In an attempt to use the least amount of both assembly code and detailed analysis, we attempt to implement ok_smul with the following code: code/asm/okmul.c 1 2 3 4 5 6 7 8 9 /* First attempt. Does not work */ int ok_smul1(int x, int y, int *dest) { int result = 0; *dest = x*y; asm("setae %al"); return result; } 3.15. *EMBEDDING ASSEMBLY CODE IN C PROGRAMS 189 code/asm/okmul.c The strategy here is to exploit the fact that register %eax is used to store the return value. Assuming the compiler uses this register for variable result, the first line will set the register to 0. The inline assembly will insert code that sets the low-order byte of this register appropriately, and the register will be used as the return value. Unfortunately, GCC has its own ideas of code generation. Instead of setting register %eax to 0 at the beginning of the function, the generated code does so at the very end, and so the function always returns 0. The fundamental problem is that the compiler has no way to know what the programmer’s intentions are, and how the assembly statement should interact with the rest of the generated code. By a process of trial and error (we will develop more systematic approaches shortly), we were able to generate working, but less than ideal code as follows: code/asm/okmul.c 1 2 3 4 5 6 7 8 9 10 11 12 /* Second attempt. int dummy = 0; Works in limited contexts */ int ok_smul2(int x, int y, int *dest) { int result; *dest = x*y; result = dummy; asm("setae %al"); return result; } code/asm/okmul.c This code uses the same strategy as before, but it reads a global variable dummy to initialize result to 0. Compilers are typically more conservative about generating code involving global variables, and therefore less likely to rearrange the ordering of the computations. The above code depends on quirks of the compiler to get proper behavior. In fact, it only works when compiled with optimization enabled (command line flag -O). When compiled without optimization, it stores result on the stack and retrieves its value just before returning, overwriting the value set by the setae instruction. The compiler has no way of knowing how the inserted assembly language relates to the rest of the code, because we provided the compiler no such information. 3.15.2 Extended Form of asm G CC provides an extended version of the asm that allows the programmer to specify which program values are to be used as operands to an assembly code sequence and which registers are overwritten by the assembly code. With this information the compiler can generate code that will correctly set up the required source values, execute the assembly instructions, and make use of the computed results. It will also have information it requires about register usage so that important program values are not overwritten by the assembly code instructions. 190 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS The general syntax of an extended assembly sequence is as follows: asm( code-string : output-list : input-list : overwrite-list ); where the square brackets denote optional arguments. The declaration contains a string describing the assembly code sequence, followed by optional lists of outputs (i.e., results generated by the assembly code), inputs (i.e., source values for the assembly code), and registers that are overwritten by the assembly code. These lists are separated by the colon (‘:’) character. As the square brackets show, we only include lists up to the last nonempty list. The syntax for the code string is reminiscent of that for the format string in a printf statement. It consists of a sequence of assembly code instructions separated by the semicolon (‘;’) character. Input and output operands are denoted by references %0, %1, and so on, up to possibly %9. Operands are numbered, according to their ordering first in the output list and then in the input list. Register names such as “%eax” must be written with an extra ‘%’ symbol, e.g., “%%eax.” The following is a better implementation of ok_smul using the extended assembly statement to indicate to the compiler that the assembly code generates the value for variable result: code/asm/okmul.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /* Uses the extended assembly statement to get reliable code */ int ok_smul3(int x, int y, int *dest) { int result; *dest = x*y; /* Insert the following setae %bl movzbl %bl, result */ asm("setae %%bl; movzbl : "=r" (result) /* : /* : "%ebx" /* ); return result; } code/asm/okmul.c assembly code: # Set low-order byte # Zero extend to be result %%bl,%0" Output */ No inputs */ Overwrites */ The first assembly instruction stores the test result in the single-byte register %bl. The second instruction then zero-extends and copies the value to whatever register the compiler chooses to hold result, indicated by operand %0. The output list consists of pairs of values separated by spaces. (In this example there is only a single pair). The first element of the pair is a string indicating the operand type, where ‘r’ indicates an integer register and ‘=’ indicates that the assembly code assigns a value to this operand. The second element of the pair is the operand enclosed in parentheses. It can be any assignable value (known in C as an lvalue). 3.15. *EMBEDDING ASSEMBLY CODE IN C PROGRAMS 191 The input list has the same general format, while the overwrite list simply gives the names of the registers (as quoted strings) that are overwritten. The code shown above works regardless of the compilation flags. As this example illustrates, it may take a little creative thinking to write assembly code that will allow the operands to be described in the required form. For example, there are no direct ways to specify a program value to use as the destination operand for the setae instruction, since the operand must be a single byte. Instead, we write a code sequence based on a specific register and then use an extra data movement instruction to copy the resulting value to some part of the program state. Practice Problem 3.30: G CC provides a facility for extended-precision arithmetic. This can be used to implement function ok_smul, with the advantage that it is portable across machines. A variable declared as type “ long long” will have twice the size of normal long variable. Thus, the statement: long long prod = (long long) x * y; will compute the full 64-bit product of x and y. Write a version of ok_smul that does not use any asm statements. One would expect the same code sequence could be used for ok_umul, but GCC uses the imull (signed multiply) instruction for both signed and unsigned multiplication. This generates the correct value for either product, but it sets the carry flag according to the rules for signed multiplication. We therefore need to include an assembly-code sequence that explicitly performs unsigned multiplication using the mull instruction as documented in Figure 3.8, as follows: code/asm/okmul.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 /* Uses the extended assembly statement */ int ok_umul(unsigned x, unsigned y, unsigned *dest) { int result; /* Insert the following assembly code: movl x,%eax # Get x mull y # Unsigned multiply by y movl %eax, *dest # Store low-order 4 bytes at dest setae %dl # Set low-order byte movzbl %dl, result # Zero extend to be result */ asm("movl %2,%%eax; mull %3; movl %%eax,%0; setae %%dl; movzbl %%dl,%1" : "=r" (*dest), "=r" (result) /* Outputs */ : "r" (x), "r" (y) /* Inputs */ : "%eax", "%edx" /* Overwrites */ ); return result; } 192 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS code/asm/okmul.c Recall that the mull instruction requires one of its arguments to be in register %eax and is given the second argument as an operand. We indicate this in the asm statement by using a movl to move program value x to %eax and indicating that program value y should be the argument for the mull instruction. The instruction then stores the 8-byte product in two registers with %eax holding the low-order 4 bytes and %edx holding the high-order bytes. We then use register %edx to construct the return value. As this example illustrates, comma (‘,’) characters are used to separate pairs of operands in the input and output lists, and register names in the overwrite list. Note that we were able to specify *dest as an output of the second movl instruction, since this is an assignable value. The compiler then generates the correct machine code to store the value in %eax at this memory location. Although the syntax of the asm statement is somewhat arcane, and its use makes the code less portable, this statement can be very useful for writing programs that accesses machine-level features using a minimal amount of assembly code. We have found that a certain amount of trial and error is required to get code that works. The best strategy is to compile the code with the -S switch and then examine the generated assembly code to see if it will have the desired effect. The code should be tested with different settings of switches such as with and without the -O flag. 3.16 Summary In this chapter, we have peered beneath the layer of abstraction provided by a high-level language to get a view of machine-level programming. By having the compiler generate an assembly-code representation of the machine-level program, we can gain insights into both the compiler and its optimization capabilities, along with the machine, its data types, and its instruction set. As we will see in Chapter 5, knowing the characteristics of a compiler can help when trying to write programs that will have efficient mappings onto the machine. We have also seen examples where the high-level language abstraction hides important details about the operation of a program. For example, we have seen that the behavior of floating-point code can depend on whether values are held in registers or in memory. In Chapter 7, we will see many examples where we need to know whether a program variable is on the runtime stack, in some dynamically-allocated data structure, or in some global storage locations. Understanding how programs map onto machines makes it easier to understand the difference between these kinds of storage. Assembly language is very different from C code. There is minimal distinction between different data types. The program is expressed as a sequence of instructions, each of which performs a single operation. Parts of the program state, such as registers and the runtime stack, are directly visible to the programmer. Only low-level operations are provided to support data manipulation and program control. The compiler must use multiple instructions to generate and operate on different data structures and to implement control constructs such as conditionals, loops, and procedures. We have covered many different aspects of C and how it gets compiled. We have seen the that the lack of bounds checking in C makes many programs prone to buffer overflows, and that this has made many system vulnerable to attacks. We have only examined the mapping of C onto IA32, but much of what we have covered is handled in a similar way for other combinations of language and machine. For example, compiling C++ is very similar to compiling C. In fact, early implementations of C++ simply performed a source-to-source conversion from 3.16. SUMMARY 193 C++ to C and generated object code by running a C compiler on the result. C++ objects are represented by structures, similar to a C struct. Methods are represented by pointers to the code implementing the methods. By contrast, Java is implemented in an entirely different fashion. The object code of Java is a special binary representation known as Java byte code. This code can be viewed as a machine-level program for a virtual machine. As its name suggests, this machine is not implemented directly in hardware. Instead, software interpreters process the byte code, simulating the behavior of the virtual machine. The advantage of this approach is that the same Java byte code can be executed on many different machines, whereas the machine code we have considered runs only under IA32. Bibliographic Notes The best references on IA32 are from Intel. Two useful references are part of their series on software development. The basic architecture manual [17] gives an overview of the architecture from the perspective of an assembly-language programmer, and the instruction set reference manual [18] gives detailed descriptions of the different instructions. These references contain far more information than is required to understand Linux code. In particular, with flat mode addressing, all of the complexities of the segmented addressing scheme can be ignored. The GAS format used by the Linux assembler is very different from the standard format used in Intel documentation and by other compilers (particularly those produced by Microsoft). One main distinction is that the source and destination operands are given in the opposite order On a Linux machine, running the command info as will display information about the assembler. One of the subsections documents machine-specific information, including a comparison of GAS with the more standard Intel notation. Note that GCC refers to these machines as “i386”—it generates code that could even run on a 1985 vintage machine. Muchnick’s book on compiler design [52] is considered the most comprehensive reference on code optimization techniques. It covers many of the techniques we discuss here, such as register usage conventions and the advantages of generating code for loops based on their do-while form. Much has been written about the use of buffer overflow to attack systems over the Internet. Detailed analyses of the 1988 Internet worm have been published by Spafford [69] as well as by members of the team at MIT who helped stop its spread [24]. Since then, a number of papers and projects have generated about both creating and preventing buffer overflow attacks, such as [19]. Homework Problems Homework Problem 3.31 [Category 1]: You are given the following information. A function with prototype int decode2(int x, int y, int z); is compiled into assembly code. The body of the code is as follows: 194 1 2 3 4 5 6 7 8 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS movl 16(%ebp),%eax movl 12(%ebp),%edx subl %eax,%edx movl %edx,%eax imull 8(%ebp),%edx sall $31,%eax sarl $31,%eax xorl %edx,%eax Parameters x, y, and z are stored at memory locations with offsets 8, 12, and 16 relative to the address in register %ebp. The code stores the return value in register %eax. Write C code for decode2 that will have an effect equivalent to our assembly code. You can test your solution by compiling your code with the -S switch. Your compiler may not generate identical code, but it should be functionally equivalent. Homework Problem 3.32 [Category 2]: The following C code is almost identical to that in Figure 3.11: 1 2 3 4 5 6 7 8 9 10 int absdiff2(int x, int y) { int result; if (x < y) result = y-x; else result = x-y; return result; } When compiled, however, it gives a different form of assembly code: 1 2 3 4 5 6 7 8 9 movl 8(%ebp),%edx movl 12(%ebp),%ecx movl %edx,%eax subl %ecx,%eax cmpl %ecx,%edx jge .L3 movl %ecx,%eax subl %edx,%eax .L3: A. What subtractions are performed when Ü Ý? When Ü Ý? B. In what way does this code deviate from the standard implementation of if-else described previously? C. Using C syntax (including goto’s), show the general form of this translation. D. What restrictions must be imposed on the use of this translation to guarantee that it has the behavior specified by the C code? 3.16. SUMMARY The jump targets Arguments p1 and p2 are in registers %ebx and %ecx. 1 .L15: MODE_A 2 movl (%ecx),%edx 3 movl (%ebx),%eax 4 movl %eax,(%ecx) 5 jmp .L14 6 .p2align 4,,7 Inserted to optimize cache performance 7 .L16: MODE_B 8 movl (%ecx),%eax 9 addl (%ebx),%eax 10 movl %eax,(%ebx) 11 movl %eax,%edx 12 jmp .L14 13 .p2align 4,,7 Inserted to optimize cache performance 14 .L17: MODE_C 15 movl $15,(%ebx) 16 movl (%ecx),%edx 17 jmp .L14 18 .p2align 4,,7 Inserted to optimize cache performance 19 .L18: MODE_D 20 movl (%ecx),%eax 21 movl %eax,(%ebx) 22 .L19: MODE_E 23 movl $17,%edx 24 jmp .L14 25 .p2align 4,,7 Inserted to optimize cache performance 26 .L20: 27 movl $-1,%edx 28 .L14: default 29 movl %edx,%eax Set return value 195 Figure 3.36: Assembly Code for Problem 3.33. This code implements the different branches of a switch statement. Homework Problem 3.33 [Category 2]: The following code shows an example of branching on an enumerated type value in a switch statement. Recall that enumerated types in C are simply a way to introduce a set of names having associated integer values. By default, the values assigned to the names go from 0 upward. In our code, the actions associated with the different case labels have been omitted. /* Enumerated type creates set of constants numbered 0 and upward */ typedef enum {MODE_A, MODE_B, MODE_C, MODE_D, MODE_E} mode_t; int switch3(int *p1, int *p2, mode_t action) { 196 int result = 0; switch(action) { case MODE_A: case MODE_B: case MODE_C: case MODE_D: case MODE_E: default: } return result; } CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS The part of the generated assembly code implementing the different actions is shown shown in Figure 3.36. The annotations indicate the values stored in the registers and the case labels for the different jump destinations. A. What register corresponds to program variable result? B. Fill in the missing parts of the C code. Watch out for cases that fall through. Homework Problem 3.34 [Category 2]: Switch statements are particularly challenging to reverse engineer from the object code. In the following procedure, the body of the switch statement has been removed. 1 2 3 4 5 6 7 8 9 10 11 int switch_prob(int x) { int result = x; switch(x) { /* Fill in code here */ } return result; } Figure 3.37 shows the disassembled object code for the procedure. We are only interested in the part of code shown on lines 4 through 16. We can see on line 4 that parameter x (at offset 8 relative to %ebp) is loaded into register %eax, corresponding to program variable result. The “lea 0x0(%esi),%esi” 3.16. SUMMARY 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 197 080483c0 <switch_prob>: 80483c0: 55 80483c1: 89 e5 80483c3: 8b 45 08 80483c6: 8d 50 ce 80483c9: 83 fa 05 80483cc: 77 1d 80483ce: ff 24 95 68 84 04 08 80483d5: c1 e0 02 80483d8: eb 14 80483da: 8d b6 00 00 00 00 80483e0: c1 f8 02 80483e3: eb 09 80483e5: 8d 04 40 80483e8: 0f af c0 80483eb: 83 c0 0a 80483ee: 89 ec 80483f0: 5d 80483f1: c3 80483f2: 89 f6 push mov mov lea cmp ja jmp shl jmp lea sar jmp lea imul add mov pop ret mov %ebp %esp,%ebp 0x8(%ebp),%eax 0xffffffce(%eax),%edx $0x5,%edx 80483eb <switch_prob+0x2b> *0x8048468(,%edx,4) $0x2,%eax 80483ee <switch_prob+0x2e> 0x0(%esi),%esi $0x2,%eax 80483ee <switch_prob+0x2e> (%eax,%eax,2),%eax %eax,%eax $0xa,%eax %ebp,%esp %ebp %esi,%esi Figure 3.37: Disassembled Code for Problem 3.34. instruction on line 11 is a nop instruction inserted to make the instruction on line 12 start on an address that is a multiple of 16. The jump table resides in a different area of memory. Using the debugger GDB we can examine the six 4-byte words of memory starting at address 0x8048468 with the command x/6w 0x8048468. G DB prints the following: (gdb) x/6w 0x8048468 0x8048468: 0x080483d5 0x8048478: 0x080483e5 (gdb) 0x080483eb 0x080483e8 0x080483d5 0x080483e0 Fill in the body of the switch statement with C code that will have the same behavior as the object code. Homework Problem 3.35 [Category 2]: The code generated by the C compiler for var_prod_ele (Figure 3.24(b)) is not optimal. Write code for this function based on a hybrid of procedures fix_prod_ele_opt (Figure 3.23) and var_prod_ele_opt (Figure 3.24) that is correct for all values of n, but compiles into code that can keep all of its temporary data in registers. Recall that the processor only has six registers available to hold temporary data, since registers %ebp and %esp cannot be used for this purpose. One of these registers must be used to hold the result of the multiply instruction. Hence, you must reduce the number of local variables in the loop from six (result, Aptr, B, nTjPk, n, and cnt) to five. Homework Problem 3.36 [Category 2]: 198 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS You are charged with maintaining a large C program, and you come across the following code: code/asm/structprob-ans.c 1 2 3 4 5 6 7 8 9 10 11 12 typedef struct { int left; a_struct a[CNT]; int right; } b_struct; void test(int i, b_struct *bp) { int n = bp->left + bp->right; a_struct *ap = &bp->a[i]; ap->x[ap->idx] = n; } code/asm/structprob-ans.c Unfortunately, the ‘.h’ file defining the compile-time constant CNT and the structure a_struct are in files for which you do not have access privileges. Fortunately, you have access to a ‘.o’ version of code, which you are able to disassemble with the objdump program, yielding the disassembly shown in Figure 3.38. Using your reverse engineering skills, deduce the following: A. The value of CNT. B. A complete declaration of structure a_struct. Assume that the only fields in this structure are idx and x. Homework Problem 3.37 [Category 1]: Write a function good_echo that reads a line from standard input and writes it to standard output. Your implementation should work for an input line of arbitrary length. You may use the library function fgets, but you must make sure your function works correctly even when the input line requires more space than you have allocated for your buffer. Your code should also check for error conditions and return when one is encounted. You should refer to the definitions of the standard I/O functions for documentation [30, 37]. Homework Problem 3.38 [Category 3]: In this problem, you will mount a buffer overflow attack on your own program. As stated earlier, we do not condone using this or any other form of attack to gain unauthorized access to a system, but by doing this exercise, you will learn a lot about machine-level programming. Download the file bufbomb.c from the CS:APP website and compile it to create an executable program. In bufbomb.c, you will find the following functions: 1 int getbuf() 3.16. SUMMARY 2 3 4 5 6 7 8 9 10 11 12 13 14 199 { char buf[12]; getxs(buf); return 1; } void test() { int val; printf("Type Hex string:"); val = getbuf(); printf("getbuf returned 0x%x\n", val); } The function getxs (also in bufbomb.c) is similar to the library gets, except that it reads characters encoded as pairs of hex digits. For example, to give it a string “0123,” the user would type in the string “30 31 32 33.” The function ignores blank characters. Recall that decimal digit Ü has ASCII representation 0x3Ü. A typical execution of the program is as follows: unix> ./bufbomb Type Hex string: 30 31 32 33 getbuf returned 0x1 Looking at the code for the getbuf function, it seems quite apparent that it will return value ½ whenever it is called. It appears as if the call to getxs has no effect. Your task is to make getbuf return ¼¿ ¿ (0xdeadbeef) to test, simply by typing an appropriate hexadecimal string to the prompt. Here are some ideas that will help you solve the problem: ¯ ¯ ¯ Use OBJDUMP to create a disassembled version of bufbomb. Study this closely to determine how the stack frame for getbuf is organized and how overflowing the buffer will alter the saved program state. Run your program under GDB. Set a breakpoint within getbuf and run to this breakpoint. Determine such parameters as the value of %ebp and the saved value of any state that will be overwritten when you overflow the buffer. Determining the byte encoding of instruction sequences by hand is tedious and prone to errors. You can let tools do all of the work by writing an assembly code file containing the instructions and data you want to put on the stack. Assemble this file with GCC and disassemble it with OBJDUMP. You should be able to get the exact byte sequence that you will type at the prompt. O BJDUMP will produce some pretty strange looking assembly instructions when it tries to disassemble the data in your file, but the hexadecimal byte sequence should be correct. Keep in mind that your attack is very machine and compiler specific. You may need to alter your string when running on a different machine or with a different version of GCC. 200 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 CHAPTER 3. MACHINE-LEVEL REPRESENTATION OF C PROGRAMS 00000000 <test>: 0: 55 1: 89 e5 3: 53 4: 8b 45 08 7: 8b 4d 0c a: 8d 04 80 d: 8d 44 81 04 11: 8b 10 13: c1 e2 02 16: 8b 99 b8 00 00 00 1c: 03 19 1e: 89 5c 02 04 22: 5b 23: 89 ec 25: 5d 26: c3 push mov push mov mov lea lea mov shl mov add mov pop mov pop ret %ebp %esp,%ebp %ebx 0x8(%ebp),%eax 0xc(%ebp),%ecx (%eax,%eax,4),%eax 0x4(%ecx,%eax,4),%eax (%eax),%edx $0x2,%edx 0xb8(%ecx),%ebx (%ecx),%ebx %ebx,0x4(%edx,%eax,1) %ebx %ebp,%esp %ebp Figure 3.38: Disassembled Code For Problem 3.36. Homework Problem 3.39 [Category 2]: Use the asm statement to implement a function with the following prototype: void full_umul(unsigned x, unsigned y, unsigned dest); This function should compute the full 64-bit product of its arguments and store the results in the destination array, with dest[0] having the low-order 4 bytes and dest[1] having the high-order 4 bytes. Homework Problem 3.40 [Category 2]: The fscale instruction computes the function Ü ¡ ¾ÊÌ ´Ýµ for floating-point values Ü and Ý , where ÊÌ denotes the round-toward-zero function, rounding positive numbers downward and negative numbers upward. The arguments to fscale come from the floating-point register stack, with Ü in %st(0) and Ý in %st(1). It writes the computed value written %st(0) without popping the second argument. (The actual implementation of this instruction works by adding ÊÌ ´Ý µ to the exponent of Ü). Using an asm statement, implement a function with the following prototype double scale(double x, int n, double *dest); that computes Ü ¡ ¾Ò using the fscale instruction and stores the result at the location designated by pointer dest. Hint: Extended asm does not provide very good support for IA32 floating point. In this case, however, you can access the arguments from the program stack. Chapter 4 Processor Architecture To appear in the final version of the manuscript. 201 202 CHAPTER 4. PROCESSOR ARCHITECTURE Chapter 5 Optimizing Program Performance Writing an efficient program requires two types of activities. First, we must select the best set of algorithms and data structures. Second, we must write source code that the compiler can effectively optimize to turn into efficient executable code. For this second part, it is important to understand the capabilities and limitations of optimizing compilers. Seemingly minor changes in how a program is written can make large differences in how well a compiler can optimize it. Some programming languages are more easily optimized than others. Some features of C, such as the ability to perform pointer arithmetic and casting, make it challenging to optimize. Programmers can often write their programs in ways that make it easier for compilers to generate efficient code. In approaching the issue of program development and optimization, we must consider how the code will be used and what critical factors affect it. In general, programmers must make a trade-off between how easy a program is to implement and maintain, and how fast it will run. At an algorithmic level, a simple insertion sort can be programmed in a matter of minutes, whereas a highly efficient sort routine may take a day or more to implement and optimize. At the coding level, many low-level optimizations tend to reduce code readability and modularity. This makes the programs more susceptible to bugs and more difficult to modify or extend. For a program that will just be run once to generate a set of data points, it is more important to write it in a way that minimizes programming effort and ensures correctness. For code that will be executed repeatedly in a performance-critical environment, such as in a network router, much more extensive optimization may be appropriate. In this chapter, we describe a number of techniques for improving code performance. Ideally, a compiler would be able to take whatever code we write and generate the most efficient possible machine-level program having the specified behavior. In reality, compilers can only perform limited transformations of the program, and they can be thwarted by optimization blockers—aspects of the program whose behavior depends strongly on the execution environment. Programmers must assist the compiler by writing code that can be optimized readily. In the compiler literature, optimization techniques are classified as either “machine independent,” meaning that they should be applied regardless of the characteristics of the computer that will execute the code, or as “machine dependent,” meaning they depend on many low-level details of the machine. We organize our presentation along similar lines, starting with program transformations that should be standard practice when writing any program. We then progress to transformations whose efficacy depends on the characteristics of the target machine and compiler. These transformations also tend to reduce 203 204 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE the modularity and readability of the code and hence should be applied when maximum performance is the dominant concern. To maximize the performance of a program, both the programmer and the compiler need to have a model of the target machine, specifying how instructions are processed and the timing characteristics of the different operations. For example, the compiler must know timing information to be able to decide whether it is should use a multiply instruction or some combinations of shifts and adds. Modern computers use sophisticated techniques to process a machine-level program, executing many instructions in parallel and possibly in a different order than they appear in the program. Programmers must understand how these processors work to be able to tune their programs for maximum speed. We present a high-level model of such a machine based on some recent models of Intel processors. We devise a graphical notation that can be used to visualize the execution of instructions on the processor and to predict program performance. We conclude by discussing issues related to optimizing large programs. We describe the use of code profilers—tools that measure the performance of different parts of a program. This analysis can help find inefficiencies in the code and identify the parts of the program on which we should focus our optimization efforts. Finally, we present an important observation, known as Amdahl’s Law quantifying the overall effect of optimizing some portion of a system. In this presentation, we make code optimization look like a simple, linear process of applying a series of transformations to the code in a particular order. In fact, the task is not nearly so straightforward. A fair amount of trial-and-error experimentation is required. This is especially true as we approach the later optimization stages, where seemingly small changes can cause major changes in performance, while some very promising techniques prove ineffective. As we will see in the examples, it can be difficult to explain exactly why a particular code sequence has a particular execution time. Performance can depend on many detailed features of the processor design for which we have relatively little documentation or understanding. This is another reason to try a number of different variations and combinations of techniques. Studying the assembly code is one of the most effective means of gaining some understanding of the compiler and how the generated code will run. A good strategy is to start by looking carefully at the code for the inner loops. One can identify performance-reducing attributes such as excessive memory references and poor use of registers. Starting with the assembly code, we can even predict what operations will be performed in parallel and how well they will use the processor resources. 5.1 Capabilities and Limitations of Optimizing Compilers Modern compilers employ sophisticated algorithms to determine what values are computed in a program and how they are used. They can then exploit opportunities to simplify expressions, to use a single computation in several different places, and to reduce the number of times a given computation must be performed. Unfortunately, optimizing compilers have limitations, due to constraints imposed on their behavior, to the limited understanding they have of the program’s behavior and how it will be used, and to the requirement that they perform the compilation quickly. Compiler optimization is supposed to be invisible to the user. When a programmer compiles code with optimization enabled (e.g., using the -O command line option), the code should have identical behavior as when compiled otherwise, except that it should run faster. This requirement restricts the ability of the 5.1. CAPABILITIES AND LIMITATIONS OF OPTIMIZING COMPILERS compiler to perform some types of optimizations. Consider, for example, the following two procedures: 1 2 3 4 5 6 7 8 9 10 205 void twiddle1(int *xp, int *yp) { *xp += *yp; *xp += *yp; } void twiddle2(int *xp, int *yp) { *xp += 2* *yp; } At first glance, both procedures seem to have identical behavior. They both add twice the value stored at the location designated by pointer yp to that designated by pointer xp. On the other hand, function twiddle2 is more efficient. It requires only three memory references (read *xp, read *yp, write *xp), whereas twiddle1 requires six (two reads of *xp, two reads of *yp, and two writes of *xp). Hence, if a compiler is given procedure twiddle1 to compile, one might think it could generate more efficient code based on the computations performed by twiddle2. Consider however, the case where xp and yp are equal. Then function twiddle1 will perform the following computations: 3 4 *xp += *xp; *xp += *xp; /* Double value at xp */ /* Double value at xp */ The result will be that the value at xp will be increased by a factor of 4. On the other hand, function twiddle2 will perform the following computation: 9 *xp += 2* *xp; /* Triple value at xp */ The result will be that the value at xp will be increased by a factor of 3. The compiler knows nothing about how twiddle1 will be called, and so it must assume that arguments xp and yp can be equal. Therefore it cannot generate code in the style of twiddle2 as an optimized version of twiddle1. This phenomenon is known as memory aliasing. The compiler must assume that different pointers may designate a single place in memory. This leads to one of the major optimization blockers, aspects of programs that can severely limit the opportunities for a compiler to generate optimized code. Practice Problem 5.1: The following problem illustrates the way memory aliasing can cause unexpected program behavior. Consider the following procedure to swap two values: 1 /* Swap value x at xp with value y at yp */ 206 2 3 4 5 6 7 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE void swap(int { *xp = *xp *yp = *xp *xp = *xp } *xp, int *yp) + *yp; /* x+y */ - *yp; /* x+y-y = x */ - *yp; /* x+y-x = y */ If this procedure is called with xp equal to yp, what effect will it have? A second optimization blocker is due to function calls. As an example, consider the following two procedures: 1 2 3 4 5 6 7 8 9 10 11 int f(int); int func1(x) { return f(x) + f(x) + f(x) + f(x); } int func2(x) { return 4*f(x); } It might seem at first that both compute the same result, but with func2 calling f only once, whereas func1 calls it four times. It is tempting to generate code in the style of func2 when given func1 as source. Consider, however, the following code for f 1 2 3 4 5 6 7 int counter = 0; int f(int x) { return counter++; } This function has a side effect—it modifies some part of the global program state. Changing the number of times it gets called changes the program behavior. In particular, a call to func1 would return ¼ · ½ · ¾ · ¿ , whereas a call to func2 would return ¡ ¼ ¼, assuming both started with global variable counter set to 0. Most compilers do not try to determine whether a function is free of side effects and hence is a candidate for optimizations such as those attempted in func2. Instead, the compiler assumes the worst case and leaves all function calls intact. 5.2. EXPRESSING PROGRAM PERFORMANCE 207 Among compilers, the GNU compiler GCC is considered adequate, but not exceptional, in terms of its optimization capabilities. It performs basic optimizations but does not perform the radical transformations on programs that more “aggressive” compilers do. As a consequence, programmers using GCC must put more effort into writing programs in a way that simplifies the compiler’s task of generating efficient code. 5.2 Expressing Program Performance We need a way to express program performance that can guide us in improving the code. A useful measure for many programs is Cycles Per Element (CPE). This measure helps us understand the loop performance of an iterative program at a detailed level. Such a measure is appropriate for programs that perform a repetitive computation, such as processing the pixels in an image or computing the elements in a matrix product. The sequencing of activities by a processor is controlled by a clock providing a regular signal of some frequency, expressed in either Megahertz (Mhz), i.e., millions of cycles per second, or Gigahertz (GHz), i.e., billions of cycles per second. For example, when product literature characterizes a system as a “1.4 GHz” processor, it means that the processor clock runs at 1,400 Megahertz. The time required for each clock cycle is given by the reciprocal of the clock frequency. These are typically expressed in nanoseconds, i.e., billionths of a second. A 2 GHz clock has a 0.5-nanosecond period, while a 500 Mhz clock has a period of 2 nanoseconds. From a programmer’s perspective, it is more instructive to express measurements in clock cycles rather than nanoseconds. That way, the measurements are less dependent on the particular model of processor being evaluated, and they help us understand exactly how the program is being executed by the machine. Many procedures contain a loop that iterates over a set of elements. For example, functions vsum1 and vsum2 in Figure 5.1 both compute the sum of two vectors of length Ò. The first computes one element of the destination vector per iteration. The second uses a technique known as loop unrolling to compute two elements per iteration. This version will only work properly for even values of Ò. Later in this chapter we cover loop unrolling in more detail, including how to make it work for arbitrary values of Ò. The time required by such a procedure can be characterized as a constant plus a factor proportional to the number of elements processed. For example, Figure 5.2 shows a plot of the number of clock cycles required by the two functions for a range of values of Ò. Using a least squares fit, we find that the two function run times (in clock cycles) can be approximated by lines with equations ¼ · ¼Ò and ¿ · ¿ Ò, respectively. These equations indicated an overhead of 80 to 84 cycles to initiate the procedure, set up the loop, and complete the procedure, plus a linear factor of 3.5 or 4.0 cycles per element. For large values of Ò (say greater than 50), the run times will be dominated by the linear factors. We refer to the coefficients in these terms as the effective number of Cycles per Element, abbreviated “CPE.” Note that we prefer measuring the number of cycles per element rather than the number of cycles per iteration, because techniques such as loop unrolling allow us to use fewer iterations to complete the computation, but our ultimate concern is how fast the procedure will run for a given vector length. We focus our efforts on minimizing the CPE for our computations. By this measure, vsum2, with a CPE of 3.50, is superior to vsum1, with a CPE of 4.0. Aside: What is a least squares fit? ÜÒ ÝÒ , we often try to draw a line that best approximates the X-Y trend For a set of data points ܽ ݽ ÑÜ that minimizes the represented by this data. With a least squares fit, we look for a line of the form Ý ´ µ ´ µ · 208 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE code/opt/vsum.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 void vsum1(int n) { int i; for (i = 0; i < n; i++) c[i] = a[i] + b[i]; } /* Sum vector of n elements (n must be even) */ void vsum2(int n) { int i; for (i = 0; i < n; i+=2) { /* Compute two elements per iteration */ c[i] = a[i] + b[i]; c[i+1] = a[i+1] + b[i+1]; } } code/opt/vsum.c Figure 5.1: Vector Sum Functions. These provide examples for how we express program performance. 1000 900 800 700 600 Cycles 500 400 300 200 100 0 0 50 100 Ele me nts 150 200 vsum1 Slope = 4.0 vsum2 Slope = 3.5 Figure 5.2: Performance of Vector Sum Functions. The slope of the lines indicates the number of clock cycles per element (CPE). 5.3. PROGRAM EXAMPLE length data 012 length–1 ••• 209 Figure 5.3: Vector Abstract Data Type. A vector is represented by header information plus array of designated length. following error measure: ´ Ñ µ ½ ´ Ò ÑÜ · µ¾ Ý An algorithm for computing Ñ and can be derived by finding the derivatives of and setting them to 0. End Aside. ´ Ñ µ with respect to Ñ and 5.3 Program Example To demonstrate how an abstract program can be systematically transformed into more efficient code, consider the simple vector data structure, shown in Figure 5.3. A vector is represented with two blocks of memory. The header is a structure declared as follows: code/opt/vec.h 1 2 3 4 5 /* Create abstract data type for vector */ typedef struct { int len; data_t *data; } vec_rec, *vec_ptr; code/opt/vec.h The declaration uses data type data t to designate the data type of the underlying elements. In our evaluation, we measure the performance of our code for data types int, float, and double. We do this by compiling and running the program separately for different type declarations, for example: typedef int data_t; In addition to the header, we allocate an array of len objects of type data t to hold the actual vector elements. Figure 5.4 shows some basic procedures for generating vectors, accessing vector elements, and determining the length of a vector. An important feature to note is that get_vec_element, the vector access routine, performs bounds checking for every vector reference. This code is similar to the array representations used in many other languages, including Java. Bounds checking reduces the chances of program error, but, as we will see, significantly affects program performance. As an optimization example, consider the code shown in Figure 5.5, which combines all of the elements in a vector into a single value according to some operation. By using different definitions of compile-time constants IDENT and OPER, the code can be recompiled to perform different operations on the data. In particular, using the declarations 210 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE code/opt/vec.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 /* Create vector of specified length */ vec_ptr new_vec(int len) { /* allocate header structure */ vec_ptr result = (vec_ptr) malloc(sizeof(vec_rec)); if (!result) return NULL; /* Couldn’t allocate storage */ result->len = len; /* Allocate array */ if (len > 0) { data_t *data = (data_t *)calloc(len, sizeof(data_t)); if (!data) { free((void *) result); return NULL; /* Couldn’t allocate storage */ } result->data = data; } else result->data = NULL; return result; } /* * Retrieve vector element and store at dest. * Return 0 (out of bounds) or 1 (successful) */ int get_vec_element(vec_ptr v, int index, data_t *dest) { if (index < 0 || index >= v->len) return 0; *dest = v->data[index]; return 1; } /* Return length of vector */ int vec_length(vec_ptr v) { return v->len; } code/opt/vec.c Figure 5.4: Implementation of Vector Abstract Data Type. In the actual program, data type data t is declared to be int, float, or double . 5.3. PROGRAM EXAMPLE 211 code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 /* Implementation with maximum use of data abstraction */ void combine1(vec_ptr v, data_t *dest) { int i; *dest = IDENT; for (i = 0; i < vec_length(v); i++) { data_t val; get_vec_element(v, i, &val); *dest = *dest OPER val; } } code/opt/combine.c Figure 5.5: Initial Implementation of Combining Operation. Using different declarations of identity element IDENT and combining operation OPER, we can measure the routine for different operations. #define IDENT 0 #define OPER + we sum the elements of the vector. Using the declarations: #define IDENT 1 #define OPER * we compute the product of the vector elements. As a starting point, here are the CPE measurements for combine1 running on an Intel Pentium III, trying all combinations of data type and combining operation. In our measurements, we found that the timings were generally equal for single and double-precision floating point data. We therefore show only the measurements for single precision. Function combine1 combine1 Page 211 211 Method Abstract unoptimized Abstract -O2 Integer + * 42.06 41.86 31.25 33.25 Floating Point + * 41.44 160.00 31.25 143.00 By default, the compiler generates code suitable for stepping with a symbolic debugger. Very little optimization is performed since the intention is to make the object code closely match the computations indicated in the source code. By simply setting the command line switch to ‘ -O2’ we enable optimizations. As can be seen, this significantly improves the program performance. In general, it is good to get into the habit of enabling this level of optimization, unless the program is being compiled with the intention of debugging it. For the remainder of our measurements we enable this level of compiler optimization. 212 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 13 /* Move call to vec_length out of loop */ void combine2(vec_ptr v, data_t *dest) { int i; int length = vec_length(v); *dest = IDENT; for (i = 0; i < length; i++) { data_t val; get_vec_element(v, i, &val); *dest = *dest OPER val; } } code/opt/combine.c Figure 5.6: Improving the Efficiency of the Loop Test. By moving the call to vec length out of the loop test, we eliminate the need to execute it on every iteration. Note also that the times are fairly comparable for the different data types and the different operations, with the exception of floating-point multiplication. These very high cycle counts for multiplication are due to an anomaly in our benchmark data. Identifying such anomalies is an important component of performance analysis and optimization. We return to this issue in Section 5.11.1. We will see that we can improve on this performance considerably. 5.4 Eliminating Loop Inefficiencies Observe that procedure combine1, as shown in Figure 5.5, calls function vec_length as the test condition of the for loop. Recall from our discussion of loops that the test condition must be evaluated on every iteration of the loop. On the other hand, the length of the vector does not change as the loop proceeds. We could therefore compute the vector length only once and use this value in our test condition. Figure 5.6 shows a modified version, called combine2, that calls vec length at the beginning and assigns the result to a local variable length. This local variable is then used in the test condition of the for loop. Surprisingly, this small change has a significant effect on program performance. Function combine1 combine2 Page 211 212 Method Abstract -O2 Move vec length Integer + * 31.25 33.25 22.61 21.25 Floating Point + * 31.25 143.00 21.15 135.00 As the table above shows, we eliminate around 10 clock cycles for each vector element with this simple transformation. 5.4. ELIMINATING LOOP INEFFICIENCIES 213 This optimization is an instance of a general class of optimizations known as code motion. They involve identifying a computation that is performed multiple times, (e.g., within a loop), but such that the result of the computation will not change. We can therefore move the computation to an earlier section of the code that does not get evaluated as often. In this case, we moved the call to vec length from within the loop to just before the loop. Optimizing compilers attempt to perform code motion. Unfortunately, as discussed previously, they are typically very cautious about making transformations that change where or how many times a procedure is called. They cannot reliably detect whether or not a function will have side effects, and so they assume that it might. For example, if vec length had some side effect, then combine1 and combine2 could have different behaviors. In cases such as these, the programmer must help the compiler by explicitly performing the code motion. As an extreme example of the loop inefficiency seen in combine1, consider the procedure lower1 shown in Figure 5.7. This procedure is styled after routines submitted by several students as part of a network programming project. Its purpose is to convert all of the upper-case letters in a string to lower case. The procedure steps through the string, converting each upper-case character to lower case. The library procedure strlen is called as part of the loop test of lower1. A simple version of strlen is also shown in Figure 5.7. Since strings in C are null-terminated character sequences, strlen must step through the sequence until it hits a null character. For a string of length Ò, strlen takes time proportional to Ò. Since strlen is called on each of the Ò iterations of lower1, the overall run time of lower1 is quadratic in the string length. This analysis is confirmed by actual measurements of the procedure for different length strings, as shown Figure 5.8. The graph of the run time for lower1 rises steeply as the string length increases. The lower part of the figure shows the run times for eight different lengths (not the same as shown in the graph), each of which is a power of two. Observe that for lower1 each doubling of the string length causes a quadrupling of the run time. This is a clear indicator of quadratic complexity. For a string of length 262,144, lower1 requires a full 3.1 minutes of CPU time. Function lower2 shown in Figure 5.7 is identical to that of lower1, except that we have moved the call to strlen out of the loop. The performance improves dramatically. For a string length of 262,144, the function requires just 0.006 seconds—over 30,000 times faster than lower1. Each doubling of the string length causes a doubling of the run time—a clear indicator of linear complexity. For longer strings, the run time improvement will be even greater. In an ideal world, a compiler would recognize that each call to strlen in the loop test will return the same result, and hence the call could be moved out of the loop. This would require a very sophisticated analysis, since strlen checks the elements of the string and these values are changing as lower1 proceeds. The compiler would need to detect that even though the characters within the string are changing, none are being set from nonzero to zero, or vice-versa. Such an analysis is well beyond that attempted by even the most aggressive compilers. Programmers must do such transformations themselves. This example illustrates a common problem in writing programs, in which a seemingly trivial piece of code has a hidden asymptotic inefficiency. One would not expect a lower-case conversion routine to be a limiting factor in a program’s performance. Typically, programs are tested and analyzed on small data sets, for which the performance of lower1 is adequate. When the program is ultimately deployed, however, it is 214 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE code/opt/lower.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 /* Convert string to lower case: slow */ void lower1(char *s) { int i; for (i = 0; i < strlen(s); i++) if (s[i] >= ’A’ && s[i] <= ’Z’) s[i] -= (’A’ - ’a’); } /* Convert string to lower case: faster */ void lower2(char *s) { int i; int len = strlen(s); for (i = 0; i < len; i++) if (s[i] >= ’A’ && s[i] <= ’Z’) s[i] -= (’A’ - ’a’); } /* Implementation of library function strlen */ /* Compute length of string */ size_t strlen(const char *s) { int length = 0; while (*s != ’\0’) { s++; length++; } return length; } code/opt/lower.c Figure 5.7: Lower-Case Conversion Routines. The two procedures have radically different performance. 5.4. ELIMINATING LOOP INEFFICIENCIES 215 250 200 CPU Seconds 150 lower1 100 50 lower2 0 0 50000 100000 150000 200000 250000 String Length Function lower1 lower2 8,192 0.15 0.0002 16,384 0.62 0.0004 String Length 32,768 65,536 3.19 12.75 0.0008 0.0016 131,072 51.01 0.0031 262,144 186.71 0.0060 Figure 5.8: Comparative Performance of Lower-Case Conversion Routines. The original code lower1 has quadratic asymptotic complexity due to an inefficient loop structure. The modified code lower2 has linear complexity. 216 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE entirely possible that the procedure could be applied to a string of one million characters, for which lower1 would over require nearly one hour of CPU time. All of a sudden this benign piece of code has become a major performance bottleneck. By contrast, lower2 would complete in well under one second. Stories abound of major programming projects in which problems of this sort occur. Part of the job of a competent programmer is to avoid ever introducing such asymptotic inefficiency. Practice Problem 5.2: Consider the following functions: int min(int x, int y) { return x < y ? x : y; } int max(int x, int y) { return x < y ? y : x; } void incr(int *xp, int v) { *xp += v; } int square(int x) { return x*x; } Here are three code fragments that call these functions A. B. C. for (i = min(x, y); i < max(x, y); incr(&i, 1)) t += square(i); for (i = max(x, y) - 1; i >= min(x, y); incr(&i, -1)) t += square(i); int low = min(x, y); int high = max(x, y); for (i = low; i < high; incr(&i, 1)) t += square(i); Assume x equals 10 and y equals 100. Fill in the table below indicating the number of times each of the four functions is called for each of these code fragments. Code A. B. C. min max incr square 5.5 Reducing Procedure Calls As we have seen, procedure calls incur substantial overhead and block most forms of program optimization. We can see in the code for combine2 (Figure 5.6) that get vec element is called on every loop iteration to retrieve the next vector element. This procedure is especially costly since it performs bounds checking. Bounds checking might be a useful feature when dealing with arbitrary array accesses, but a simple analysis of the code for combine2 shows that all references will be valid. Suppose instead that we add a function get vec start to our abstract data type. This function returns the starting address of the data array, as shown in Figure 5.9. We could then write the procedure shown as combine3 in this figure, having no function calls in the inner loop. Rather than making a function call 5.5. REDUCING PROCEDURE CALLS 217 code/opt/vec.c 1 2 3 4 data_t *get_vec_start(vec_ptr v) { return v->data; } code/opt/vec.c code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 /* Direct access to vector data */ void combine3(vec_ptr v, data_t *dest) { int i; int length = vec_length(v); data_t *data = get_vec_start(v); *dest = IDENT; for (i = 0; i < length; i++) { *dest = *dest OPER data[i]; } } code/opt/combine.c Figure 5.9: Eliminating Function Calls within the Loop. The resulting code runs much faster, at some cost in program modularity. 218 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE to retrieve each vector element, it accesses the array directly. A purist might say that this transformation seriously impairs the program modularity. In principle, the user of the vector abstract data type should not even need to know that the vector contents are stored as an array, rather than as some other data structure such as a linked list. A more pragmatic programmer would argue the advantage of this transformation based on the following experimental results: Function combine2 combine3 Page 212 217 Method Move vec length Direct data access Integer + * 20.66 21.25 6.00 9.00 Floating Point + * 21.15 135.00 8.00 117.00 There is a improvement of up to a factor of 3.5X. For applications where performance is a significant issue, one must often compromise modularity and abstraction for speed. It is wise to include documentation on the transformations applied, and the assumptions that led to them, in case the code needs to be modified later. Aside: Expressing relative performance. The best way to express a performance improvement is as a ratio of the form ÌÓÐ ÌÒ Û , where ÌÓÐ is the time required for the original version and ÌÒ Û is the time required by the modified version. This will be a number greater than 1.0 if any real improvement occurred. We use the suffix ‘X’ to indicate such a ratio, where the factor “3.5X” is expressed verbally as “3.5 times.” The more traditional way of expressing relative change as a percentage works well when the change is small, but its definition is ambiguous. Should it be ÌÓÐ ÌÒ Û ÌÒ Û or possibly ÌÓÐ ÌÒ Û ÌÓÐ , or something else? In addition, it is less instructive for large changes. Saying that “performance improved by 250%” is more difficult to comprehend than simply saying that the performance improved by a factor of 3.5. End Aside. ½¼¼ ¡ ´ µ ½¼¼ ¡ ´ µ 5.6 Eliminating Unneeded Memory References The code for combine3 accumulates the value being computed by the combining operation at the location designated by pointer dest. This attribute can be seen by examining the assembly code generated for the compiled loop, with integers as the data type and multiplication as the combining operation. In this code, register %ecx points to data, %edx contains the value of i, and %edi points to dest. combine3: type=INT, OPER = * dest in %edi, data in %ecx, i in %edx, length in %esi .L18: loop: movl (%edi),%eax Read *dest imull (%ecx,%edx,4),%eax Multiply by data[i] movl %eax,(%edi) Write *dest incl %edx i++ cmpl %esi,%edx Compare i:length jl .L18 If <, goto loop 1 2 3 4 5 6 7 Instruction 2 reads the value stored at dest and instruction 4 writes back to this location. This seems wasteful, since the value read by instruction 1 on the next iteration will normally be the value that has just been written. 5.6. ELIMINATING UNNEEDED MEMORY REFERENCES 219 code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* Accumulate result in local variable */ void combine4(vec_ptr v, data_t *dest) { int i; int length = vec_length(v); data_t *data = get_vec_start(v); data_t x = IDENT; *dest = IDENT; for (i = 0; i < length; i++) { x = x OPER data[i]; } *dest = x; } code/opt/combine.c Figure 5.10: Accumulating Result in Temporary. This eliminates the need to read and write intermediate values on every loop iteration. This leads to the optimization shown as combine4 in Figure 5.10 where we introduce a temporary variable x that is used in the loop to accumulate the computed value. The result is stored at *dest only after the loop has been completed. As the following assembly code for the loop shows, the compiler can now use register %eax to hold the accumulated value. Comparing to the loop for combine3, we have reduced the memory operations per iteration from two reads and one write to just a single read. Registers %ecx and %edx are used as before, but there is no need to reference *dest. combine4: type=INT, OPER = * data in %eax, x in %ecx, i in %edx, length in %esi .L24: loop: imull (%eax,%edx,4),%ecx Multiply x by data[i] incl %edx i++ cmpl %esi,%edx Compare i:length jl .L24 If <, goto loop 1 2 3 4 5 We see a significant improvement in program performance: Function combine3 combine4 Page 217 219 Method Direct data access Accumulate in temporary Integer + * 6.00 9.00 2.00 4.00 Floating Point + * 8.00 117.00 3.00 5.00 The most dramatic decline is in the time for floating-point multiplication. Its time becomes comparable to the times for the other combinations of data type and operation. We will examine the cause for this sudden decrease in Section 5.11.1. 220 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE Again, one might think that a compiler should be able to automatically transform the combine3 code shown in Figure 5.9 to accumulate the value in a register, as it does with the code for combine4 shown in Figure 5.10. In fact, however, the two functions can have different behavior due to memory aliasing. Consider, for example, the case of integer data with multiplication as the operation and 1 as the identity element. Let v be a vector consisting of the three elements ¾ ¿ and consider the following two function calls: combine3(v, get_vec_start(v) + 2); combine4(v, get_vec_start(v) + 2); That is, we create an alias between the last element of the vector and the destination for storing the result. The two functions would then execute as follows: Function combine3 combine4 Initial ¾¿ ¾¿ Before Loop ¾¿½ ¾¿ i=0 ¾¿¾ ¾¿ i=1 ¾¿ ¾¿ i=2 ¾¿¿ ¾¿ Final ¾¿¿ ¾ ¿ ¿¼ As shown above, combine3 accumulates its result at the destination, which in this case is the final vector element. This value is therefore set first to 1, then to ¾ ¡ ½ ¾, and then to ¿ ¡ ¾ . On the final iteration this value is then multiplied by itself to yield a final value of 36. For the case of combine4, the vector remains unchanged until the end, when the final element is set to the computed result ½ ¡ ¾ ¡ ¿ ¡ ¿¼. Of course, our example showing the distinction between combine3 and combine4 is highly contrived. One could argue that the behavior of combine4 more closely matches the intention of the function description. Unfortunately, an optimizing compiler cannot make a judgement about the conditions under which a function might be used and what the programmer’s intentions might be. Instead, when given combine3 to compile, it is obligated to preserve its exact functionality, even if this means generating inefficient code. 5.7 Understanding Modern Processors Up to this point, we have applied optimizations that did not rely on any features of the target machine. They simply reduced the overhead of procedure calls and eliminated some of the critical “optimization blockers” that cause difficulties for optimizing compilers. As we seek to push the performance further, we must begin to consider optimizations that make more use of the means by which processors execute instructions and the capabilities of particular processors. Getting every last bit of performance requires a detailed analysis of the program as well as code generation tuned for the target processor. Nonetheless, we can apply some basic optimizations that will yield an overall performance improvement on a large class of processors. The detailed performance results we report here may not hold for other machines, but the general principles of operation and optimization apply to a wide variety of machines. To understand ways to improve performance, we require a simple operational model of how modern processors work. Due to the large number of transistors that can be integrated onto a single chip, modern microprocessors employ complex hardware that attempts to maximize program performance. One result is that their actual operation is far different from the view that is perceived by looking at assembly-language programs. At the assembly-code level, it appears as if instructions are executed one at a time, where each 5.7. UNDERSTANDING MODERN PROCESSORS 221 Instruction Control Instruction Control Retirement Unit Register File Fetch Control Instruction Decode Address Instructions Instruction Cache Operations Register Updates Prediction OK? Integer/ Branch General Integer FP Add FP Mult/Div Load Store Functional Units Operation Results Addr. Addr. Data Data Data Cache Execution Execution Figure 5.11: Block Diagram of a Modern Processor. The Instruction Control Unit is responsible for reading instructions from memory and generating a sequence of primitive operations. The Execution Unit then performs the operations and indicates whether the branches were correctly predicted. instruction involves fetching values from registers or memory, performing an operation, and storing results back to a register or memory location. In the actual processor, a number of instructions are evaluated simultaneously. In some designs, there can be 80 or more instructions “in flight.” Elaborate mechanisms are employed to make sure the behavior of this parallel execution exactly captures the sequential semantic model required by the machine-level program. 5.7.1 Overall Operation Figure 5.11 shows a very simplified view of a modern microprocessor. Our hypothetical processor design is based loosely on the Intel “P6” microarchitecture [28], the basis for the Intel PentiumPro, Pentium II and Pentium III processors. The newer Pentium 4 has a different microarchitecture, but it has a similar overall structure to the one we present here. The P6 microarchitecture typifies the high-end processors produced by a number of manufacturers since the late 1990s. It is described in the industry as being superscalar, which means it can perform multiple operations on every clock cycle, and out-of-order meaning that the 222 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE order in which instructions execute need not correspond to their ordering in the assembly program. The overall design has two main parts. The Instruction Control Unit (ICU) is responsible for reading a sequence of instructions from memory and generating from these a set of primitive operations to perform on program data. The Execution Unit (EU) then executes these operations. The ICU reads the instructions from an instruction cache—a special, high-speed memory containing the most recently accessed instructions. In general, the ICU fetches well ahead of the currently executing instructions, so that it has enough time to decode these and send operations down to the EU. One problem, however, is that when a program hits a branch,1 there are two possible directions the program might go. The branch can be taken, with control passing to the branch target. Alternatively, the branch can be not taken, with control passing to the next instruction in the instruction sequence. Modern processors employ a technique known as branch prediction, where they guess whether or not a branch will be taken, and they also predict the target address for the branch. Using a technique known as speculative execution, the processor begins fetching and decoding instructions at where it predicts the branch will go, and even begins executing these operations before it has been determined whether or not the branch prediction was correct. If it later determines that the branch was predicted incorrectly, it resets the state to that at the branch point and begins fetching and executing instructions in the other direction. A more exotic technique would be to begin fetching and executing instructions for both possible directions, later discarding the results for the incorrect direction. To date, this approach has not been considered cost effective. The block labeled Fetch Control incorporates branch prediction to perform the task of determining which instructions to fetch. The Instruction Decoding logic takes the actual program instructions and converts them into a set of primitive operations. Each of these operations performs some simple computational task such as adding two numbers, reading data from memory, or writing data to memory. For machines with complex instructions, such as an IA32 processor, an instruction can be decoded into a variable number of operations. The details vary from one processor design to another, but we attempt to describe a typical implementation. In this machine, decoding the instruction addl %eax,%edx yields a single addition operation, whereas decoding the instruction addl %eax,4(%edx) yields three operations: one to load a value from memory into the processor, one to add the loaded value to the value in register %eax, and one to store the result back to memory. This decoding splits instructions to allow a division of labor among a set of dedicated hardware units. These units can then execute the different parts of multiple instructions in parallel. For machines with simple instructions, the operations correspond more closely to the original instructions. The EU receives operations from the instruction fetch unit. Typically, it can receive a number of them on each clock cycle. These operations are dispatched to a set of functional units that perform the actual operations. These functional units are specialized to handle specific types of operations. Our figure illustrates a typical set of functional units. It is styled after those found in recent Intel processors. The units in the figure are as follows: 1 We use the term “branch” specifically to refer to conditional jump instructions. Other instructions that can transfer control to multiple destinations, such as procedure return and indirect jumps, provide similar challenges for the processor. 5.7. UNDERSTANDING MODERN PROCESSORS 223 Integer/Branch: Performs simple integer operations (add, test, compare, logical). Also processes branches, as is discussed below. General Integer: Can handle all integer operations, including multiplication and division. Floating-Point Add: Handles simple floating-point operations (addition, format conversion). Floating-Point Multiplication/Division: Handles floating-point multiplication and division. More complex floating-point instructions, such transcendental functions, are converted into sequences of operations. Load: Handles operations that read data from the memory into the processor. The functional unit has an adder to perform address computations. Store: Handles operations that write data from the processor to the memory. The functional unit has an adder to perform address computations. As shown in the figure, the load and store units access memory via a data cache, a high-speed memory containing the most recently accessed data values. With speculative execution, the operations are evaluated, but the final results are not stored in the program registers or data memory until the processor can be certain that these instructions should actually have been executed. Branch operations are sent to the EU not to determine where the branch should go, but rather to determine whether or not they were predicted correctly. If the prediction was incorrect, the EU will discard the results that have been computed beyond the branch point. It will also signal to the Branch Unit that the prediction was incorrect and indicate the correct branch destination. In this case the Branch Unit begins fetching at the new location. Such a misprediction incurs a significant cost in performance. It takes a while before the new instructions can be fetched, decoded, and sent to the execution units. We explore this further in Section 5.12. Within the ICU, the Retirement Unit keeps track of the ongoing processing and makes sure that it obeys the sequential semantics of the machine-level program. Our figure shows a Register File, containing the integer and floating-point registers, as part of the Retirement Unit, because this unit controls the updating of these registers. As an instruction is decoded, information about it is placed in a first-in, first-out queue. This information remains in the queue until one of two outcomes occurs. First, once the operations for the instruction have completed and any branch points leading to this instruction are confirmed as having been correctly predicted, the instruction can be retired, with any updates to the program registers being made. If some branch point leading to this instruction was mispredicted, on the other hand, the instruction will be flushed, discarding any results that may have been computed. By this means, mispredictions will not alter the program state. As we have described, any updates to the program registers occur only as instructions are being retired, and this takes place only after the processor can be certain that any branches leading to this instruction have been correctly predicted. To expedite the communication of results from one instruction to another, much of this information is exchanged among the execution units, shown in the figure as “Operation Results.” As the arrows in the figure show, the execution units can send results directly to each other. The most common mechanism for controlling the communication of operands among the execution units is called register renaming. When an instruction that updates register Ö is decoded, a tag Ø is generated 224 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE Operation Integer Add Integer Multiply Integer Divide Floating-Point Add Floating-Point Multiply Floating-Point Divide Load (Cache Hit) Store (Cache Hit) Latency 1 4 36 3 5 38 3 3 Issue Time 1 1 36 1 2 38 1 1 Figure 5.12: Performance of Pentium III Arithmetic Operations. Latency represents the total number of cycles for a single operation. Issue time denotes the number of cycles between successive, independent operations. (Obtained from Intel literature). giving a unique identifier to the result of the operation. An entry ´Ö ص is added to a table maintaining the association between each program register and the tag for an operation that will update this register. When a subsequent instruction using register Ö as an operand is decoded, the operation sent to the Execution Unit will contain Ø as the source for the operand value. When some execution unit completes the first operation, it generates a result ´Ú ص indicating that the operation with tag Ø produced value Ú . Any operation waiting for Ø as a source will then use Ú as the source value. By this mechanism, values can be passed directly from one operation to another, rather than being written to and read from the register file. The renaming table only contains entries for registers having pending write operations. When a decoded instruction requires a register Ö , and there is no tag associated with this register, the operand is retrieved directly from the register file. With register renaming, an entire sequence of operations can be performed speculatively, even though the registers are updated only after the processor is certain of the branch outcomes. 5.7.2 Functional Unit Performance Figure 5.12 documents the performance of some of basic operations for an Intel Pentium III. These timings are typical for other processors as well. Each operation is characterized by two cycle counts: the latency, indicating the total number of cycles the functional unit requires to complete the operation; and the issue time, indicating the number of cycles between successive, independent operations. The latencies range from one cycle for basic integer operations; several cycles for loads, stores, integer multiplication, and the more common floating-point operations; and then to many cycles for division and other complex operations. As the third column in Figure 5.12 shows, several functional units of the processor are pipelined, meaning that they can start on a new operation before the previous one is completed. The issue time indicates the number of cycles between successive operations for the unit. In a pipelined unit, the issue time is smaller than the latency. A pipelined function unit is implemented as a series of stages, each of which performs part of the operation. For example, a typical floating-point adder contains three stages: one to process the exponent values, one to add the fractions, and one to round the final result. The operations can proceed through the stages in close succession rather than waiting for one operation to complete before the next begins. This capability can only be exploited if there are successive, logically independent operations to 5.7. UNDERSTANDING MODERN PROCESSORS 225 be performed. As indicated, most of the units can begin a new operation on every clock cycle. The only exceptions are the floating-point multiplier, which requires a minimum of two cycles between successive operations, and the two dividers, which are not pipelined at all. Circuit designers can create functional units with a range of performance characteristics. Creating a unit with short latency or issue time requires more hardware, especially for more complex functions such as multiplication and floating-point operations. Since there is only a limited amount of space for these units on the microprocessor chip, the CPU designers must carefully balance the number of functional units and their individual performance to achieve optimal overall performance. They evaluate many different benchmark programs and dedicate the most resources to the most critical operations. As Figure 5.12 indicates, integer multiplication and floating-point multiplication and addition were considered important operations in design of the Pentium III, even though a significant amount of hardware is required to achieve the low latencies and high degree of pipelining shown. On the other hand, division is relatively infrequent, and difficult to implement with short latency or issue time, and so these operations are relatively slow. 5.7.3 A Closer Look at Processor Operation As a tool for analyzing the performance of a machine level program executing on a modern processor, we have developed a more detailed textual notation to describe the operations generated by the instruction decoder, as well as a graphical notation to show the processing of operations by the functional units. Neither of these notations exactly represents the implementation of a specific, real-life processor. They are simply methods to help understand how a processor can take advantage of parallelism and branch prediction in executing a program. Translating Instructions into Operations We present our notation by working with combine4 (Figure 5.10), our fastest code up to this point as an example. We focus just on the computation performed by the loop, since this is the dominating factor in performance for large vectors. We consider the cases of integer data with both multiplication and addition as the combining operations. The compiled code for this loop with multiplication consists of four instructions. In this code, register %eax holds the pointer data, %edx holds i, %ecx holds x, and %esi holds length. combine4: type=INT, OPER = * data in %eax, x in %ecx, i in %edx, length in %esi .L24: loop: imull (%eax,%edx,4),%ecx Multiply x by data[i] incl %edx i++ cmpl %esi,%edx Compare i:length jl .L24 If <, goto loop 1 2 3 4 5 Every time the processor executes the loop, the instruction decoder translates these four instructions into a sequence of operations for the Execution Unit. On the first iteration, with i equal to 0, our hypothetical machine would issue the following sequence of operations: 226 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE Assembly Instructions .L24: imull (%eax,%edx,4),%ecx incl %edx cmpl %esi,%edx jl .L24 Execution Unit Operations load (%eax, %edx.0, 4) imull t.1, %ecx.0 incl %edx.0 cmpl %esi, %edx.1 jl-taken cc.1 t.1 %ecx.1 %edx.1 cc.1 In our translation, we have converted the memory reference by the multiply instruction into an explicit load instruction that reads the data from memory into the processor. We have also assigned operand labels to the values that change each iteration. These labels are a stylized version of the tags generated by register renaming. Thus, the value in register %ecx is identified by the label %ecx.0 at the beginning of the loop, and by %ecx.1 after it has been updated. The register values that do not change from one iteration to the next would be obtained directly from the register file during decoding. We also introduce the label t.1 to denote the value read by the load operation and passed to the imull operation, and we explicitly show the destination of the operation. Thus, the pair of operations load (%eax, %edx.0, 4) imull t.1, %ecx.0 t.1 %ecx.1 indicates that the processor first performs a load operation, computing the address using the value of %eax (which does not change during the loop), and the value stored in %edx at the start of the loop. This will yield a temporary value, which we label t.1. The multiply operation then takes this value and the value of %ecx at the start of the loop and produces a new value for %ecx. As this example illustrates, tags can be associated with intermediate values that are never written to the register file. The operation incl %edx.0 %edx.1 indicates that the increment operation adds one to the value of %edx at the start of the loop to generate a new value for this register. The operation cmpl %esi, %edx.1 cc.1 indicates that the compare operation (performed by either integer unit) compares the value in %esi (which does not change in the loop) with the newly computed value for %edx. It then sets the condition codes, identified with the explicit label cc.1. As this example illustrates, the processor can use renaming to track changes to the condition code registers. Finally, the jump instruction was predicted taken. The jump operation jl-taken cc.1 5.7. UNDERSTANDING MODERN PROCESSORS %edx.0 227 incl %edx.1 Execution Unit Operations load (%eax, %edx.0, 4) imull t.1, %ecx.0 incl %edx.0 cmpl %esi, %edx.1 jl-taken cc.1 load cmpl jl cc.1 t.1 %ecx.1 %edx.1 cc.1 %ecx.0 t.1 imull %ecx.1 Figure 5.13: Operations for First Iteration of Inner Loop of combine4 for integer multiplication. Memory reads are explicitly converted to loads. Register names are tagged with instance numbers. checks whether the newly computed values for the condition codes (cc.1) indicate this was the correct choice. If not, then it signals the ICU to begin fetching instructions at the instruction following the jl. To simplify the notation, we omit any information about the possible jump destinations. In practice, the processor must keep track of the destination for the unpredicted direction, so that it can begin fetching from there in the event the prediction is incorrect. As this example translation shows, our operations mimic the structure of the assembly-language instructions in many ways, except that they refer to their source and destination operations by labels that identify different instances of the registers. In the actual hardware, register renaming dynamically assigns tags to indicate these different values. Tags are bit patterns rather than symbolic names such as “%edx.1,” but they serve the same purpose. Processing of Operations by the Execution Unit Figure 5.13 shows the operations in two forms: that generated by the instruction decoder and as a computation graph where operations are represented by rounded boxes and arrows indicate the passing of data between operations. We only show the arrows for the operands that change from one iteration to the next, since only these values are passed directly between functional units. The height of each operator box indicates how many cycles the operation requires, that is, the latency of that particular function. In this case, integer multiplication imull requires four cycles, load requires three, and the other operations require one. In demonstrating the timing of a loop, we position the blocks vertically to represent the times when operations are performed, with time increasing in the downward direction. We can see that the five operations for the loop form two parallel chains, indicating two series of computations that must be performed in sequence. The chain on the left processes the data, first reading an array element from memory and then multiplying it times the accumulated product. The chain on the right processes the loop index i, first incrementing it and then comparing it to length. The jump operation checks the result of this comparison to make sure the branch was correctly predicted. Note that there are no outgoing arrows 228 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE %edx.0 Execution Unit Operations load (%eax, %edx.0, 4) addl t.1, %ecx.0 incl %edx.0 cmpl %esi, %edx.1 jl-taken cc.1 load incl %ecx.i +1 cmpl cc.1 %edx.1 t.1 %ecx.1 %edx.1 cc.1 load %ecx.0 t.1 jl addl %ecx.1 Figure 5.14: Operations for First Iteration of Inner Loop of combine4 for Integer Addition. Compared to multiplication, the only change is that the addition operation requires only one cycle. from the jump operation box. If the branch was correctly predicted, no other processing is required. If the branch was incorrectly predicted, then the branch function unit will signal the instruction fetch control unit, and this unit will take corrective action. In either case, the other operations do not depend on the outcome of the jump operation. Figure 5.14 shows the same translation into operations but with integer addition as the combining operation. As the graphical depiction shows, all of the operations, except load, now require just one cycle. Scheduling of Operations with Unlimited Resources To see how a processor would execute a series of iterations, imagine first a processor with an unlimited number of functional units and with perfect branch prediction. Each operation could then begin as soon as its data operands were available. The performance of such a processor would be limited only by the latencies and throughputs of the functional units, and the data dependencies in the program. Figure 5.15 shows the computation graph for the first three iterations of the loop in combine4 with integer multiplication on such a machine. For each iteration, there is a set of five operations with the same configuration as those in Figure 5.13, with appropriate changes to the operand labels. The arrows from the operators of one iteration to those of another show the data dependencies between the different iterations. Each operator is placed vertically at the highest position possible, subject to the constraint that no arrows can point upward, since this would indicate information flowing backward in time. Thus, the load operation of one iteration can begin as soon as the incl operation of the previous iteration has generated an updated value of the loop index. The computation graph shows the parallel execution of operations by the Execution Unit. On each cycle, all of the operations on one horizontal line of the graph execute in parallel. The graph also demonstrates out-of-order, speculative execution. For example, the incl operation in one iteration is executed before the jl instruction of the previous iteration has even begun. We can also see the effect of pipelining. Each iteration requires at least seven cycles from start to end, but successive iterations are completed every 4 cycles. Thus, the effective processing rate is one iteration every 4 cycles, giving a CPE of 4.0. The four-cycle latency of integer multiplication constrains the performance of the processor for this program. Each imull operation must wait until the previous one has completed, since it needs the result of 5.7. UNDERSTANDING MODERN PROCESSORS 229 %edx.0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Cycle imull %ecx.0 incl load t.1 %edx.1 cmpl jl i=0 cc.1 incl load t.2 %edx.2 cmpl jl cc.2 incl load t.3 %edx.3 cmpl jl cc.3 %ecx.1 Iteration 1 imull i=1 %ecx.2 Iteration 2 imull i=2 %ecx.3 Iteration 3 Figure 5.15: Scheduling of Operations for Integer Multiplication with Unlimited Number of Execution Units. The 4 cycle latency of the multiplier is the performance-limiting resource. 230 %edx.0 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE 1 2 3 4 5 6 7 Cycle %ecx.0 incl load t.1 %ecx.i +1 cmpl cc.1 %edx.1 incl load t.2 %ecx.i +1 cmpl cc.2 %edx.2 jl incl load t.3 %ecx.i +1 cmpl cc.3 %edx.3 addl %ecx.1 i=0 jl incl load t.4 %ecx.i +1 cmpl cc.4 %edx.4 Iteration 1 addl %ecx.2 i=1 jl Iteration 2 addl %ecx.3 i=2 jl Iteration 3 addl %ecx.4 i=3 Iteration 4 Figure 5.16: Scheduling of Operations for Integer Addition with Unbounded Resource Constraints. With unbounded resources the processor could achieve a CPE of 1.0. this multiplication before it can begin. In our figure, the multiplication operations begin on cycles 4, 8, and 12. With each succeeding iteration, a new multiplication begins every fourth cycle. Figure 5.16 shows the first four iterations of combine4 for integer addition on a machine with an unbounded number of functional units. With a single-cycle combining operation, the program could achieve a CPE of 1.0. We see that as the iterations progress, the Execution Unit would perform parts of seven operations on each clock cycle. For example, in cycle 4 we can see that the machine is executing the addl for iteration 1; different parts of the load operations for iterations 2, 3, and 4; the jl for iteration 2; the cmpl for iteration 3; and the incl for iteration 4. Scheduling of Operations with Resource Constraints Of course, a real processor has only a fixed set of functional units. Unlike our earlier examples, where the performance was constrained only by the data dependencies and the latencies of the functional units, performance becomes limited by resource constraints as well. In particular, our processor has only two units capable of performing integer and branch operations. In contrast, the graph of Figure 5.15 has three of these operations in parallel on cycles 3 and four in parallel on cycle 4. Figure 5.17 shows the scheduling of the operations for combine4 with integer multiplication on a resourceconstrained processor. We assume that the general integer unit and the branch/integer unit can each begin a new operation on every clock cycle. It is possible to have more than two integer or branch operations executing in parallel, as shown in cycle 6, because the imull operation is in its third cycle by this point. With constrained resources, our processor must have some scheduling policy that determines which operation to perform when it has more than one choice. For example, in cycle 3 of the graph of Figure 5.15, we show three integer operations being executed: the jl of iteration 1, the cmpl of iteration 2, and the incl of iteration 3. For Figure 5.17, we must delay one of these operations. We do so by keeping track of 5.7. UNDERSTANDING MODERN PROCESSORS 231 %edx.0 1 2 %ecx.0 incl load t.1 %edx.1 cmpl jl i=0 cc.1 incl load t.2 %edx.2 3 4 5 6 7 8 9 cmpl jl cc.2 load incl t.3 imull cmpl jl cc.3 incl load t.4 %edx.4 %ecx.1 cmpl jl cc.4 Iteration 1 imull Cycle i=1 %ecx.2 10 11 12 13 14 15 16 17 18 19 Iteration 2 imull i=2 %ecx.3 Iteration 3 imull i=3 %ecx.4 Iteration 4 Figure 5.17: Scheduling of Operations for Integer Multiplication with Actual Resource Constraints. The multiplier latency remains the performance-limiting factor. 232 %edx.3 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE 6 7 8 %ecx.3 9 10 11 12 13 14 15 16 17 18 %ecx.8 %ecx.6 %ecx.4 load t.4 incl %ecx.i +1 cmpl cc.4 %edx.4 incl load t.5 %ecx.i +1 cmpl cc.5 %edx.5 addl jl i=3 Iteration 4 addl %ecx.5 load t.6 incl %edx.6 jl i=4 addl cmpl jl cc.6 cc.6 load t.7 Iteration 5 incl cmpl jl cc.7 %edx.7 i=5 addl Iteration 6 load t.8 incl %ecx.i +1 cmpl cc.8 %edx.8 C ycl e %ecx.7 i=6 addl jl Iteration 7 i=7 Iteration 8 Figure 5.18: Scheduling of Operations for Integer Addition with Actual Resource Constraints. The limitation to two integer units constrains performance to a CPE of 2.0. the program order for the operations, that is, the order in which the operations would be performed if we executed the machine-level program in strict sequence. We then give priority to the operations according to their program order. In this example, we would defer the incl operation, since any operation of iteration 3 is later in program order than those of iterations 1 and 2. Similarly, in cycle 4, we would give priority to the imull operation of iteration 1 and the jl of iteration 2 over that of the incl operation of iteration 3. For this example, the limited number of functional units does not slow down our program. Performance is still constrained by the four-cycle latency of integer multiplication. For the case of integer addition, the resource constraints impose a clear limitation on program performance. Each iteration requires four integer or branch operations, and there are only two functional units for these operations. Thus, we cannot hope to sustain a processing rate any better than two cycles per iteration. In creating the graph for multiple iterations of combine4 for integer addition, an interesting pattern emerges. Figure 5.18 shows the scheduling of operations for iterations 4 through 8. We chose this range of iterations because it shows a regular pattern of operation timings. Observe how the timing of all operations in iterations 4 and 8 is identical, except that the operations in iteration 8 occur eight cycles later. As the iterations proceed, the patterns shown for iterations 4 to 7 would keep repeating. Thus, we complete four iterations every eight 5.8. REDUCING LOOP OVERHEAD cycles, achieving the optimum CPE of 2.0. 233 Summary of combine4 Performance We can now consider the measured performance of combine4 for all four combinations of data type and combining operations: Function combine4 Page 219 Method Accumulate in temporary Integer + * 2.00 4.00 Floating Point + * 3.00 5.00 With the exception of integer addition, these cycle times nearly match the latency for the combining operation, as shown in Figure 5.12. Our transformations to this point have reduced the CPE value to the point where the time for the combining operation becomes the limiting factor. For the case of integer addition, we have seen that the limited number of functional units for branch and integer operations limits the achievable performance. With four such operations per iteration, and just two functional units, we cannot expect the program to go faster than 2 cycles per iteration. In general, processor performance is limited by three types of constraints. First, the data dependencies in the program force some operations to delay until their operands have been computed. Since the functional units have latencies of one or more cycles, this places a lower bound on the number of cycles in which a given sequence of operations can be performed. Second, the resource constraints limit how many operations can be performed at any given time. We have seen that the limited number of functional units is one such resource constraint. Other constraints include the degree of pipelining by the functional units, as well as limitations of other resources in the ICU and the EU. For example, an Intel Pentium III can only decode three instructions on every clock cycle. Finally, the success of the branch prediction logic constrains the degree to which the processor can work far enough ahead in the instruction stream to keep the execution unit busy. Whenever a misprediction occurs, a significant delay occurs getting the processor restarted at the correct location. 5.8 Reducing Loop Overhead The performance of combine4 for integer addition is limited by the fact that each iteration contains four instructions, with only two functional units capable of performing them. Only one of these four instructions operates on the program data. The others are part of the loop overhead of computing the loop index and testing the loop condition. We can reduce overhead effects by performing more data operations in each iteration, via a technique known as loop unrolling. The idea is to access and combine multiple array elements within a single iteration. The resulting program requires fewer iterations, leading to reduced loop overhead. Figure 5.19 shows a version of our combining code using three-way loop unrolling. The first loop steps through the array three elements at a time. That is, the loop index i is incremented by three on each iteration, and the combining operation is applied to array elements , · ½, and · ¾ in a single iteration. 234 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* Unroll loop by 3 */ void combine5(vec_ptr v, data_t *dest) { int length = vec_length(v); int limit = length-2; data_t *data = get_vec_start(v); data_t x = IDENT; int i; /* Combine 3 elements at a time */ for (i = 0; i < limit; i+=3) { x = x OPER data[i] OPER data[i+1] OPER data[i+2]; } /* Finish any remaining elements */ for (; i < length; i++) { x = x OPER data[i]; } *dest = x; } code/opt/combine.c Figure 5.19: Unrolling Loop by 3. Loop unrolling can reduce the effect of loop overhead. 5.8. REDUCING LOOP OVERHEAD Execution Unit Operations load (%eax, %edx.0, 4) addl t.1a, %ecx.0c load 4(%eax, %edx.0, 4) addl t.1b, %ecx.1a load 8(%eax, %edx.0, 4) addl t.1c, %ecx.1b addl %edx.0, 3 cmpl %esi, %edx.1 jl-taken cc.1 %edx.0 235 t.1a %ecx.1a t.1b %ecx.1b t.1c %ecx.1c %edx.1 cc.1 addl load %ecx.0c %ecx.i +1 cmpl cc.1 %edx.1 load addl t.1a t.1b t.1c jl load %ecx.1a addl %ecx.1b addl %ecx.1c Figure 5.20: Operations for First Iteration of Inner Loop of Three-Way Unrolled Integer Addition. With this degree of loop unrolling we can combine three array elements using six integer/branch operations. In general, the vector length will not be a multiple of 3. We want our code to work correctly for arbitrary vector lengths. We account for this requirement in two ways. First, we make sure the first loop does not overrun the array bounds. For a vector of length Ò, we set the loop limit to be Ò ¾. We are then assured that the loop will only be executed when the loop index satisfies Ò ¾, and hence the maximum array index · ¾ will satisfy · ¾ ´Ò ¾µ · ¾ Ò. In general, if the loop is unrolled by , we set the upper limit to be Ò · ½. The maximum loop index · ½ will then be less than Ò. In addition to this, we add a second loop to step through the final few elements of the vector one at a time. The body of this loop will be executed between 0 and 2 times. To better understand the performance of code with loop unrolling, let us look at the assembly code for the inner loop and its translation into operations. Assembly Instructions .L49: addl (%eax,%edx,4),%ecx addl 4(%eax,%edx,4),%ecx addl 8(%eax,%edx,4),%ecx addl %edx,3 cmpl %esi,%edx jl .L49 Execution Unit Operations load (%eax, %edx.0, 4) addl t.1a, %ecx.0c load 4(%eax, %edx.0, 4) addl t.1b, %ecx.1a load 8(%eax, %edx.0, 4) addl t.1c, %ecx.1b addl %edx.0, 3 cmpl %esi, %edx.1 jl-taken cc.1 t.1a %ecx.1a t.1b %ecx.1b t.1c %ecx.1c %edx.1 cc.1 As mentioned earlier, loop unrolling by itself will only help the performance of the code for the case of integer sum, since our other cases are limited by the latency of the functional units. For integer sum, threeway unrolling allows us to combine three elements with six integer/branch operations, as shown in Figure 5.20. With two functional units for these operations, we could potentially achieve a CPE of 1.0. Figure 5.21 236 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE %edx.2 5 6 7 8 9 %ecx.2c 10 11 12 13 14 15 Cycle i=9 i=6 load load addl t.3a t.3b t.3c %ecx.3c t.4a t.4b t.4c %ecx.4c addl %ecx.i +1 cmpl cc.3 %edx.3 jl load addl load %ecx.i +1 cmpl cc.4 %edx.4 %ecx.3a addl %ecx.3b addl load addl load addl %ecx.4b %ecx.4a jl Iteration 3 addl Iteration 4 Figure 5.21: Scheduling of Operations for Three-Way Unrolled Integer Sum with Bounded Resource Constraints. In principle, the procedure can achieve a CPE of 1.0. The measured CPE, however, is 1.33. 5.8. REDUCING LOOP OVERHEAD 237 shows that once we reach iteration 3 (i ), the operations would follow a regular pattern. The operations of iteration 4 (i ) have the same timings, but shifted by three cycles. This would indeed yield a CPE of 1.0. Our measurement for this function shows a CPE of 1.33, that is, we require four cycles per iteration. Evidently some resource constraint we did not account for in our analysis delays the computation by one additional cycle per iteration. Nonetheless, this performance represents an improvement over the code without loop unrolling. Measuring the performance for different degrees of unrolling yields the following values for the CPE Vector Length CPE 1 2.00 Degree of Unrolling 2 3 4 8 1.50 1.33 1.50 1.25 16 1.06 As these measurements show, loop unrolling can reduce the CPE. With the loop unrolled by a factor of two, each iteration of the main loop requires three clock cycles, giving a CPE of ¿ ¾ ½ . As we increase the degree of unrolling, we generally get better performance, nearing the theoretical CPE limit of 1.0. It is interesting to note that the improvement is not monotonic—unrolling by three gives better performance than unrolling by four. Evidently the scheduling of operations on the execution units is less efficient for the latter case. Our CPE measurements do not account for overhead factors such as the cost of the procedure call and of setting up the loop. With loop unrolling, we introduce a new source of overhead—the need to finish any remaining elements when the vector length is not divisible by the degree of unrolling. To investigate the impact of overhead, we measure the net CPE for different vector lengths. The net CPE is computed as the total number of cycles required by the procedure divided by the number of elements. For the different degrees of unrolling, and for two different vector lengths we obtain the following: Vector Length CPE 31 Net CPE 1024 Net CPE 1 2.00 4.02 2.06 Degree of Unrolling 2 3 4 8 1.50 1.33 1.50 1.25 3.57 3.39 3.84 3.91 1.56 1.40 1.56 1.31 16 1.06 3.66 1.12 The distinction between CPE and net CPE is minimal for long vectors, as seen with the measurements for length 1024, but the impact is significant for short vectors, as seen with the measurements for length 31. Our measurements of the net CPE for a vector of length 31 demonstrate one drawback of loop unrolling. Even with no unrolling, the net CPE of 4.02 is considerably higher than the 2.06 measured for long vectors. The overhead of starting and completing the loop becomes far more significant when the loop is executed a smaller number of times. In addition, the benefit of loop unrolling is less significant. Our unrolled code must start and stop two loops, and it must complete the final elements one at a time. The overhead decreases with increased loop unrolling, while the number of operations performed in the final loop increases. With a vector length of 1024, performance generally improves as the degree of unrolling increases. With a vector length of 31, the best performance is achieved by unrolling the loop by only a factor of three. A second drawback of loop unrolling is that it increases the amount of object code generated. The object code for combine4 requires 63 bytes, whereas the object code with the loop unrolled by a factor of 16 238 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE requires 142 bytes. In this case, that seems like a small price to pay for code that runs nearly twice as fast. In other cases, however, the optimum position in this time-space tradeoff is not so clear. 5.9 Converting to Pointer Code Before proceeding further, let us attempt one more transformation that can sometimes improve program performance, at the expense of program readability. One of the unique features of C is the ability to create and reference pointers to arbitrary program objects. Pointer arithmetic, in fact, has a close connection to array referencing. The combination of pointer arithmetic and referencing given by the expression *(a+i) is exactly equivalent to the array reference a[i]. At times, we can improve the performance of a program by using pointers rather than arrays. Figure 5.22 shows an example of converting the procedures combine4 and combine5 to pointer code, giving procedures combine4p and combine5p, respectively. Instead of keeping pointer data fixed at the beginning of the vector, we move it with each iteration. The vector elements are then referenced by a fixed offset (between 0 and 2) of data. Most significantly, we can eliminate the iteration variable i from the procedure. To detect when the loop should terminate, we compute a pointer dend to be an upper bound on pointer data. Comparing the performance of these procedures to their array counterparts yields mixed results: Function combine4 combine4p combine5 combine5p combine5x4 combine5px4 Page 219 239 234 239 Method Accumulate in temporary Pointer version Unroll loop ¢¿ Pointer version Unroll loop ¢ Pointer version Integer + * 2.00 4.00 3.00 4.00 1.33 4.00 1.33 4.00 1.50 4.00 1.25 4.00 Floating Point + * 3.00 5.00 3.00 5.00 3.00 5.00 3.00 5.00 3.00 5.00 3.00 5.00 For most of the cases, the array and pointer versions have the exact same performance. With pointer code, the CPE for integer sum with no unrolling actually gets worse by one cycle. This result is somewhat surprising, since the inner loops for the pointer and array versions are very similar, as shown in Figure 5.23. It is hard to imagine why the pointer code requires an additional clock cycle per iteration. Just as mysteriously, versions of the procedures with four-way loop unrolling yield a one-cycle-per-iteration improvement with pointer code, giving a CPE of 1.25 (five cycles per iteration) rather then 1.5 (six cycles per iteration). In our experience, the relative performance of pointer versus array code depends on the machine, the compiler, and even the particular procedure. We have seen compilers that apply very advanced optimizations to array code but only minimal optimizations to pointer code. For the sake of readability, array code is generally preferable. Practice Problem 5.3: At times, GCC does its own version of converting array code to pointer code. For example, with integer data and addition as the combining operation, it generates the following code for the inner loop of a variant of combine5 that uses eight-way loop unrolling: 5.9. CONVERTING TO POINTER CODE 239 code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 /* Accumulate in local variable, pointer version */ void combine4p(vec_ptr v, data_t *dest) { int length = vec_length(v); data_t *data = get_vec_start(v); data_t *dend = data+length; data_t x = IDENT; for (; data < dend; data++) x = x OPER *data; *dest = x; } code/opt/combine.c (a) Pointer version of combine4. code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /* Unroll loop by 3, pointer version */ void combine5p(vec_ptr v, data_t *dest) { data_t *data = get_vec_start(v); data_t *dend = data+vec_length(v); data_t *dlimit = dend-2; data_t x = IDENT; /* Combine 3 elements at a time */ for (; data < dlimit; data += 3) { x = x OPER data[0] OPER data[1] OPER data[2]; } /* Finish any remaining elements */ for (; data < dend; data++) { x = x OPER data[0]; } *dest = x; } code/opt/combine.c (b) Pointer version of combine5 Figure 5.22: Converting Array Code to Pointer Code. In some cases, this can lead to improved performance. 240 combine4: type=INT, OPER = ’+’ CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE data in %eax, x in %ecx, i in %edx, length in %esi 1 2 3 4 5 .L24: addl (%eax,%edx,4),%ecx incl %edx cmpl %esi,%edx jl .L24 loop: Add data[i] to x i++ Compare i:length If <, goto loop (a) Array code combine4p: type=INT, OPER = ’+’ data in %eax, x in %ecx, dend in %edx 1 2 3 4 5 .L30: addl (%eax),%ecx addl $4,%eax cmpl %edx,%eax jb .L30 loop: Add data[0] to x data++ Compare data:dend If <, goto loop (b) Pointer code Figure 5.23: Pointer Code Performance Anomaly. Although the two programs are very similar in structure, the array code requires two cycles per iteration, while the pointer code requires three. 1 2 3 4 5 6 7 8 9 10 11 12 13 .L6: addl (%eax),%edx addl 4(%eax),%edx addl 8(%eax),%edx addl 12(%eax),%edx addl 16(%eax),%edx addl 20(%eax),%edx addl 24(%eax),%edx addl 28(%eax),%edx addl $32,%eax addl $8,%ecx cmpl %esi,%ecx jl .L6 Observe how register %eax is being incremented by 32 on each iteration. Write C code for a procedure combine5px8 that shows how pointers, loop variables, and termination conditions are being computed by this code. Show the general form with arbitrary data and combining operation in the style of Figure 5.19. Describe how it differs from our handwritten pointer code (Figure 5.22). 5.10. ENHANCING PARALLELISM 241 code/opt/combine.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /* Unroll loop by 2, 2-way parallelism */ void combine6(vec_ptr v, data_t *dest) { int length = vec_length(v); int limit = length-1; data_t *data = get_vec_start(v); data_t x0 = IDENT; data_t x1 = IDENT; int i; /* Combine 2 elements at a time */ for (i = 0; i < limit; i+=2) { x0 = x0 OPER data[i]; x1 = x1 OPER data[i+1]; } /* Finish any remaining elements */ for (; i < length; i++) { x0 = x0 OPER data[i]; } *dest = x0 OPER x1; } code/opt/combine.c Figure 5.24: Unrolling Loop by 2 and Using Two-Way Parallelism. This approach makes use of the pipelining capability of the functional units. 5.10 Enhancing Parallelism At this point, our programs are limited by the latency of the functional units. As the third column in Figure 5.12 shows, however, several functional units of the processor are pipelined, meaning that they can start on a new operation before the previous one is completed. Our code cannot take advantage of this capability, even with loop unrolling, since we are accumulating the value as a single variable x. We cannot compute a new value of x until the preceding computation has completed. As a result, the processor will stall, waiting to begin a new operation until the current one has completed. This limitation shows clearly in Figures 5.15 and 5.17. Even with unbounded processor resources, the multiplier can only produce a new result every four clock cycles. Similar limitations occur with floating-point addition (three cycles) and multiplication (five cycles). 5.10.1 Loop Splitting For a combining operation that is associative and commutative, such as integer addition or multiplication, we can improve performance by splitting the set of combining operations into two or more parts and combining 242 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE %edx.0 addl %edx.1 Execution Unit Operations load (%eax, %edx.0, 4) imull t.1a, %ecx.0 load 4(%eax, %edx.0, 4) imull t.1b, %ebx.0 addl $2, %edx.0 cmpl %esi, %edx.1 jl-taken cc.1 load cmpl load jl cc.1 t.1a %ecx.1 t.1b %ebx.1 %edx.1 cc.1 %ecx.0 %ebx.0 t.1a t.1b imull imull %ecx.1 %ebx.1 Figure 5.25: Operations for First Iteration of Inner Loop of Two-Way Unrolled, Two-Way Parallel Integer Multiplication. The two multiplication operations are logically independent. the results at the end. For example, let ÈÒ denote the product of elements ¼ ½ Ò ½ : È Ò Ò ½ ¼ Assuming Ò is even, we can also write this as ÈÒ È Ò ¢ È ÇÒ , where È Ò is the product of the elements with even indices, and È ÇÒ is the product of the elements with odd indices: È ÈÇ Ò Ò ¾ ¾ ¾ Ò Ò ¾ ¾ ¾ ·½ ¼ ¼ Figure 5.24 shows code that uses this method. It uses both two-way loop unrolling to combine more elements per iteration, and two-way parallelism, accumulating elements with even index in variable x0, and elements with odd index in variable x1. As before, we include a second loop to accumulate any remaining array elements for the case where the vector length is not a multiple of 2. We then apply the combining operation to x0 and x1 to compute the final result. To see how this code yields improved performance, let us consider the translation of the loop into operations for the case of integer multiplication: 5.10. ENHANCING PARALLELISM Assembly Instructions .L151: imull (%eax,%edx,4),%ecx imull 4(%eax,%edx,4),%ebx addl $2,%edx cmpl %esi,%edx jl .L151 Execution Unit Operations load (%eax, %edx.0, 4) imull t.1a, %ecx.0 load 4(%eax, %edx.0, 4) imull t.1b, %ebx.0 addl $2, %edx.0 cmpl %esi, %edx.1 jl-taken cc.1 t.1a %ecx.1 t.1b %ebx.1 %edx.1 cc.1 243 Figure 5.25 shows a graphical representation of these operations for the first iteration (i ¼). As this diagram illustrates, the two multiplications in the loop are independent of each other. One has register %ecx as its source and destination (corresponding to program variable x0), while the other has register %ebx as its source and destination (corresponding to program variable x1). The second multiplication can start just one cycle after the first. This makes use of the pipelining capabilities of both the load unit and the integer multiplier. Figure 5.26 shows a graphical representation of the first three iterations (i ¼, ¾, and ) for integer multiplication. For each iteration, the two multiplications must wait until the results from the previous iteration have been computed. Still, the machine can generate two results every four clock cycles, giving a theoretical CPE of 2.0. In this figure we do not take into account the limited set of integer functional units, but this does not prove to be a limitation for this particular procedure. Comparing loop unrolling alone to loop unrolling with two-way parallelism, we obtain the following performance: Function Page Method Unroll ¢¾ Unroll ¢¾, Parallelism ¢¾ Integer + * 1.50 4.00 1.50 2.00 Floating Point + * 3.00 5.00 2.00 2.50 combine6 241 For integer sum, parallelism does not help, as the latency of integer addition is only one clock cycle. For integer and floating-point product, however, we reduce the CPE by a factor of two. We are essentially doubling the use of the functional units. For floating-point sum, some other resource constraint is limiting our CPE to 2.0, rather than the theoretical value of 1.5. We have seen earlier that two’s complement arithmetic is commutative and associative, even when overflow occurs. Hence for an integer data type, the result computed by combine6 will be identical to that computed by combine5 under all possible conditions. Thus, an optimizing compiler could potentially convert the code shown in combine4 first to a two-way unrolled variant of combine5 by loop unrolling, and then to that of combine6 by introducing parallelism. This is referred to as iteration splitting in the optimizing compiler literature. Many compilers do loop unrolling automatically, but relatively few do iteration splitting. On the other hand, we have seen that floating-point multiplication and addition are not associative. Thus, combine5 and combine6 could potentially produce different results due to rounding or overflow. Imagine, for example, a case where all the elements with even indices were numbers with very large absolute value, while those with odd indices were very close to 0.0. Then product È Ò might overflow, or È ÇÒ might underflow, even though the final product ÈÒ does not. In most real-life applications, however, such 244 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE %edx.0 1 2 3 %ecx.0 4 %ebx.0 5 6 7 8 9 10 11 12 13 14 15 16 Cycle i=0 Iteration 1 imull imull load load t.1a t.1b addl cmpl jl cc.1 %edx.1 addl load load cmpl jl cc.2 %edx.2 addl load load cmpl jl cc.3 %edx.3 %ecx.1 %ebx.1 t.2a t.2b imull imull %ecx.2 t.3a t.3b i=2 Iteration 2 %ebx.2 imull imull %ecx.3 i=4 Iteration 3 %ebx.3 Figure 5.26: Scheduling of Operations for Two-Way Unrolled, Two-Way Parallel Integer Multiplication with Unlimited Resources. The multiplier can now generate two values every 4 cycles. 5.10. ENHANCING PARALLELISM 245 patterns are unlikely. Since most physical phenomena are continous, numerical data tend to be reasonably smooth and well-behaved. Even when there are discontinuities, they do not generally cause periodic patterns that lead to a condition such as that sketched above. It is unlikely that summing the elements in strict order gives fundamentally better accuracy than does summing two groups independently and then adding those sums together. For most applications, achieving a performance gain of 2X outweighs the risk of generating different results for strange data patterns. Nevertheless, a program developer should check with potential users to see if there are particular conditions that may cause the revised algorithm to be unacceptable. Just as we can unroll loops by an arbitrary factor , we can also increase the parallelism to any factor Ô such that is divisible by Ô. The following are some results for different degrees of unrolling and parallelism: Method Unroll ¢¾ Unroll ¢¾, Parallelism ¢¾ Unroll ¢ Unroll ¢ , Parallelism ¢¾ Unroll ¢ Unroll ¢ , Parallelism ¢¾ Unroll ¢ , Parallelism ¢ Unroll ¢ , Parallelism ¢ Unroll ¢ , Parallelism ¢¿ Integer + * 1.50 4.00 1.50 2.00 1.50 4.00 1.50 2.00 1.25 4.00 1.25 2.00 1.25 1.25 1.75 1.87 1.22 1.33 Floating Point + * 3.00 5.00 2.00 2.50 3.00 5.00 1.50 2.50 3.00 5.00 1.50 2.50 1.61 2.00 1.87 2.07 1.66 2.00 As this table shows, increasing the degree of loop unrolling and the degree of parallelism helps program performance up to some point, but it yields diminishing improvement or even worse performance when taken to an extreme. In the next section, we will describe two reasons for this phenomenon. 5.10.2 Register Spilling The benefits of loop parallelism are limited by the ability to express the computation in assembly code. In particular, the IA32 instruction set only has a small number of registers to hold the values being accumulated. If we have a degree of parallelism Ô that exceeds the number of available registers, then the compiler will resort to spilling, storing some of the temporary values on the stack. Once this happens, the performance drops dramatically. This occurs for our benchmarks when we attempt to have Ô . Our measurements show the performance for this case is worse than that for Ô . For the case of the integer data type, there are only eight total integer registers available. Two of these (%ebp and %esp) point to regions of the stack. With the pointer version of the code, one of the remaining six holds the pointer data, and one holds the stopping position dend. This leaves only four integer registers for accumulating values. With the array version of the code, we require three registers to hold the loop index i, the stopping index limit, and the array address data. This leaves only three registers for accumulating values. For the floating-point data type, we need two of eight registers to hold intermediate values, leaving six for accumulating values. Thus, we could have a maximum parallelism of six before register spilling occurs. This limitation to eight integer and eight floating-point registers is an unfortunate artifact of the IA32 instruc- 246 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE tion set. The renaming scheme described previously eliminates the direct correspondence between register names and the actual location of the register data. In a modern processor, register names serve simply to identify the program values being passed between the functional units. IA32 provides only a small number of such identifiers, constraining the amount of parallelism that can be expressed in programs. The occurrence of spilling can be seen by examining the assembly code. For example, within the first loop for the code with eight-way parallelism we see the following instruction sequence: type=INT, OPER = ’*’ x6 in -12(%ebp), data+i in %eax 1 2 3 movl -12(%ebp),%edi imull 24(%eax),%edi movl %edi,-12(%ebp) Get x6 from stack Multiply by data[i+6] Put x6 back In this code, a stack location is being used to hold x6, one of the eight local variables used to accumulate sums. The code loads it into a register, multiplies it by one of the data elements, and stores it back to the same stack location. As a general rule, any time a compiled program shows evidence of register spilling within some heavily used inner loop, it might be preferable to rewrite the code so that fewer temporary values are required. These include explicitly declared local variables as well as intermediate results being saved to avoid recomputation. Practice Problem 5.4: The following shows the code generated from a variant of combine6 that uses eight-way loop unrolling and four-way parallelism. 1 2 3 4 5 6 7 8 9 10 11 12 13 .L152: addl (%eax),%ecx addl 4(%eax),%esi addl 8(%eax),%edi addl 12(%eax),%ebx addl 16(%eax),%ecx addl 20(%eax),%esi addl 24(%eax),%edi addl 28(%eax),%ebx addl $32,%eax addl $8,%edx cmpl -8(%ebp),%edx jl .L152 A. What program variable has being spilled onto the stack? B. At what location on the stack? C. Why is this a good choice of which value to spill? With floating-point data, we want to keep all of the local variables in the floating-point register stack. We also need to keep the top of stack available for loading data from memory. This limits us to a degree of parallelism less than or equal to 7. 5.11. PUTTING IT TOGETHER: SUMMARY OF RESULTS FOR OPTIMIZING COMBINING CODE247 Function combine1 combine1 combine2 combine3 combine4 combine5 combine6 Page 211 211 212 217 219 234 241 Method Abstract unoptimized Abstract -O2 Move vec length Direct data access Accumulate in temporary Unroll ¢ Unroll ¢½ Unroll ¢¾, Parallelism ¢¾ Unroll ¢ , Parallelism ¢¾ Unroll ¢ , Parallelism ¢ Integer + * 42.06 41.86 31.25 33.25 20.66 21.25 6.00 9.00 2.00 4.00 1.50 4.00 1.06 4.00 1.50 2.00 1.50 2.00 1.25 1.25 39.7 33.5 Floating Point + * 41.44 160.00 31.25 143.00 21.15 135.00 8.00 117.00 3.00 5.00 3.00 5.00 3.00 5.00 2.00 2.50 1.50 2.50 1.50 2.00 27.6 80.0 Worst:Best Figure 5.27: Comparative Result for All Combining Routines. The best performing version is shown in bold face. 5.10.3 Limits to Parallelism For our benchmarks, the main performance limitations are due to the capabilities of the functional units. As Figure 5.12 shows, the integer multiplier and the floating-point adder can only initiate a new operation every clock cycle. This, plus a similar limitation on the load unit limits these cases to a CPE of 1.0. The floating-point multiplier can only initiate a new operation every two clock cycles. This limits this case to a CPE of 2.0. Integer sum is limited to a CPE of 1.0, due to the limitations of the load unit. This leads to the following comparison between the achieved performance versus the theoretical limits: Method Achieved Theoretical Limit Integer + * 1.06 1.25 1.00 1.00 Floating Point + * 1.50 2.00 1.00 2.00 In this table, we have chosen the combination of unrolling and parallelism that achieves the best performance for each case. We have been able to get close to the theoretical limit for integer sum and product and for floating-point product. Some machine-dependent factor limits the achieved CPE for floating-point multiplication to 1.50 rather than the theoretical limit of 1.0. 5.11 Putting it Together: Summary of Results for Optimizing Combining Code We have now considered six versions of the combining code, some of which had multiple variants. Let us pause to take a look at the overall effect of this effort, and how our code would do on a different machine. Figure 5.27 shows the measured performance for all of our routines plus several other variants. As can 248 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE be seen, we achieve maximum performance for the integer sum by simply unrolling the loop many times, whereas we achieve maximum performance for the other operations by introducing some, but not too much, parallelism. The overall performance gain of 27.6X and better from our original code is quite impressive. 5.11.1 Floating-Point Performance Anomaly One of the most striking features of Figure 5.27 is the dramatic drop in the cycle time for floating-point multiplication when we go from combine3, where the product is accumulated in memory, to combine4 where the product is accumulated in a floating-point register. By making this small change, the code suddenly runs 23.4 times faster. When an unexpected result such as this one arises, it is important to hypothesize what could cause this behavior and then devise a series of tests to evaluate this hypothesis. Examining the table, it appears that something strange is happening for the case of floating-point multiplication when we accumulate the results in memory. The performance is far worse than for floating-point addition or integer multiplication, even though the number of cycles for the functional units are comparable. On an IA32 processor, all floating-point operations are performed in extended 80-bit) precision, and the floating-point registers store values in this format. Only when the value in a register is written to memory is it converted to 32-bit (float) or 64-bit (double) format. Examining the data used for our measurements, the source of the problem becomes clear. The measurements were performed on a vector of length 1024 having element equal to · ½. Hence, we are attempting to compute ½¼¾ , which is approximately ¢ ½¼¾ ¿ . Such a large number can be represented in the extended-precision floating-point format (it can represent numbers up to around ½¼ ¿¾ ), but it far exceeds what can be represented as a single precision (up to around ½¼¿ ) or double precision (up to around ½¼¿¼ ). The single precision case overflows when we reach ¿ , while the double precision case overflows when we reach ½ ½. Once we reach this point, every execution of the statement *dest = *dest OPER val; in the inner loop of combine3 requires reading the value ·½, from dest, multiplying this by val to get ·½ and then storing this back at dest. Evidently, some part of this computation requires much longer than the normal five clock cycles required by floating-point multiplication. In fact, running measurements on this operation we find it takes between 110 and 120 cycles to multiply a number by infinity. Most likely, the hardware detected this as a special case and issued a trap that caused a software routine to perform the actual computation. The CPU designers felt such an occurrence would be sufficiently rare that they did not need to deal with it as part of the hardware design. Similar behavior could happen with underflow. When we run the benchmarks on data for which every vector element equals ½ ¼, combine3 achieves a CPE of 10.00 cycles for both double and single precision. This is much more in line with the times measured for the other data types and operations, and comparable to the time for combine4. This example illustrates one of the challenges of evaluating program performance. Measurements can be strongly affected by characteristics of the data and operating conditions that initially seem insignificant. 5.12. BRANCH PREDICTION AND MISPREDICTION PENALTIES Function combine1 combine1 combine2 combine3 combine4 combine5 combine6 Page 211 211 212 217 219 234 241 Method Abstract unoptimized Abstract -O2 Move vec length Direct data access Accumulate in temporary Unroll ¢ Unroll ¢½ Unroll ¢ , Parallelism ¢¾ Unroll ¢ , Parallelism ¢ Unroll ¢ , Parallelism ¢ Integer + * 40.14 47.14 25.08 36.05 19.19 32.18 6.26 12.52 1.76 9.01 1.51 9.01 1.25 9.01 1.19 4.69 1.15 4.12 1.11 4.24 36.2 11.4 Floating Point + * 52.07 53.71 37.37 32.02 28.73 32.73 13.26 13.01 8.01 8.01 6.32 6.32 6.33 6.22 4.44 4.45 2.34 2.01 2.36 2.08 22.3 26.7 249 Worst:Best Figure 5.28: Comparative Result for All Combining Routines Running on a Compaq Alpha 21164 Processor. The same general optimization techniques are useful on this machine as well. 5.11.2 Changing Platforms Although we presented our optimization strategies in the context of a specific machine and compiler, the general principles also apply to other machine and compiler combinations. Of course, the optimal strategy may be very machine dependent. As an example, Figure 5.28 shows performance results for a Compaq Alpha 21164 processor for conditions comparable to those for a Pentium III shown in Figure 5.27. These measurements were taken for code generated by the Compaq C compiler, which applies more advanced optimizations than GCC. Observe how the cycle times generally decline as we move down the table, just as they did for the other machine. We see that we can effectively exploit a higher (eight-way) degree of parallelism, because the Alpha has 32 integer and 32 floating-point registers. As this example illustrates, the general principles of program optimization apply to a variety of different machines, even if the particular combination of features leading to optimum performance depend on the specific machine. 5.12 Branch Prediction and Misprediction Penalties As we have mentioned, modern processors work well ahead of the currently executing instructions, reading new instructions from memory, and decoding them to determine what operations to perform on what operands. This instruction pipelining works well as long as the instructions follow in a simple sequence. When a branch is encountered, however, the processor must guess which way the branch will go. For the case of a conditional jump, this means predicting whether or not the branch will be taken. For an instruction such as an indirect jump (as we saw in the code to jump to an address specified by a jump table entry) or a procedure return, this means predicting the target address. In this discussion, we focus on conditional branches. In a processor that employs speculative execution, the processor begins executing the instructions at the predicted branch target. It does this in a way that avoids modifying any actual register or memory locations 250 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE 1 2 3 4 5 6 7 8 9 10 11 code/opt/absval.c 1 2 3 4 int absval(int val) { return (val<0) ? -val : val; } code/opt/absval.c absval: pushl %ebp movl %esp,%ebp movl 8(%ebp),%eax testl %eax,%eax jge .L3 negl %eax .L3: movl %ebp,%esp popl %ebp ret Get val Test it If >0, goto end Else, negate it end: (a) C code. (b) Assembly code. Figure 5.29: Absolute Value Code We use this to measure the cost of branch misprediction. until the actual outcome has been determined. If the prediction is correct, the processor simply “commits” the results of the speculatively executed instructions by storing them in registers or memory. If the prediction is incorrect, the processor must discard all of the speculatively executed results, and restart the instruction fetch process at the correct location. A significant branch penalty is incurred in doing this, because the instruction pipeline must be refilled before useful results are generated. Once upon a time, the technology required to support speculative execution was considered too costly and exotic for all but the most advanced supercomputers. Since around 1998, integrated circuit technology has made it possible to put so much circuitry on one chip that some can be dedicated to supporting branch prediction and speculative execution. At this point, almost every processor in a desktop or server machine supports speculative execution. In optimizing our combining procedure, we did not observe any performance limitation imposed by the loop structure. That is, it appeared that the only limiting factor to performance was due to the functional units. For this procedure, the processor was generally able to predict the direction of the branch at the end of the loop. In fact, if it predicted the branch will always be taken, the processor would be correct on all but the final iteration. Many schemes have been devised for predicting branches, and many studies have been made on their performance. A common heuristic is to predict that any branch to a lower address will be taken, while any branch to a higher address will not be taken. Branches to lower addresses are used to close loops, and since loops are usually executed many times, predicting these branches as being taken is generally a good idea. Forward branches, on the other hand, are used for conditional computation. Experiments have shown that the backward-taken, forward-not-taken heuristic is correct around 65% of the time. Predicting all branches as being taken, on the other other hand, has a success rate of only around 60%. Far more sophisticated strategies have been devised, requiring greater amounts of hardware. For example, the Intel Pentium II and III processors use a branch prediction strategy that is claimed to be correct between 90% and 95% of the time [29]. We can run experiments to test the branch predication capability of a processor and the cost of a misprediction. We use the absolute value routine shown in Figure 5.29 as our test case. This figure also shows the compiled form. For nonnegative arguments, the branch will be taken to skip over the negation instruction. 5.12. BRANCH PREDICTION AND MISPREDICTION PENALTIES 251 We time this function computing the absolute value of every element in an array, with the array consisting of various patterns of of ·½s and ½s. For regular patterns (e.g., all ·½s, all ½s, or alternating ·½ and ½s), we find the function requires between 13.01 and 13.41 cycles. We use this as our estimate of the performance with perfect branch condition. On an array set to random patterns of ·½s and ½s, we find that the function requires 20.32 cycles. One principle of random processes is that no matter what strategy one uses to guess a sequence of values, if the underlying process is truly random, then we will be right only 50% of the time. For example, no matter what strategy one uses to guess the outcome of a coin toss, as long as the coin toss is fair, our probability of success is only 0.5. Thus, we can see that a mispredicted branch with this processor incurs a penalty of around 14 clock cycles, since a misprediction rate of 50% causes the function to run an average of 7 cycles slower. This means that calls to absval require between 13 and 27 cycles depending on the success of the branch predictor. This penalty of 14 cycles is quite large. For example, if our prediction accuracy were only 65%, then the processor would waste, on average, ½ ¢ ¼ ¿ cycles for every branch instruction. Even with the 90 to 95% prediction accuracy claimed for the Pentium II and III, around one cycle is wasted for every branch due to mispredictions. Studies of actual programs show that branches constitute around 14 to 16% of all executed instructions in typical “integer” programs (i.e., those that do not process numeric data), and around 3 to 12% of all executed instructions in typical numeric programs[31, Sect. 3.5]. Thus, any wasted time due to inefficient branch handling can have a significant effect on processor performance. Many data dependent branches are not at all predictable. For example, there is no basis for guessing whether an argument to our absolute value routine will be positive or negative. To improve performance on code involving conditional evaluation, many processor designs have been extended to include conditional move instructions. These instructions allow some forms of conditionals to be implemented without any branch instructions. With the IA32 instruction set, a number of different cmov instructions were added starting with the PentiumPro. These are supported by all recent Intel and Intel-compatible processors. These instructions perform an operation similar to the C code: if (COND) x = y; where y is the source operand and x is the destination operand. The condition COND determining whether the copy operation takes place is based on some combination of condition code values, similar to the test and conditional jump instructions. As an example, the cmovll instruction performs a copy when the condition codes indicate a value less than zero. Note that the first ‘l’ of this instruction indicates “less,” while the second is the GAS suffix for long word. The following assembly code shows how to implement absolute value with conditional move. 1 2 3 4 5 movl 8(%ebp),%eax movl %eax,%edx negl %edx testl %eax,%eax Conditionally move %edx to %eax Get val as result Copy to %edx Negate %edx Test val If < 0, copy %edx to result cmovll %edx,%eax 252 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE As this code shows, the strategy is to set val as a return value, compute -val, and conditionally move it to register %eax to change the return value when val is negative. Our measurements of this code shows that it runs for 13.7 cycles regardless of the data patterns. This clearly yields better overall performance than a procedure that requires between 13 and 27 cycles. Practice Problem 5.5: A friend of yours has written an optimizing compiler that makes use of conditional move instructions. You try compiling the following C code: 1 2 3 4 5 /* Dereference pointer or return 0 if null */ int deref(int *xp) { return xp ? *xp : 0; } The compiler generates the following code for the body of the procedure. 1 2 3 4 movl 8(%ebp),%edx movl (%edx),%eax testl %edx,%edx cmovll %edx,%eax Get xp Get *xp as result Test xp If 0, copy 0 to result Explain why this code does not provide a valid implementation of deref The current version of GCC does not generate any code using conditional moves. Due to a desire to remain compatible with earlier 486 and Pentium processors, the compiler does not take advantage of these new features. In our experiments, we used the handwritten assembly code shown above. A version using GCC’s facility to embed assembly code within a C program (Section 3.15) required 17.1 cycles due to poorer quality code generation. Unfortunately, there is not much a C programmer can do to improve the branch performance of a program, except to recognize that data-dependent branches incur a high cost in terms of performance. Beyond this, the programmer has little control over the detailed branch structure generated by the compiler, and it is hard to make branches more predictable. Ultimately, we must rely on a combination of good code generation by the compiler to minimize the use of conditional branches, and effective branch prediction by the processor to reduce the number of branch mispredictions. 5.13 Understanding Memory Performance All of the code we have written, and all the tests we have run, require relatively small amounts of memory. For example, the combining routines were measured over vectors of length 1024, requiring no more than 8,096 bytes of data. All modern processors contain one or more cache memories to provide fast access to such small amounts of memory. All of the timings in Figure 5.12 assume that the data being read or written 5.13. UNDERSTANDING MEMORY PERFORMANCE 253 code/opt/list.c 1 2 3 4 5 6 7 8 9 10 11 12 13 typedef struct ELE { struct ELE *next; int data; } list_ele, *list_ptr; static int list_len(list_ptr ls) { int len = 0; for (; ls; ls = ls->next) len++; return len; } code/opt/list.c Figure 5.30: Linked List Functions. These illustrate the latency of the load operation. is contained in cache. In Chapter 6, we go into much more detail about how caches work and how to write code that makes best use of the cache. In this section, we will further investigate the performance of load and store operations while maintaining the assumption that the data being read or written are held in cache. As Figure 5.12 shows, both of these units have a latency of 3, and an issue time of 1. All of our programs so far have used only load operations, and they have had the property that the address of one load depended on incrementing some register, rather than as the result of another load. Thus, as shown in Figures 5.15 to 5.18, 5.21 and 5.26, the load operations could take advantage of pipelining to initiate new load operations on every cycle. The relatively long latency of the load operation has not had any adverse affect on program performance. 5.13.1 Load Latency As an example of code whose performance is constrained by the latency of the load operation, consider the function list_len, shown in Figure 5.30. This function computes the length of a linked list. In the loop of this function, each successive value of variable ls depends on the value read by the pointer reference ls->next. Our measurements show that function list_len has a CPE of 3.00, which we claim is a direct reflection of the latency of the load operation. To see this, consider the assembly code for the loop, and the translation of its first iteration into operations: Assembly Instructions .L27: incl %eax movl (%edx),%edx testl %edx,%edx jne .L27 Execution Unit Operations incl %eax.0 load (%edx.0) testl %edx.1,%edx.1 jne-taken cc.1 %eax.1 %edx.1 cc.1 254 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE %eax.0 %edx.0 1 2 3 4 5 6 7 8 9 10 11 Cycle testl jne cc.1 incl load %eax.1 incl %eax.2 incl %edx.1 %eax.3 i=0 load Iteration 1 testl jne cc.2 %edx.2 i=1 load Iteration 2 testl jne cc.3 %edx.3 i=2 Iteration 3 Figure 5.31: Scheduling of Operations for List Length Function. The latency of the load operation limits the CPE to a minimum of 3.0. 5.13. UNDERSTANDING MEMORY PERFORMANCE 255 code/opt/copy.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 /* Set element of array to 0 */ static void array_clear(int *src, int *dest, int n) { int i; for (i = 0; i < n; i++) dest[i] = 0; } /* Set elements of array to 0, unrolling by 8 */ static void array_clear_8(int *src, int *dest, int n) { int i; int len = n - 7; for (i = 0; i dest[i] = dest[i+1] dest[i+2] dest[i+3] dest[i+4] dest[i+5] dest[i+6] dest[i+7] } for (; i < n; dest[i] = } code/opt/copy.c < len; i+=8) { 0; = 0; = 0; = 0; = 0; = 0; = 0; = 0; i++) 0; Figure 5.32: Functions to Clear Array. These illustrate the pipelining of the store operation. Each successive value of register %edx depends on the result of a load operation having %edx as an operand. Figure 5.31 shows the scheduling of operations for the first three iterations of this function. As can be seen, the latency of the load operation limits the CPE to 3.0. 5.13.2 Store Latency In all of our examples so far, we have interacted with the memory only by using the load operation to read from a memory location into a register. Its counterpart, the store operation, writes a register value to memory. As Figure 5.12 indicates, this operation also has a nominal latency of three cycles, and an issue time of one cycle. However, its behavior, and its interactions with load operations, involve several subtle issues. As with the load operation, in most cases the store operation can operate in a fully pipelined mode, beginning 256 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE code/opt/copy.c 1 2 3 4 5 6 7 8 9 10 11 /* Write to static void { int cnt int val dest, read from src */ write_read(int *src, int *dest, int n) = n; = 0; while (cnt--) { *dest = val; val = (*src)+1; } } code/opt/copy.c Example A: write_read(&a[0],&a[1],3) Initial cnt a val –10 3 17 0 Iter. 1 2 –10 0 –9 Iter. 2 1 –10 –9 –9 Iter. 3 0 –10 –9 –9 Example B: write_read(&a[0],&a[0],3) Initial cnt a val –10 3 17 0 Iter. 1 2 0 17 1 Iter. 2 1 1 17 2 Iter. 3 0 2 17 3 Figure 5.33: Code to Write and Read Memory Locations, Along with Illustrative Executions. This function highlights the interactions between stores and loads when arguments src and dest are equal. a new store on every cycle. For example, consider the functions shown in Figure 5.32 that set the elements of an array dest of length n to zero. Our measurements for the first version show a CPE of 2.00. Since each iteration requires a store operation, it is clear that the processor can begin a new store operation at least once every two cycles. To probe further, we try unrolling the loop eight times, as shown in the code for array_clear_8. For this one we measure a CPE of 1.25. That is, each iteration requires around ten cycles and issues eight store operations. Thus, we have nearly achieved the optimum limit of one new store operation per cycle. Unlike the other operations we have considered so far, the store operation does not affect any register values. Thus, by their very nature a series of store operations must be independent from each other. In fact, only a load operation is affected by the result of a store operation, since only a load can read back the memory location that has been written by the store. The function write_read shown in Figure 5.33 illustrates the potential interactions between loads and stores. This figure also shows two example executions of this 5.13. UNDERSTANDING MEMORY PERFORMANCE 257 Load Unit Address Data Address Data Store Unit Store Buffer Address Data Matching Addresses Address Data Data Cache Figure 5.34: Detail of Load and Store Units. The store unit maintains a buffer of pending writes. The load unit must check its address with those in the store unit to detect a write/read dependency. function, when it is called for a two-element array a, with initial contents ½¼ and ½ , and with argument cnt equal to 3. These executions illustrate some subtleties of the load and store operations. In example A of Figure 5.33, argument src is a pointer to array element a[0], while dest is a pointer to array element a[1]. In this case, each load by the pointer reference *src will yield the value ½¼. Hence, after two iterations, the array elements will remain fixed at ½¼ and , respectively. The result of the read from src is not affected by the write to dest. Measuring this example, but over a larger number of iterations, gives a CPE of 2.00. In example B of Figure 5.33(a), both arguments src and dest are pointers to array element a[0]. In this case, each load by the pointer reference *src will yield the value stored by the previous execution of the pointer reference *dest. As a consequence, a series of ascending values will be stored in this location. In general, if function write_read is called with arguments src and dest pointing to the same memory location, and with argument cnt having some value Ò ¼, the net effect is to set the location to Ò ½. This example illustrates a phenomenon we will call write/read dependency—the outcome of a memory read depends on a very recent memory write. Our performance measurements show that example B has a CPE of 6.00. The write/read dependency causes a slowdown in the processing. To see how the processor can distinguish between these two cases and why one runs slower than another, we must take a more detailed look at the load and store execution units, as shown in Figure 5.34. The store unit contains a store buffer containing the addresses and data of the store operations that have been issued to the store unit, but have not yet been completed, where completion involves updating the data cache. This buffer is provided so that a series of store operations can be executed without having to wait for each one to update the cache. When a load operation occurs, it must check the entries in the store buffer for matching addresses. If it finds a match, it retrieves the corresponding data entry as the result of the load operation. The assembly code for the inner loop, and its translation into operations during the first iteration, is as follows: 258 %eax.0 %edx.0 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE 1 2 3 4 5 6 7 ≠ store data store addr load %edx.1a %edx.1b cc.1 decl jnc %eax.1 ≠ store addr load %edx.2a decl cc.2 %eax.2 jnc incl Iteration 1 Cycle store data incl %edx.2b Iteration 2 Figure 5.35: Timing of write read for Example A. The store and load operations have different addresses, and so the load can proceed without waiting for the store. Assembly Instructions .L32: movl %edx,(%ecx) movl (%ebx),%edx incl %edx decl %eax jnc .L32 Execution Unit Operations storeaddr (%ecx) storedata %edx.0 load (%ebx) incl %edx.1a decl $eax.0 jnc-taken cc.1 %edx.1a %edx.1b %eax.1 Observe that the instruction movl %edx,(%ecx) is translated into two operations: the storeaddr instruction computes the address for the store operation, creates an entry in the store buffer, and sets the address field for that entry. The storedata instruction sets the data field for the entry. Since there is only one store unit, and store operations are processed in program order, there is no ambiguity about how the two operations match up. As we will see, the fact that these two computations are performed independently can be important to program performance. Figure 5.35 shows the timing of the operations for the first two iterations of write_read for the case of example A. As indicated by the dotted line between the storeaddr and load operations, the storeaddr operation creates an entry in the store buffer, which is then checked by the load. Since these are unequal, the load proceeds to read the data from the cache. Even though the store operation has not been completed, the processor can detect that it will affect a different memory location than the load is trying to read. This process is repeated on the second iteration as well. Here we can see that the storedata operation must wait until the result from the previous iteration has been loaded and incremented. Long before this, the storeaddr operation and the load operations can match up their adddresses, determine they are different, and allow the load to proceed. In our computation graph, we show the load for the second iteration beginning just one cycle after the load from the first. If continued for more iterations, we would find the 5.13. UNDERSTANDING MEMORY PERFORMANCE %eax.0 %edx.0 259 1 2 3 4 5 6 7 8 9 = store data store addr load cc.1 decl jnc %eax.1 = store addr decl cc.2 %eax.2 jnc %edx.1a %edx.1b incl load store data Iteration 1 10 11 12 Cycle %edx.2a incl %edx.2b Iteration 2 Figure 5.36: Timing of write read for Example B. The store and load operations have the same address, and hence the load must wait until it can get the result from the store. graph indicates a CPE of 1.0. Evidentally, some other resource constraint limits the actual performance to a CPE of 2.0. Figure 5.36 shows the timing of the operations for the first two iterations of write_read for the case of example B. Again, the dotted line between the storeaddr and load operations indicates that the the storeaddr operation creates an entry in the store buffer which is then checked by the load. Since these are equal, the load must wait until the storedata operation has completed, and then it gets the data from the store buffer. This waiting is indicated in the graph by a much more elongated box for the load operation. In addition, we show a dashed arrow from the storedata to the load operations to indicate that the result of the storedata is passed to the load as its result. Our timings of these operations are drawn to reflect the measured CPE of 6.0. Exactly how this timing arises is not totally clear, however, and so these figures are intended to be more illustrative than factual. In general, the processor/memory interface is one of the most complex portions of a processor design. Without access to detailed documentation and machine analysis tools, we can only give a hypothetical description of the actual behavior. As these two examples show, the implementation of memory operations involves many subtleties. With operations on registers, the processor can determine which instructions will affect which others as they are being decoded into operations. With memory operations, on the other hand, the processor cannot predict which will affect which others until the load and store addresses have been computed. Since memory 260 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE operations make up a significant fraction of the program, the memory subsystem is optimized to run with greater parallelism for independent memory operations. Practice Problem 5.6: As another example of code with potential load-store interactions, consider the following function to copy the contents of one array to another: 1 2 3 4 5 6 7 static void copy_array(int *src, int *dest, int n) { int i; for (i = 0; i < n; i++) dest[i] = src[i]; } Suppose a is an array of length 1000 initialized so that each element a[ ] equals . A. What would be the effect of the call copy_array(a+1,a,999)? B. What would be the effect of the call copy_array(a,a+1,999)? C. Our performance measurements indicate that the call of part A has a CPE of 3.00, while the call of part B has a CPE of 5.00. To what factor do you attribute this performance difference? D. What performance would you expect for the call copy_array(a,a,999)? 5.14 Life in the Real World: Performance Improvement Techniques Although we have only considered a limited set of applications, we can draw important lessons on how to write efficient code. We have described a number of basic strategies for optimizing program performance: 1. High-level design. Choose appropriate algorithms and data structures for the problem at hand. Be especially vigilant to avoid algorithms or coding techniques that yield asymptotically poor performance. 2. Basic coding principles. Avoid optimization blockers so that a compiler can generate efficient code. (a) Eliminate excessive function calls. Move computations out of loops when possible. Consider selective compromises of program modularity to gain greater efficiency. (b) Eliminate unnecessary memory references. Introduce temporary variables to hold intermediate results. Store a result in an array or global variable only when the final value has been computed. 3. Low-level optimizations. (a) Try various forms of pointer versus array code. (b) Reduce loop overhead by unrolling loops. (c) Find ways to make use of the pipelined functional units by techniques such as iteration splitting. 5.15. IDENTIFYING AND ELIMINATING PERFORMANCE BOTTLENECKS 261 A final word of advice to the reader is to be careful to avoid expending effort on misleading results. One useful technique is to use checking code to test each version of the code as it is being optimized to make sure no bugs are introduced during this process. Checking code applies a series of tests to the program and makes sure it obtains the desired results. It is very easy to make mistakes when one is introducing new variables, changing loop bounds, and making the code more complex overall. In addition, it is important to notice any unusual or unexpected changes in performance. As we have shown, the selection of the benchmark data can make a big difference in performance comparisons due to performance anomalies, and because we are only executing short instruction sequences. 5.15 Identifying and Eliminating Performance Bottlenecks Up to this point, we have only considered optimizing small programs, where there is some clear place in the program that requires optimization. When working with large programs, even knowing where to focus our optimizations efforts can be difficult. In this section we describe how to use code profilers, analysis tools that collect performance data about a program as it executes. We also present a general principle of system optimization known as Amdahl’s Law. 5.15.1 Program Profiling Program profiling involves running a version of a program in which instrumentation code has been incorporated to determine how much time the different parts of the program require. It can be very useful for identifying the parts of a program on which we should focus our optimization efforts. One strength of profiling is that it can be performed while running the actual program on realistic benchmark data. Unix systems provide the profiling program GPROF. This program generates two forms of information. First, it determines how much CPU time was spent for each of the functions in the program. Second, it computes a count of how many times each function gets called, categorized by which function performs the call. Both forms of information can be quite useful. The timings give a sense of the relative importance of the different functions in determining the overall run time. The calling information allows us to understand the dynamic behavior of the program. Profiling with GPROF requires three steps. We show this for a C program prog.c, to be running with command line argument file.txt: 1. The program must be compiled and linked for profiling. With GCC (and other C compilers) this involves simply including the run-time flag ‘-pg’ on the command line: unix> gcc -O2 -pg prog.c -o prog 2. The program is then executed as usual: unix> ./prog file.txt It runs slightly (up to a factor of two) slower than normal, but otherwise the only difference is that it generates a file gmon.out. 262 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE 3. G PROF is invoked to analyze the data in gmon.out. unix> gprof prog The first part of the profile report lists the times spent executing the different functions, sorted in descending order. As an example, the following shows this part of the report for the first three functions in a program: % cumulative time seconds 85.62 7.80 6.59 8.40 4.50 8.81 self seconds 7.80 0.60 0.41 self ms/call 7800.00 0.00 0.00 total ms/call 7800.00 0.00 0.00 calls 1 946596 946596 name sort_words find_ele_rec lower1 Each row represents the time spent for all calls to some function. The first column indicates the percentage of the overall time spent on the function. The second shows the cumulative time spent by the functions up to and including the one on this row. The third shows the time spent on this particular function, and the fourth shows how many times it was called (not counting recursive calls). In our example, the function sort_words was called only once, but this single call required 7.80 seconds, while the function lower1 was called 946,596 times, requiring a total of 0.41 seconds. The second part of the profile report shows the calling history of the function. The following is the history for a recursive function find_ele_rec: 4872758 find_ele_rec [5] 946596/946596 insert_string [4] 946596+4872758 find_ele_rec [5] 26946/26946 save_string [9] 26946/26946 new_ele [11] 4872758 find_ele_rec [5] [5] 6.7 0.60 0.60 0.00 0.00 0.01 0.01 0.01 0.00 This history shows both the functions that called find_ele_rec, as well as the functions that it called. In the upper part, we find that the function was actually called 5,819,354 times (shown as “946596+4872758”)— 4,872,758 times by itself, and 946,596 times by function insert_string (which itself was called 946,596 times). Function find_ele_rec in turn called two other functions: save_string and new_ele, each a total of 26,946 times. From this calling information, we can often infer useful information about the program behavior. For example, the function find_ele_rec is a recursive procedure that scans a linked list looking for a particular string. Given that the ratio of recursive to top-level calls was 5.15, we can infer that it required scanning an average of around 6 elements each time. Some properties of GPROF are worth noting: ¯ The timing is not very precise. It is based on a simple interval counting scheme, as will be discussed in Chapter 9. In brief, the compiled program maintains a counter for each function recording the time spent executing that function. The operating system causes the program to be interrupted at some regular time interval Æ . Typical values of Æ range between 1.0 and 10.0 milliseconds. It then determines what function the program was executing when the interrupt occurs and increments the 5.15. IDENTIFYING AND ELIMINATING PERFORMANCE BOTTLENECKS 263 counter for that function by Æ . Of course, it may happen that this function just started executing and will shortly be completed, but it is assigned the full cost of the execution since the previous interrupt. Some other function may run between two interrupts and therefore not be charged any time at all. Over a long duration, this scheme works reasonably well. Statistically, every function should be charged according to the relative time spent executing it. For programs that run for less than around one second, however, the numbers should be viewed as only rough estimates. ¯ ¯ The calling information is quite reliable. The compiled program maintains a counter for each combination of caller and callee. The appropriate counter is incremented every time a procedure is called. By default, the timings for library functions are not shown. Instead, these times are incorporated into the times for the calling functions. 5.15.2 Using a Profiler to Guide Optimization As an example of using a profiler to guide program optimization, we created an application that involves several different tasks and data structures. This application reads a text file, creates a table of unique words and how many times each word occurs, and then sorts the words in descending order of occurrence. As a benchmark, we ran it on a file consisting of the complete works of William Shakespeare. From this, we determined that Shakespeare wrote a total of 946,596 words, of which 26,946 are unique. The most common word was “the,” occurring 29,801 times. The word “love” occurs 2249 times, while “death” occurs 933. Our program consists of the following parts. We created a series of versions, starting with naive algorithms for the different parts, and then replacing them with more sophisticated ones: 1. Each word is read from the file and converted to lower case. Our initial version used the function lower1 (Figure 5.7), which we know to have quadratic complexity. 2. A hash function is applied to the string to create a number between 0 and × ½, for a hash table with × buckets. Our initial function simply summed the ASCII codes for the characters modulo ×. 3. Each hash bucket is organized as a linked list. The program scans down this list looking for a matching entry. If one is found, the frequency for this word is incremented. Otherwise, a new list element is created. Our initial version performed this operation recursively, inserting new elements at the end of the list. 4. Once the table has been generated, we sort all of the elements according to the frequencies. Our initial version used insertion sort. Figure 5.37 shows the profile results for different versions of our word-frequency analysis program. For each version, we divide the time into five categories: Sort Sorting the words by frequency. List Scanning the linked list for a matching word, inserting a new element if necessary. Lower Converting the string to lower case. 264 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE 10 9 8 7 6 5 4 3 2 1 0 Initial Quicksort Iter First Iter Last Big Table Better Hash Linear Lower CPU Secs. . Rest Hash Lower List Sort (a) All versions. 2 1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2 0 Quicksort Iter First Iter Last Big Table Better Hash Linear Lower Rest Hash Lower List Sort . CPU Seconds (b) All but the slowest version. Figure 5.37: Profile Results for Different Version of Word Frequency Counting Program. divided according to the different major operations in the program. Time is 5.15. IDENTIFYING AND ELIMINATING PERFORMANCE BOTTLENECKS Hash Computing the hash function. Rest The sum of all other functions. 265 As part (a) of the figure shows, our initial version requires over 9 seconds, with most of the time spent sorting. This is not surprising, since insertion sort has quadratic complexity, and the program sorted nearly 27,000 values. In our next version, we performed sorting using the library function qsort, which is based on the quicksort algorithm. This version is labeled “Quicksort” in the figure. The more efficient sorting algorithm reduces the time spent sorting to become negligible, and the overall run time to around 1.2 seconds. Part (b) of the figure shows the times for the remaining version on a scale where we can see them better. With improved sorting, we now find that list scanning becomes the bottleneck. Thinking that the inefficiency is due to the recursive structure of the function, we replaced it by an iterative one, shown as “Iter First.” Surprisingly, the run time increases to around 1.8 seconds. On closer study, we find a subtle difference between the two list functions. The recursive version inserted new elements at the end of the list, while the iterative one inserted them at the front. To maximize performance, we want the most frequent words to occur near the beginnings of the lists. That way, the function will quickly locate the common cases. Assuming words are spread uniformly throughout the document, we would expect the first occurrence of a frequent one come before that of a less frequent one. By inserting new words at the end, the first function tended to order words in descending order of frequency, while the second function tended to do just the opposite. We therefore created a third list scanning function that uses iteration but inserts new elements at the end of this list. With this version, shown as “Iter Last,” the time dropped to around 1.0 seconds, just slightly better than with the recursive version. Next, we consider the hash table structure. The initial version had only 1021 buckets (typically, the number of buckets is chosen to be a prime number to enhance the ability of the hash function to distribute keys uniformly among the buckets). For a table with 26,946 entries, this would imply an average load of ¾ ½¼¼ ¾ . That explains why so much of the time is spent performing list operations—the searches involve testing a significant number of candidate words. It also explains why the performance is so sensitive to the list ordering. We then increased the number of buckets to 10,007, reducing the average load to ¾ ¼. Oddly enough, however, our overall run time increased to 1.11 seconds. The profile results indicate that this additional time was mostly spent with the lower-case conversion routine, although this is highly unlikely. Our run times are sufficiently short that we cannot expect very high accuracy with these timings. We hypothesized that the poor performance with a larger table was due to a poor choice of hash function. Simply summing the character codes does not produce a very wide range of values and does not differentiate according to the ordering of the characters. For example, the words “god” and “dog” would hash to location ½ ·½ ·½ , since they contain the same characters. The word “foe” would also hash to this location, since ½ · ½ · ½ . We switched to a hash function that uses shift and EXCLUSIVE - OR operations. With this version, shown as “Better Hash,” the time drops to 0.84 seconds. A more systematic approach would be to study the distribution of keys among the buckets more carefully, making sure that it comes close to what one would expect if the hash function had a uniform output distribution. Finally, we have reduced the run time to the point where one half of the time is spent performing lower-case conversion. We have already seen that function lower1 has very poor performance, especially for long strings. The words in this document are short enough to avoid the disasterous consequences of quadratic pe- 266 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE formance; the longest word (“honorificabilitudinitatibus”) is 27 characters long. Still, switching to lower2, shown as “Linear Lower” yields a significant performance, with the overall time dropping to 0.52 seconds. With this exercise, we have shown that code profiling can help drop the time required for a simple application from 9.11 seconds down to 0.52—a factor of 17.5 improvement. The profiler helps us focus our attentionon the most time-consuming parts of the program and also provides useful information about the procedure call structure. We can see that profiling is a useful tool to have in the toolbox, but it should not be the only one. The timing measurements are imperfect, especially for shorter (under one second) run times. The results apply only to the particular data tested. For example, if we had run the original function on data consisting of a smaller number of longer strings, we would have found that the lower-case conversion routine was the major performance bottleneck. Even worse, if only profiled documents with short words, we might never never detect hidden performance killers such as the quadratic performance of lower1. In general, profiling can help us optimize for typical cases, assuming we run the program on representative data, but we should also make sure the program will have respectable performance for all possible cases. This is mainly involves avoiding algorithms (such as insertion sort) and bad programming practices (such as lower1) that yield poor asymptotic performance. 5.15.3 Amdahl’s Law Gene Amdahl, one of the early pioneers in computing, made a simple, but insightful observation about the effectiveness of improving the performance of one part of a system. This observation is therefore called Amdahl’s Law. The main idea is that when we speed up one part of a system, the effect on the overall system performance depends on both how significant this part was and how much it sped up. Consider a system where executing some application requires time ÌÓÐ . Suppose, some part of the system requires a fraction « of this time, and that we improve its performance by a factor of . That is, the component originally required time «ÌÓÐ , and it now requires time ´«ÌÓÐ µ . The overall execution time will be: ÌÒ Û From this, we can compute the speedup Ë « ÌÓÐ ÌÓÐ « ´½ µ ´½ «ÌÓÐ µ·« ·´ µ ÌÓÐ ÌÒ Û as: ´½ Ë « ½ µ· « (5.1) As an example, consider the case where a part of the system that initially consumed 60% of the time (« ¼ ) is sped up by a factor of 3 ( ½¼). Then we get a speedup of ½ ¼ ·¼ ¿ ½ . Thus, even though we made a substantial improvement to a major part of the system, our net speedup was significantly less. This is the major insight of Amdahl’s Law—to significantly speed up the entire system, we must improve the speed of a very large fraction of the overall system. Practice Problem 5.7: The marketing department at your company has promised your customers that the next software release will show a 2X performance improvement. You have been assigned the task of delivering on that 5.16. SUMMARY promise. You have determined that only 80% of the system can be improved. How much (i.e., what value of ) would you need to improve this part to meet the overall performance target? 267 One interesting special case of Amdahl’s Law is to consider the case where ½. That is, we are able to take some part of the system and speed it up to the point where it takes a negligible amount of time. We then get ˽ ´½ « ½ µ (5.2) So, for example, if we can speed up 60% of the system to the point where it requires close to no time, our net speedup will still only be ½ ¼ ¾ . We saw this performance with our dictionary program as we replaced insertion sort by quicksort. The initial version spent 7.8 of its 9.1 seconds performing insertion sort, giving « . With quicksort, the time spent sorting becomes negligible, giving a predicted speedup of 7.1. In fact the actual speedup was higher: ½½ ½ ¾¾ , due to inaccuracies in the profiling measurements for the initial version. We were able to gain a large speedup because sorting constituted a very large fraction of the overall execution time. Amdahl’s Law describes a general principle for improving any process. In addition to applying to speeding up computer systems, it can guide company trying to reduce the cost of manufacturing razor blades, or to a student trying to improve his or her gradepoint average. Perhaps it is most meaningful in the world of computers, where we routinely improve performance by factors of two or more. Such high factors can only be obtained by optimizing a large part of the system. 5.16 Summary Although most presentations on code optimization describe how compilers can generate efficient code, much can be done by an application programmer to assist the compiler in this task. No compiler can replace an inefficient algorithm or data structure by a good one, and so these aspects of program design should remain a primary concern for programmers. We have also see that optimization blockers, such as memory aliasing and procedure calls, seriously restrict the ability of compilers to perform extensive optimizations. Again, the programmer must take primary responsibility in eliminating these. Beyond this, we have studied a series of techniques, including loop unrolling, iteration splitting, and pointer arithmetic. As we get deeper into the optimization, it becomes important to study the generated assembly code, and to try to understand how the computation is being performed by the machine. For execution on a modern, out-of-order processor, much can be gained by analyzing how the program would execute on a machine with unlimited processing resources, but where the latencies and the issue times of the functional units match those of the target processor. To refine this analysis, we should also consider such resource constraints as the number and types of functional units. Programs that involve conditional branches or complex interactions with the memory system are more difficult to analyze and optimize than the simple loop programs we first considered. The basic strategy is to try to make loops more predictable and to try to reduce interactions between store and load operations. When working with large programs, it becomes important to focus our optimization efforts on the parts that consume the most time. Code profilers and related tools can help us systematically evaluate and improve 268 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE program performance. We described GPROF, a standard Unix profiling tool. More sophisticated profilers are available, such as the VTUNE program development system from Intel. These tools can break down the execution time below the procedure level, to measure performance of each basic block of the program. A basic block is a sequence of instructions with no conditional operations. Amdahl’s Law provides a simple, but powerful insight into the performance gains obtained by improving just one part of the system. The gain depends both on how much we improve this part and how large a fraction of the overall time this part originally required. Bibliographic Notes Many books have been written about compiler optimization techniques. Muchnick’s book is considered the most comprehensive [52]. Wadleigh and Crawford’s book on software optimization [81] covers some of the material we have, but also describes the process of getting high performance on parallel machines. Our presentation of the operation of an out-of-order processor is fairly brief and abstract. More complete descriptions of the general principles can be found in advanced computer architecture textbooks, such as the one by Hennessy and Patterson [31, Ch. 4]. Shriver and Smith give a detailed presentation of an AMD processor [65] that bears many similarities to the one we have described. Amdahl’s Law is presented in most books on computer architecture. With its major focus on quantitative system evaluation, Hennessy and Patterson’s book [31] provides a particularly good treatment. Homework Problems Homework Problem 5.8 [Category 2]: Suppose that we wish to write a procedure that computes the inner product of two vectors. An abstract version of the function has a CPE of 54 for both integer and floating-point data. By doing the same sort of transformations we did to transform the abstract program combine1 into the more efficient combine4, we get the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* Accumulate in temporary */ void inner4(vec_ptr u, vec_ptr v, data_t *dest) { int i; int length = vec_length(u); data_t *udata = get_vec_start(u); data_t *vdata = get_vec_start(v); data_t sum = (data_t) 0; for (i = 0; i < length; i++) { sum = sum + udata[i] * vdata[i]; } *dest = sum; } 5.16. SUMMARY 269 Our measurements show that this function requires 3.11 cycles per iteration for integer data. The assembly code for the inner loop is: udata in %esi, vdata in %ebx, i in %edx, sum in %ecx, length in %edi loop: Get udata[i] Multiply by vdata[i] Add to sum i++ Compare i:length If <, goto loop 1 2 3 4 5 6 7 .L24: movl (%esi,%edx,4),%eax imull (%ebx,%edx,4),%eax addl %eax,%ecx incl %edx cmpl %edi,%edx jl .L24 Assume that integer multiplication is performed by the general integer functional unit and that this unit is pipelined. This means that one cycle after a multiplication has started, a new integer operation (multiplication or otherwise) can begin. Assume also that the Integer/Branch function unit can perform simple integer operations. A. Show a translation of these lines of assembly code into a sequence of operations. The movl instruction translates into a single load operation. Register %eax gets updated twice in the loop. Label the different versions %eax.1a and %eax.1b. B. Explain how the function can go faster than the number of cycles required for integer multiplication. C. Explain what factor limits the performance of this code to at best a CPE of 2.5. D. For floating-point data, we get a CPE of 3.5. Without needing to examine the assembly code, describe a factor that will limit the performance to at best 3 cycles per iteration. Homework Problem 5.9 [Category 1]: Write a version of the inner product procedure described in Problem 5.8 that uses four-way loop unrolling. Our measurements for this procedure give a CPE of 2.20 for integer data and 3.50 for floating point. A. Explain why any version of any inner product procedure cannot achieve a CPE better than 2. B. Explain why the performance for floating point did not improve with loop unrolling. Homework Problem 5.10 [Category 1]: Write a version of the inner product procedure described in Problem 5.8 that uses four-way loop unrolling and two-way parallelism. Our measurements for this procedure give a CPE of 2.25 for floating-point data. Describe two factors that limit the performance to a CPE of at best 2.0. Homework Problem 5.11 [Category 2]: 270 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE You’ve just joined a programming team that is trying to develop the world’s fastest factorial routine. Starting with recursive factorial, they’ve converted the code to use iteration: 1 2 3 4 5 6 7 8 9 int fact(int n) { int i; int result = 1; for (i = n; i > 0; i--) result = result * i; return result; } ¿ By doing so, they have reduced the number of CPE for the function from Pentium III (really!). Still, they would like to do better. to , measured on an Intel One of the programmers heard about loop unrolling. She generated the following code: 1 2 3 4 5 6 7 8 9 int fact_u2(int n) { int i; int result = 1; for (i = n; i > 0; i-=2) { result = (result * i) * (i-1); } return result; } Unfortunately, the team discovered that this code returns 0 for some values of argument n. A. For what values of n will fact_u2 and fact return different values? B. Show how to fix fact_u2. Note that there is a special trick for this procedure that involves just changing a loop bound. C. Benchmarking fact_u2 shows no improvement in performance. How would you explain that? D. You modify the line inside the loop to read: 7 result = result * (i * (i - 1)); To everyone’s astonishment, the measured performance now has a CPE of ¾ . How do you explain this performance improvement? Homework Problem 5.12 [Category 1]: Using the conditional move instruction, write assembly code for the body of the following function: 5.16. SUMMARY 1 2 3 4 5 271 /* Return maximum of x and y */ int max(int x, int y) { return (x < y) ? y : x; } Homework Problem 5.13 [Category 2]: Using conditional moves, the general technique for translating a statement of the form: val = cond-expr ? then-expr : else-expr; is to generate code of the form: val = then-expr; temp = else-expr; test = cond-expr; if (test) val = temp; where the last line is implemented with a conditional move instruction. Using the example of Practice Problem 5.5 as a guide, state the general requirements for this translation to be valid. Homework Problem 5.14 [Category 2]: The following function computes the sum of the elements in a linked list: 1 2 3 4 5 6 7 8 static int list_sum(list_ptr ls) { int sum = 0; for (; ls; ls = ls->next) sum += ls->data; return sum; } The assembly code for the loop, and its translation of the first iteration into operations yields the following: Assembly Instructions .L43: addl 4(%edx),%eax movl (%edx),%edx testl %edx,%edx jne .L43 Execution Unit Operations movl 4(%edx.0) addl t.1,%eax.0 load (%edx.0) testl %edx.1,%edx.1 jne-taken cc.1 t.1 %eax.1 %edx.1 cc.1 272 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE A. Draw a graph showing the scheduling of operations for the first three iterations of the loop, in the style of Figure 5.31. Recall that there is just one load unit. B. Our measurements for this function give a CPE of 4.00. Is this consistent with the graph you drew in part A? Homework Problem 5.15 [Category 2]: The following function is a variant on the list sum function shown in Problem 5.14: 1 2 3 4 5 6 7 8 9 10 11 12 static int list_sum2(list_ptr ls) { int sum = 0; list_ptr old; while (ls) { old = ls; ls = ls->next; sum += old->data; } return sum; } This code is written in such a way that the memory access to fetch the next list element comes before the one to retrieve the data field from the current element. The assembly code for the loop, and its translation of the first iteration into operations yields the following: Assembly Instructions .L48: movl %edx,%ecx movl (%edx),%edx addl 4(%ecx),%eax testl %edx,%edx jne .L48 Execution Unit Operations load (%edx.0) movl 4(%edx.0) addl t.1,%eax.0 testl %edx.1,%edx.1 jne-taken cc.1 %edx.1 t.1 %eax.1 cc.1 Note that the register move operation movl %edx,%ecx does not require any operations to implement. It is handled by simply associating the tag edx.0 with register %ecx, so that the later instruction addl 4(%ecx),%eax is translated to use edx.0 as its source operand. A. Draw a graph showing the scheduling of operations for the first three iterations of the loop, in the style of Figure 5.31. Recall that there is just one load unit. 5.16. SUMMARY 273 B. Our measurements for this function give a CPE of 3.00. Is this consistent with the graph you drew in part A? C. How does this function make better use of the load unit than did the function of Problem 5.14? 274 CHAPTER 5. OPTIMIZING PROGRAM PERFORMANCE Chapter 6 The Memory Hierarchy To this point in our study of systems, we have relied on a simple model of a computer system as a CPU that executes instructions and a memory system that holds instructions and data for the CPU. In our simple model, the memory system is a linear array of bytes, and the CPU can access each memory location in a constant amount of time. While this is an effective model as far as it goes, it does not reflect the way that modern systems really work. In practice, a memory system is a hierarchy of storage devices with different capacities, costs, and access times. Registers in the CPU hold the most frequently used data. Small, fast cache memories near the CPU act as staging areas for a subset of the data and instructions stored in the relatively slow main memory. The main memory stages data stored on large, slow disks, which in turn often serve as staging areas for data stored on the disks or tapes of other machines connected by networks. Memory hierarchies work because programs tend to access the storage at any particular level more frequently than they access the storage at the next lower level. So the storage at the next level can be slower, and thus larger and cheaper per bit. The overall effect is a large pool of memory that costs as much as the cheap storage near the bottom of the hierarchy, but that serves data to programs at the rate of the fast storage near the top of the hierarchy. In contrast to the uniform access times in our simple system model, memory access times on a real system can vary by factors of ten, or one hundred, or even one million. Unwary programmers who assume a flat, uniform memory risk significant and inexplicable performance slowdowns in their programs. On the other hand, wise programmers who understand the hierarchical nature of memory can use relatively simple techniques to produce efficient programs with fast average memory access times. In this chapter, we look at the most basic storage technologies of SRAM memory, DRAM memory, and disks. We also introduce a fundamental property of programs known as locality and show how locality motivates the organization of memory as a hierarchy of devices. Finally, we focus on the design and performance impact of the cache memories that act as staging areas between the CPU and main memory, and show you how to use your understanding of locality and caching to make your programs run faster. 275 276 CHAPTER 6. THE MEMORY HIERARCHY 6.1 Storage Technologies Much of the success of computer technology stems from the tremendous progress in storage technology. Early computers had a few kilobytes of random-access memory. The earliest IBM PCs didn’t even have a hard disk. That changed with the introduction of the IBM PC-XT in 1982, with its 10-megabyte disk. By the year 2000, typical machines had 1000 times as much disk storage and the ratio was increasing by a factor of 10 every two or three years. 6.1.1 Random-Access Memory Random-access memory (RAM) comes in two varieties—static and dynamic. Static RAM (SRAM) is faster and significantly more expensive than Dynamic RAM (DRAM). SRAM is used for cache memories, both on and off the CPU chip. DRAM is used for the main memory plus the frame buffer of a graphics system. Typically, a desktop system will have no more than a few megabytes of SRAM, but hundreds or thousands of megabytes of DRAM. Static RAM SRAM stores each bit in a bistable memory cell. Each cell is implemented with a six-transistor circuit. This circuit has the property that it can stay indefinitely in either of two different voltage configurations, or states. Any other state will be unstable—starting from there, the circuit will quickly move toward one of the stable states. Such a memory cell is analogous to the inverted pendulum illustrated in Figure 6.1. Unstable Stable Left . . Stable Right Figure 6.1: Inverted pendulum. Like an SRAM cell, the pendulum has only two stable configurations, or states. The pendulum is stable when it is tilted either all the way to the left, or all the way to the right. From any other position, the pendulum will fall to one side or the other. In principle, the pendulum could also remain balanced in a vertical position indefinitely, but this state is metastable—the smallest disturbance would make it start to fall, and once it fell it would never return to the vertical position. Due to its bistable nature, an SRAM memory cell will retain its value indefinitely, as long as it is kept powered. Even when a disturbance, such as electrical noise, perturbs the voltages, the circuit will return to the stable value when the disturbance is removed. . 6.1. STORAGE TECHNOLOGIES 277 Dynamic RAM DRAM stores each bit as charge on a capacitor. This capacitor is very small—typically around 30 femtofarads, that is, ¿¼ ¢ ½¼ ½ farads. Recall, however, that a farad is a very large unit of measure. DRAM storage can be made very dense—each cell consists of a capacitor and a single-access transistor. Unlike SRAM, however, a DRAM memory cell is very sensitive to any disturbance. When the capacitor voltage is disturbed, it will never recover. Exposure to light rays will cause the capacitor voltages to change. In fact, the sensors in digital cameras and camcorders are essentially arrays of DRAM cells. Various sources of leakage current cause a DRAM cell to lose its charge within a time period of around 10 to 100 milliseconds. Fortunately, for computers operating with clock cycles times measured in nanoseconds, this retention time is quite long. The memory system must periodically refresh every bit of memory by reading it out and then rewriting it. Some systems also use error-correcting codes, where the computer words are encoded a few more bits (e.g., a 32-bit word might be encoded using 38 bits), such that circuitry can detect and correct any single erroneous bit within a word. Figure 6.2 summarizes the characteristics of SRAM and DRAM memory. SRAM is persistent as long as power is applied to them. Unlike DRAM, no refresh is necessary. SRAM can be accessed faster than DRAM. SRAM is not sensitive to disturbances such as light and electrical noise. The tradeoff is that SRAM cells use more transistors than DRAM cells, and thus have lower densities, are more expensive, and consume more power. Transistors per bit 6 1 Relative access time 1X 10X Persistent? Yes No Sensitive? No Yes Relative Cost 100X 1X Applications Cache memory Main mem, frame buffers SRAM DRAM Figure 6.2: Characteristics of DRAM and SRAM memory. Conventional DRAMs The cells (bits) in a DRAM chip are partitioned into supercells, each consisting of Û DRAM cells. A ¢ Û DRAM stores a total of Û bits of information. The supercells are organized as a rectangular array with Ö rows and columns, where Ö . Each supercell has an address of the form ´ µ, where denotes the row, and denotes the column. For example, Figure 6.3 shows the organization of a ½ ¢ DRAM chip with ½ supercells, Û bits per supercell, Ö rows, and columns. The shaded box denotes the supercell at address ´¾ ½µ. Information flows in and out of the chip via external connectors called pins. Each pin carries a 1-bit signal. Figure 6.3 shows two of these sets of pins: 8 data pins that can transfer one byte in or out of the chip, and 2 addr pins that carry 2-bit row and column supercell addresses. Other pins that carry control information are not shown. Aside: A note on terminology. The storage community has never settled on a standard name for a DRAM array element. Computer architects tend to refer to it as a “cell”, overloading the term with the DRAM storage cell. Circuit designers tend to refer to it as a 278 DRAM chip CHAPTER 6. THE MEMORY HIERARCHY cols 0 2 / 1 2 3 0 1 rows 2 3 supercell (2,1) addr memory controller (to CPU) 8 / data internal row buffer Figure 6.3: High level view of a 128-bit ½ ¢ DRAM chip. “word”, overloading the term with a word of main memory. To avoid confusion, we have adopted the unambiguous term “supercell”. End Aside. Each DRAM chip is connected to some circuitry, known as the memory controller, that can transfer Û bits at a time to and from each DRAM chip. To read the contents of supercell ´ µ, the memory controller sends the row address to the DRAM, followed by the column address . The DRAM responds by sending the contents of supercell ´ µ back to the controller. The row address is called a RAS (Row Access Strobe) request. The column address is called a CAS (Column Access Strobe) request. Notice that the RAS and CAS requests share the same DRAM address pins. For example, to read supercell ´¾ ½µ from the ½ ¢ DRAM in Figure 6.3, the memory controller sends row address 2, as shown in Figure 6.4(a). The DRAM responds by copying the entire contents of row 2 into an internal row buffer. Next, the memory controller sends column address 1, as shown in Figure 6.4(b). The DRAM responds by copying the 8 bits in supercell ´¾ ½µ from the row buffer and sending them to the memory controller. DRAM chip cols RAS = 2 2 / DRAM chip cols 2 3 CAS = 1 2 / 0 0 1 1 0 0 1 1 2 3 addr memory controller 8 / addr rows 2 3 memory controller rows supercell (2,1) 8 / 2 3 data row 2 internal row buffer data internal row buffer (a) Select row 2 (RAS request). (b) Select column 1 (CAS request). Figure 6.4: Reading the contents of a DRAM supercell. One reason circuit designers organize DRAMs as two-dimensional arrays instead of linear arrays is to reduce 6.1. STORAGE TECHNOLOGIES 279 the number of address pins on the chip. For example, if our example 128-bit DRAM were organized as a linear array of 16 supercells with addresses 0 to 15, then the chip would need four address pins instead of two. The disadvantage of the two-dimensional array organization is that addresses must be sent in two distinct steps, which increases the access time. Memory Modules DRAM chips are packaged in memory modules that plug into expansion slots on the main system board (motherboard). Common packages include the 168-pin Dual Inline Memory Module (DIMM), which transfers data to and from the memory controller in 64-bit chunks, and the 72-pin Single Inline Memory Module (SIMM), which transfers data in 32-bit chunks. Figure 6.5 shows the basic idea of a memory module. The example module stores a total of 64 MB (megabytes) using eight 64-Mbit Å ¢ DRAM chips, numbered 0 to 7. Each supercell stores one byte of main memory, and each 64-bit doubleword1 at byte address in main memory is represented by the eight supercells whose corresponding supercell address is ´ µ. In our example in Figure 6.5, DRAM 0 stores the first (lower-order) byte, DRAM 1 stores the next byte, and so on. addr (row = i, col = j) : supercell (i,j) DRAM 0 DRAM 7 64 MB memory module consisting of 8 8Mx8 DRAMs data bits 56-63 bits 48-55 bits 40-47 bits 32-39 bits 24-31 bits 16-23 bits 8-15 bits 0-7 63 56 55 48 47 40 39 32 31 24 23 16 15 87 0 Memory controller 64-bit double word at main memory address A 64-bit doubleword to CPU chip Figure 6.5: Reading the contents of a memory module. To retrieve a 64-bit doubleword at memory address , the memory controller converts to a supercell address ´ µ and sends it to the memory module, which then broadcasts and to each DRAM. In response, each DRAM outputs the 8-bit contents of its ´ µ supercell. Circuitry in the module collects these outputs and forms them into a 64-bit doubleword, which it returns to the memory controller. 1 IA32 would call this 64-bit quantity a “quadword.” 280 CHAPTER 6. THE MEMORY HIERARCHY Main memory can be aggregated by connecting multiple memory modules to the memory controller. In this case, when the controller receives an address , the controller selects the module that contains , converts to its ´ µ form, and sends ´ µ to module . Practice Problem 6.1: In the following, let Ö be the number of rows in a DRAM array, the number of columns, Ö the number of bits needed to address the rows, and the number of bits needed to address the columns. For each of the following DRAMs, determine the power-of-two array dimensions that minimize Ñ Ü´ Ö µ, the maximum number of bits needed to address the rows or columns of the array. Organization Ö ¢½ ¢ ½¾ ¢ ½¾ ¢ ½¼¾ ¢ ½ ½ Ö Ñ Ü´ Ö µ Enhanced DRAMs There are many kinds of DRAM memories, and new kinds appear on the market with regularity as manufacturers attempt to keep up with rapidly increasing processor speeds. Each is based on the conventional DRAM cell, with optimizations that improve the speed with which the basic DRAM cells can be accessed. ¯ Fast page mode DRAM (FPM DRAM). A conventional DRAM copies an entire row of supercells into its internal row buffer, uses one, and then discards the rest. FPM DRAM improves on this by allowing consecutive accesses to the same row to be served directly from the row buffer. For example, to read four supercells from row of a conventional DRAM, the memory controller must send four RAS/CAS requests, even though the row address is identical in each case. To read supercells from the same row of an FPM DRAM, the memory controller sends an initial RAS/CAS request, followed by three CAS requests. The initial RAS/CAS request copies row into the row buffer and returns the first supercell. The next three supercells are served directly from the row buffer, and thus more quickly than the initial supercell. Extended data out DRAM (EDO DRAM). An enhanced form of FPM DRAM that allows the individual CAS signals to be spaced closer together in time. Synchronous DRAM (SDRAM). Conventional, FPM, and EDO DRAMs are asynchronous in the sense that they communicate with the memory controller using a set of explicit control signals. SDRAM replaces many of these control signals with the rising edges of the same external clock signal that drives the memory controller. Without going into detail, the net effect is that an SDRAM can output the contents of its supercells at a faster rate than its asynchronous counterparts. Double Data-Rate Synchronous DRAM (DDR SDRAM). DDR SDRAM is an enhancement of SDRAM that doubles the speed of the DRAM by using both clock edges as control signals. ¯ ¯ ¯ 6.1. STORAGE TECHNOLOGIES 281 ¯ Video RAM (VRAM). Used in the frame buffers of graphics systems. VRAM is similar in spirit to FPM DRAM. Two major differences are that (1) VRAM output is produced by shifting the entire contents of the internal buffer in sequence, and (2) VRAM allows concurrent reads and writes to the memory. Thus the system can be painting the screen with the pixels in the frame buffer (reads) while concurrently writing new values for the next update (writes). Aside: Historical popularity of DRAM technologies. Until 1995, most PC’s were built with FPM DRAMs. From 1996-1999, EDO DRAMs dominated the market while FPM DRAMs all but disappeared. SDRAMs first appeared in 1995 in high-end systems, and by 2001 most PC’s were built with SDRAMs. End Aside. Nonvolatile Memory DRAMs and SRAMs are volatile in the sense that they lose their information if the supply voltage is turned off. Nonvolatile memories, on the other hand, retain their information even when they are powered off. There are a variety of nonvolatile memories. For historical reasons, they are referred to collectively as read-only memories (ROMs), even though some types of ROMs can be written to as well as read. ROMs are distinguished by the number of times they can be reprogrammed (written to) and by the mechanism for reprogramming them. A programmable ROM (PROM) can be programmed exactly once. PROMs include a sort of fuse with each memory cell that can be blown once by zapping it with a high current. An erasable programmable ROM (EPROM) has a small transparent window on the outside of the chip that exposes the memory cells to outside light. The EPROM is reprogrammed by placing it in a special device that shines ultraviolet light onto the storage cells. An EPROM can be reprogrammed on the order of 1,000 times. An electrically-erasable PROM (EEPROM) is akin to an EPROM, but it has an internal structure that allows it to be reprogrammed electrically. Unlike EPROMs, EEPROMs do not require a physically separate programming device, and thus can be reprogrammed in-place on printed circuit cards. An EEPROM can be reprogrammed on the order of ½¼ times. Flash memory is a family of small nonvolatile memory cards, based on EEPROMs, that can be plugged in and out of a desktop machine, handheld device, or video game console. Programs stored in ROM devices are often referred to as firmware. When a computer system is powered up, it runs firmware stored in a ROM. Some systems provide a small set of primitive input and output functions in firmware, for example, a PC’s BIOS (basic input/output system) routines. Complicated devices such as graphics cards and disk drives also rely on firmware to translate I/O (input/output) requests from the CPU. Accessing Main Memory Data flows back and forth between the processor and the DRAM main memory over shared electrical conduits called buses. Each transfer of data between the CPU and memory is accomplished with a series of steps called a bus transaction. A read transaction transfers data from the main memory to the CPU. A write transaction transfers data from the CPU to the main memory. A bus is a collection of parallel wires that carry address, data, and control signals. Depending on the particular bus design, data and address signals can share the same set of wires, or they can use different 282 CHAPTER 6. THE MEMORY HIERARCHY sets. Also, more than two devices can share the same bus. The control wires carry signals that synchronize the transaction and identify what kind of transaction is currently being performed. For example, is this transaction of interest to the main memory, or to some other I/O device such as a disk controller? Is the transaction a read or a write? Is the information on the bus an address or a data item? Figure 6.6 shows the configuration of a typical desktop system. The main components are the CPU chip, a chipset that we will call an I/O bridge (which includes the memory controller), and the DRAM memory modules that comprise main memory. These components are connected by a pair of buses: a system bus that connects the CPU to the I/O bridge, and a memory bus that connects the I/O bridge to the main memory. CPU chip register file ALU system bus memory bus bus interface I/O bridge main memory Figure 6.6: Typical bus structure that connects the CPU and main memory. The I/O bridge translates the electrical signals of the system bus into the electrical signals of the memory bus. As we will see, the I/O bridge also connects the system bus and memory bus to an I/O bus that is shared by I/O devices such as disks and graphics cards. For now, though, we will focus on the memory bus. Consider what happens when the CPU performs a load operation such as movl A,%eax where the contents of address are loaded into register %eax. Circuitry on the CPU chip called the bus interface initiates a read transaction on the bus. The read transaction consists of three steps. First, the CPU places the address on the system bus. The I/O bridge passes the signal along to the memory bus (Figure 6.7(a)). Next, the main memory senses the address signal on the memory bus, reads the address from the memory bus, fetches the data word from the DRAM, and writes the data to the memory bus. The I/O bridge translates the memory bus signal into a system bus signal, and passes it along to the system bus (Figure 6.7(b)). Finally, the CPU senses the data on the system bus, reads it from the bus, and copies it to register %eax (Figure 6.7(c)). Conversely, when the CPU performs a store instruction such as movl %eax,A where the contents of register %eax are written to address , the CPU initiates a write transaction. Again, there are three basic steps. First, the CPU places the address on the system bus. The memory reads the address from the memory bus and waits for the data to arrive (Figure 6.8(a)). Next, the CPU copies the data word in %eax to the system bus (Figure 6.8(b)). Finally, the main memory reads the data word from the memory bus and stores the bits in the DRAM (Figure 6.8(c)). 6.1. STORAGE TECHNOLOGIES 283 register file %eax ALU main memory 0 x I/O bridge bus interface A A (a) CPU places address on the memory bus. register file %eax ALU main memory 0 x I/O bridge bus interface x A (b) Main memory reads from the bus, retrieves word Ü, and places it on the bus. register file %eax x ALU main memory 0 x I/O bridge bus interface A (c) CPU reads word Ü from the bus, and copies it into register %eax. Figure 6.7: Memory read transaction for a load operation: movl A,%eax. 284 CHAPTER 6. THE MEMORY HIERARCHY register file %eax y ALU main memory 0 A I/O bridge bus interface A (a) CPU places address on the memory bus. Main memory reads it and waits for the data word. register file %eax y ALU main memory 0 A I/O bridge bus interface y (b) CPU places data word Ý on the bus. register file %eax y ALU main memory 0 y I/O bridge bus interface A (c) Main memory reads data word Ý from the bus and stores it at address . Figure 6.8: Memory write transaction for a store operation: movl %eax,A. 6.1. STORAGE TECHNOLOGIES 285 6.1.2 Disk Storage Disks are workhorse storage devices that hold enormous amounts of data, on the order of tens to hundreds of gigabytes, as opposed to the hundreds or thousands of megabytes in a RAM-based memory. However, it takes on the order of milliseconds to read information from a disk, a hundred thousand times longer than from DRAM and a million times longer than from SRAM. Disk Geometry Disks are constructed from platters. Each platter consists of two sides, or surfaces, that are coated with magnetic recording material. A rotating spindle in the center of the platter spins the platter at a fixed rotational rate, typically between 5400 and 15,000 revolutions per minute (RPM). A disk will typically contain one or more of these platters encased in a sealed container. Figure 6.9(a) shows the geometry of a typical disk surface. Each surface consists of a collection of concentric rings called tracks. Each track is partitioned into a collection of sectors. Each sector contains an equal number of data bits (typically 512 bytes) encoded in the magnetic material on the sector. Sectors are separated by gaps where no data bits are stored. Gaps store formatting bits that identify sectors. tracks surface track k gaps cylinder k surface 0 spindle surface 1 surface 2 surface 3 surface 4 surface 5 platter 0 platter 1 platter 2 sectors spindle (a) Single-platter view. Figure 6.9: Disk geometry. (b) Multiple-platter view. A disk consists of one or more platters stacked on top of each other and encased in a sealed package, as shown in Figure 6.9(b). The entire assembly is often referred to as a disk drive, although we will usually refer to it as simply a disk. Disk manufacturers often describe the geometry of multiple-platter drives in terms of cylinders, where a cylinder is the collection of tracks on all the surfaces that are equidistant from the center of the spindle. For example, if a drive has three platters and six surfaces, and the tracks on each surface are numbered consistently, then cylinder is the collection of the six instances of track . 286 CHAPTER 6. THE MEMORY HIERARCHY Disk Capacity The maximum number of bits that can be recorded by a disk is known as its maximum capacity, or simply capacity. Disk capacity is determined by the following technology factors: ¯ ¯ ¯ Recording density (bits in): The number of bits that can be squeezed into a one-inch segment of a track. Track density (tracks in): The number of tracks that can be squeezed into a one-inch segment of the radius extending from the center of the platter. Areal density (bits in¾ ): The product of the recording density and the track density. Disk manufacturers work tirelessly to increase areal density (and thus capacity), and this is doubling every few years. The original disks, designed in an age of low areal density, partitioned every track into the same number of sectors, which was determined by the number of sectors that could be recorded on the innermost track. To maintain a fixed number of sectors per track, the sectors were spaced further apart on the outer tracks. This was a reasonable approach when areal densities were relatively low. However, as areal densities increased, the gaps between sectors (where no data bits were stored) became unacceptably large. Thus, modern high-capacity disks use a technique known as multiple zone recording, where the set of tracks is partitioned into disjoint subsets known as recording zones. Each zone contains a contiguous collection of tracks. Each track in a zone has the same number of sectors, which is determined by the number of sectors that can be packed into the innermost track of the zone. Note that diskettes (floppy disks) still use the old-fashioned approach, with a constant number of sectors per track. The capacity of a disk is given by the following: Disk capacity # bytes sector surfaces ¢ average # sectors ¢ # tracks ¢ # platter ¢ # platters track surface disk For example, suppose we have a disk with 5 platters, 512 bytes per sector, 20,000 tracks per surface, and an average of 300 sectors per track. Then the capacity of the disk is: Disk capacity 512 bytes 300 sectors ¢ track sector 30,720,000,000 bytes 30.72 GB Notice that manufacturers express disk capacity in units of gigabytes (GB), where ½ ½¼ surfaces ¢ 20,000 tracks ¢ 2 platter ¢ 5 platters surface disk bytes. Aside: How much is a gigabyte? Unfortunately, the meanings of prefixes such as kilo (à ), mega (Å ) and giga ( ) depend on the context. For ½¼ ¾¼ ¿¼ measures that relate to the capacity of DRAMs and SRAMs, typically à ,Å and . For ¿ ,Å and measures related to the capacity of I/O devices such as disks and networks, typically à . Rates and throughputs usually use these prefix values as well. ¾ ¾ ½¼ ½¼ ¾ ½¼ ½¼ µ ½¼ Fortunately, for the back-of-the-envelope estimates that we typically rely on, either assumption works fine in pracand is small: ¾¼ tice. For example, the relative difference between ¾¼ ¿¼ ¿¼ . Similarly for and : . End Aside. ± ¾ ¾ ½¼¿ ½ ¾ ½¼ ½¼ ½ ¼¼¼ ¼¼¼ ½¼ ½ ¼¼¼ ¼¼¼ ¼¼¼ ´¾ ½¼ µ ½¼ ´¾ ± 6.1. STORAGE TECHNOLOGIES Practice Problem 6.2: What is the capacity of a disk with 2 platters, 10,000 cylinders, an average of 400 sectors per track, and 512 bytes per sector? 287 Disk Operation Disks read and write bits stored on the magnetic surface using a read/write head connected to the end of an actuator arm, as shown in Figure 6.10(a). By moving the arm back and forth along its radial axis the drive can position the head over any track on the surface. This mechanical motion is known as a seek. Once the head is positioned over the desired track, then as each bit on the track passes underneath, the head can either sense the value of the bit (read the bit) or alter the value of the bit (write the bit). Disks with multiple platters have a separate read/write head for each surface, as shown in Figure 6.10(b). The heads are lined up vertically and move in unison. At any point in time, all heads are positioned on the same cylinder. The disk surface spins at a fixed rotational rate The read/write head is attached to the end of the arm and flies over the disk surface on a thin cushion of air. read/write heads spindle arm By moving radially, the arm can position the read/write head over any track. spindle (a) Single-platter view Figure 6.10: Disk dynamics. (b) Multiple-platter view The read/write head at the end of the arm flies (literally) on a thin cushion of air over the disk surface at a height of about 0.1 microns and a speed of about 80 km/h. This is analogous to placing the Sears Tower on its side and flying it around the world at a height of 2.5 cm (1 inch) above the ground, with each orbit of the earth taking only 8 seconds! At these tolerances, a tiny piece of dust on the surface is a huge boulder. If the head were to strike one of these boulders, the head would cease flying and crash into the surface (a so-called head crash). For this reason, disks are always sealed in airtight packages. Disks read and write data in sector-sized blocks. The access time for a sector has three main components: seek time, rotational latency, and transfer time: ¯ Seek time: To read the contents of some target sector, the arm first positions the head over the track that contains the target sector. The time required to move the arm is called the seek time. The seek time, Ì× , depends on the previous position of the head and the speed that the arm moves across the surface. The average seek time in modern drives, Ì Ú × , measured by taking the mean of several 288 CHAPTER 6. THE MEMORY HIERARCHY thousand seeks to random sectors, is typically on the order of 6 to 9 ms. The maximum time for a single seek, ÌÑ Ü × , can be as high as 20 ms. ¯ Rotational latency: Once the head is in position over the track, the drive waits for the first bit of the target sector to pass under the head. The performance of this step depends on the position of the surface when the head arrives at the target sector, and the rotational speed of the disk. In the worst case, the head just misses the target sector, and waits for the disk to make a full rotation. So the maximum rotational latency in seconds is: Ì The average rotational latency, Ì Ú Ñ Ü ÖÓØ Ø ÓÒ ÖÓØ Ø ÓÒ , is simply half of ÌÑ secs ¢ 60 min RPM 1 ½ Ü ÖÓØ Ø ÓÒ . ¯ Transfer time: When the first bit of the target sector is under the head, the drive can begin to read or write the contents of the sector. The transfer time for one sector depends on the rotational speed and the number of sectors per track. Thus, we can roughly estimate the average transfer time for one sector in seconds as: ½ ½ secs Ì Ú ØÖ Ò× Ö ¢ ¢ 60 min RPM ´average # sectors/track µ 1 We can estimate the average time to access a the contents of a disk sector as the sum of the average seek time, the average rotational latency, and the average transfer time. For example, consider a disk with the following parameters: Parameter Rotational rate Ì Ú× Average # sectors/track Value 7,200 RPM 9 ms 400 For this disk, the average rotational latency (in ms) is Ì Ú ÖÓØ Ø ÓÒ 1/2 ¢ ÌÑ 4 ms 1/2 ¢ ´60 secs / 7,200 RPMµ ¢ 1000 ms/sec Ü ÖÓØ Ø ÓÒ The average transfer time is Ì Ú ØÖ Ò× Ö 60 / 7,200 RPM ¢ 1 / 400 sectors/track ¢ 1000 ms/sec 0.02 ms Putting it all together, the total estimated access time is Ì ×× Ì Ú × · Ì Ú ÖÓØ Ø ÓÒ · Ì Ú ØÖ Ò× Ö 9 ms · 4 ms · 0.02 ms 13.02 ms This example illustrates some important points: 6.1. STORAGE TECHNOLOGIES 289 ¯ ¯ ¯ The time to access the 512 bytes in a disk sector is dominated by the seek time and the rotational latency. Accessing the first byte in the sector takes a long time, but the remaining bytes are essentially free. Since the seek time and rotational latency are roughly the same, twice the seek time is a simple and reasonable rule for estimating disk access time. The access time for a doubleword stored in SRAM is roughly 4 ns, and 60 ns for DRAM. Thus, the time to read a 512-byte sector-sized block from memory is roughly 256 ns for SRAM and 4000 ns for DRAM. The disk access time, roughly 10 ms, is about 40,000 times greater than SRAM, and about 2,500 times greater than DRAM. The difference in access times is even more dramatic if we compare the times to access a single word. Practice Problem 6.3: Estimate the average time (in ms) to access a sector on the following disk: Parameter Rotational rate Ì Ú× Average # sectors/track Value 15,000 RPM 8 ms 500 Logical Disk Blocks As we have seen, modern disks have complex geometries, with multiple surfaces and different recording zones on those surfaces. To hide this complexity from the operating system, modern disks present a simpler view of their geometry as a sequence of sector-sized logical blocks, numbered ¼ ½ ½. A small hardware/firmware device in the disk, called the disk controller, maintains the mapping between logical block numbers and actual (physical) disk sectors. When the operating system wants to perform an I/O operation such as reading a disk sector into main memory, it sends a command to the disk controller asking it to read a particular logical block number. Firmware on the controller performs a fast table lookup that translates the logical block number into a (surface, track, sector) triple that uniquely identifies the corresponding physical sector. Hardware on the controller interprets this triple to move the heads to the appropriate cylinder, waits for the sector to pass under the head, gathers up the bits sensed by the head into a small buffer on the controller, and copies them into main memory. Aside: Formatted disk capacity. Before a disk can be used to store data, it must be formatted by the disk controller. This involves filling in the gaps between sectors with information that identifies the sectors, identifying any cylinders with surface defects and taking them out of action, and setting aside a set of cylinders in each zone as spares that can be called into action if one of more cylinders in the zone goes bad during the lifetime of the disk. The formatted capacity quoted by disk manufacturers is less than the maximum capacity because of the existence of these spare cylinders. End Aside. 290 CHAPTER 6. THE MEMORY HIERARCHY Accessing Disks Devices such as graphics cards, monitors, mice, keyboards, and disks are connected to the CPU and main memory using an I/O bus such as Intel’s Peripheral Component Interconnect (PCI) bus. Unlike the system bus and memory buses, which are CPU-specific, I/O buses such as PCI are designed to be independent of the underlying CPU. For example, PCs and Macintosh’s both incorporate the PCI bus. Figure 6.11 shows a typical I/O bus structure (modeled on PCI) that connects the CPU, main memory, and I/O devices. CPU register file ALU system bus memory bus main memory bus interface I/O bridge I/O bus USB controller mouse keyboard graphics adapter monitor disk disk controller Expansion slots for other devices such as network adapters. Figure 6.11: Typical bus structure that connects the CPU, main memory, and I/O devices. Although the I/O bus is slower than the system and memory buses, it can accommodate a wide variety of third-party I/O devices. For example, the bus in Figure 6.11 has three different types of devices attached to it. ¯ ¯ ¯ A Universal Serial Bus (USB) controller is a conduit for devices attached to the USB. A USB has a throughput of 12 Mbits/s and is designed for slow to moderate speed serial devices such as keyboards, mice, modems, digital cameras, joysticks, CD-ROM drives, and printers. A graphics card (or adapter) contains hardware and software logic that is responsible for painting the pixels on the display monitor on behalf of the CPU. A disk controller contains the hardware and software logic for reading and writing disk data on behalf of the CPU. Additional devices such as network adapters can be attached to the I/O bus by plugging the adapter into empty expansion slots on the motherboard that provide a direct electrical connection to the bus. While a detailed description of how I/O devices work and how they are programmed is outside our scope, we can give you a general idea. For example, Figure 6.12 summarizes the steps that take place when a CPU reads data from a disk. 6.1. STORAGE TECHNOLOGIES CPU chip register file ALU 291 bus interface main memory I/O bus USB controller mouse keyboard graphics adapter monitor disk controller disk (a) The CPU initiates a disk read by writing a command, logical block number, and destination memory address to the memory-mapped address associated with the disk. CPU chip register file ALU bus interface main memory I/O bus USB controller mouse keyboard graphics adapter monitor disk controller disk (b) The disk controller reads the sector and performs a DMA transfer into main memory. CPU chip register file ALU bus interface main memory I/O bus USB controller mouse keyboard graphics adapter monitor disk controller disk (c) When the DMA transfer is complete, the disk controller notifies the CPU with an interrupt. Figure 6.12: Reading a disk sector. 292 CHAPTER 6. THE MEMORY HIERARCHY The CPU issues commands to I/O devices using a technique called memory-mapped I/O (Figure 6.12(a)). In a system with memory-mapped I/O, a block of addresses in the address space is reserved for communicating with I/O devices. Each of these addresses is known as an I/O port. Each device is associated with (or mapped to) one or more ports when it is attached to the bus. As a simple example, suppose that the disk controller is mapped to port 0xa0. Then the CPU might initiate a disk read by executing three store instructions to address 0xa: The first of these instructions sends a command word that tells the disk to initiate a read, along with other parameters such as whether to interrupt the CPU when the read is finished. (We will discuss interrupts in Section 8.1). The second instruction indicates the number of the logical block that should be read. The third instruction indicates the main memory address where the contents of the disk sector should be stored. After it issues the request, the CPU will typically do other work while the disk is performing the read. Recall that a 1 GHz processor with a 1 ns clock cycle can potentially execute 16 million instructions in the 16 ms it takes to read the disk. Simply waiting and doing nothing while the transfer is taking place would be enormously wasteful. After the disk controller receives the read command from the CPU, it translates the logical block number to a sector address, reads the contents of the sector, and transfers the contents directly to main memory, without any intervention from the CPU (Figure 6.12(b)). This process where a device performs a read or write bus transaction on its own, without any involvement of the CPU, is known as direct memory access (DMA). The transfer of data is known as a DMA transfer. After the DMA transfer is complete and the contents of the disk sector are safely stored in main memory, the disk controller notifies the CPU by sending an interrupt signal to the CPU (Figure 6.12(c)). The basic idea is that an interrupt signals an external pin on the CPU chip. This causes the CPU to stop what it is currently working on and to jump to an operating system routine. The routine records the fact that the I/O has finished and then returns control to the point where the CPU was interrupted. Aside: Anatomy of a commercial disk. Disk manufacturers publish a lot of high-level technical information on their Web pages. For example, if we visit the Web page for the IBM Ultrastar 36LZX disk, we can glean the geometry and performance information shown in Figure 6.13. Geometry attribute Platters Surfaces (heads) Sector size Zones Cylinders Recording density (max) Track density Areal density (max) Formatted capacity Value 6 12 512 bytes 11 15,110 352,000 bits/in. 20,000 tracks/in. 7040 Mbits/sq. in. 36 GBbytes Performance attribute Rotational rate Avg. rotational latency Avg. seek time Sustained transfer rate Value 10,000 RPM 2.99 ms 4.9 ms 21–36 MBytes/s Figure 6.13: IBM Ultrastar 36LZX geometry and performance. Source: www.storage.ibm.com Disk manufacturers often neglect to publish detailed technical information about the geometry of the individual recording zones. However, storage researchers have developed a useful tool, called DIXtrac, that automatically discovers a wealth of low-level information about the geometry and performance of SCSI disks [64]. For example, 6.1. STORAGE TECHNOLOGIES DIXtrac is able to discover the detailed zone geometry of our example IBM disk, which we’ve shown in Figure 6.14. Each row in the table characterizes one of the 11 zones on the disk surface, in terms of the number of sectors in the zone, the range of logical blocks mapped to the sectors in the zone, and the range and number of cylinders in the zone. Zone number (outer) 0 1 2 3 4 5 6 7 8 9 (inner) 10 Sectors per track 504 476 462 420 406 392 378 364 352 336 308 Starting logical block 0 2,292,097 11,949,752 19,416,567 36,409,690 39,844,152 46,287,904 52,201,830 56,691,916 60,087,819 67,001,920 Ending logical block 2,292,096 11,949,751 19,416,566 36,409,689 39,844,151 46,287,903 52,201,829 56,691,915 60,087,818 67,001,919 71,687,339 Starting cylinder 1 381 2,079 3,431 6,816 7,524 8,899 10,208 11,240 12,047 13,769 Ending cylinder 380 2,078 3,430 6,815 7,523 8,898 10,207 11,239 12,046 13,768 15,042 Cylinders per zone 380 1,698 1,352 3,385 708 1,375 1,309 1,032 807 1,722 1,274 293 Figure 6.14: IBM Ultrastar 36LZX zone map. Source: DIXtrac automatic disk drive characterization tool [64]. The zone map confirms some interesting facts about the IBM disk. First, more tracks are packed into the outer zones (which have a larger circumference) than the inner zones. Second, each zone has more sectors than logical blocks (check this yourself). The unused sectors form a pool of spare cylinders. If the recording material on a sector goes bad, the disk controller will automatically and transparently remap the logical blocks on that cylinder to an available spare. So we see that the notion of a logical block not only provides a simpler interface to the operating system, it also provides a level of indirection that enables the disk to be more robust. This general idea of indirection is very powerful, as we will see when we study virtual memory in Chapter 10. End Aside. 6.1.3 Storage Technology Trends There are several important concepts to take away from our discussion of storage technologies. ¯ ¯ Different storage technologies have different price and performance tradeoffs. SRAM is somewhat faster than DRAM, and DRAM is much faster than disk. On the other hand, fast storage is always more expensive than slower storage. SRAM costs more per byte than DRAM. DRAM costs much more than disk. The price and performance properties of different storage technologies are changing at dramatically different rates. Figure 6.15 summarizes the price and performance properties of storage technologies since 1980, when the first PCs were introduced. The numbers were culled from back issues of trade magazines. Although they were collected in an informal survey, the numbers reveal some interesting trends. Since 1980, both the cost and performance of SRAM technology have improved at roughly the same rate. Access times have decreased by a factor of about 100 and cost per megabyte by a factor of 200 (Figure 6.15(a)). However, the trends for DRAM and disk are much more dramatic and divergent. 294 CHAPTER 6. THE MEMORY HIERARCHY While the cost per megabyte of DRAM has decreased by a factor of 8000 (almost four orders of magnitude!), DRAM access times have decreased by only a factor of 6 or so (Figure 6.15(b)). Disk technology has followed the same trend as DRAM and in even more dramatic fashion. While the cost of a megabyte of disk storage has plummeted by a factor of 50,000 since 1980, access times have improved much more slowly, by only a factor of 10 or so (Figure 6.15(c)). These startling long-term trends highlight a basic truth of memory and disk technology: it is easier to increase density (and thereby reduce cost) than to decrease access time. Metric $/MB Access (ns) 1980 19,200 300 1985 2,900 150 1990 320 35 1995 256 15 2000 100 3 2000:1980 190 100 (a) SRAM trends Metric $/MB Access (ns) Typical size (MB) 1980 8,000 375 0.064 1985 880 200 0.256 1990 100 100 4 1995 30 70 16 2000 1 60 64 2000:1980 8,000 6 1,000 (b) DRAM trends Metric $/MB seek time (ms) typical size (MB) 1980 500 87 1 1985 100 75 10 1990 8 28 160 1995 0.30 10 1,000 2000 0.01 8 20,000 2000:1980 50,000 11 20,000 (c) Disk trends Metric Intel CPU CPU clock rate (MHz) CPU cycle time (ns) 1980 8080 1 1,000 1985 80286 6 166 1990 80386 20 50 1995 Pentium 150 6 2000 P-III 600 1.6 2000:1980 — 600 600 (d) CPU trends Figure 6.15: Storage and processing technology trends. ¯ DRAM and disk access times are lagging behind CPU cycle times. As we see in Figure 6.15(d), CPU cycle times improved by a factor of 600 between 1980 and 2000. While SRAM performance lags, it is roughly keeping up. However, the gap between DRAM and disk performance and CPU performance is actually widening. The various trends are shown quite clearly in Figure 6.16, which plots the access and cycle times from Figure 6.15 on a semi-log scale. As we will see in Section 6.4, modern computers make heavy use of SRAM-based caches to try to bridge the processor-memory gap. This approach works because of a fundamental property of application programs known as locality, which we discuss next. 6.2. LOCALITY 100,000,000 10,000,000 1,000,000 100,000 ns 10,000 1,000 100 10 1 1980 1985 1990 Year 1995 2000 Disk seek time DRAM access time SRAM access time CPU cycle time 295 Figure 6.16: The increasing gap between DRAM, disk, and CPU speeds. 6.2 Locality Well-written computer programs tend to exhibit good locality. That is, they tend to reference data items that are near other recently referenced data items, or that were recently referenced themselves. This tendency, known as the principle of locality, is an enduring concept that has enormous impact on the design and performance of hardware and software systems. Locality is typically described as having two distinct forms: temporal locality and spatial locality. In a program with good temporal locality, a memory location that is referenced once is likely to be referenced again multiple times in the near future. In a program with good spatial locality, if a memory location is referenced once, then the program is likely to reference a nearby memory location in the near future. Programmers should understand the principle of locality because, in general, programs with good locality run faster than programs with poor locality. All levels of modern computer systems, from the hardware, to the operating system, to application programs, are designed to exploit locality. At the hardware level, the principle of locality allows computer designers to speed up main memory accesses by introducing small fast memories known as cache memories that hold blocks of the most recently referenced instructions and data items. At the operating system level, the principle of locality allows the system to use the main memory as a cache of the most recently referenced chunks of the virtual address space. Similarly, the operating system uses main memory to cache the most recently used disk blocks in the disk file system. The principle of locality also plays a crucial role in the design of application programs. For example, Web browsers exploit temporal locality by caching recently referenced documents on a local disk. High volume Web servers hold recently requested documents in front-end disk caches that satisfy requests for these documents without requiring any intervention from the server. 6.2.1 Locality of References to Program Data Consider the simple function in Figure 6.17(a) that sums the elements of a vector. Does this function have good locality? To answer this question, we look at the reference pattern for each variable. In this example, the sum variable is referenced once in each loop iteration, and thus there is good temporal locality with respect to sum. On the other hand, since sum is a scalar, there is no spatial locality with respect to sum. 296 1 2 3 4 5 6 7 8 CHAPTER 6. THE MEMORY HIERARCHY int sumvec(int v[N]) { int i, sum = 0; for (i = 0; i < N; i++) sum += v[i]; return sum; } Address Contents Access order 0 Ú¼ 4 Ú½ 8 Ú¾ 12 Ú¿ 16 Ú 20 Ú 24 Ú 28 Ú 1 2 3 4 5 6 7 8 (a) (b) ). Notice how Figure 6.17: (a) A function with good locality. (b) Reference pattern for vector v (Æ the vector elements are accessed in the same order that they are stored in memory. As we see in Figure 6.17(b), the elements of vector v are read sequentially, one after the other, in the order they are stored in memory (we assume for convenience that the array starts at address 0). Thus, with respect to variable v, the function has good spatial locality, but poor temporal locality since each vector element is accessed exactly once. Since the function has either good spatial or temporal locality with respect to each variable in the loop body, we can conclude that the sumvec function enjoys good locality. A function such as sumvec that visits each element of a vector sequentially is said to have a stride-1 reference pattern (with respect to the element size). Visiting every Ø element of a contiguous vector is called a stride- reference pattern. Stride-1 reference patterns are a common and important source of spatial locality in programs. In general, as the stride increases, the spatial locality decreases. Stride is also an important issue for programs that reference multidimensional arrays. Consider the sumarrayrows function in Figure 6.18(a) that sums the elements of a two-dimensional array. The doubly nested loop reads the elements of the array in row-major order. That is, the inner loop reads the elements of the first row, then the second row, and so on. The sumarrayrows function enjoys good spatial locality because 1 2 3 4 5 6 7 8 9 int sumarrayrows(int a[M][N]) { int i, j, sum = 0; for (i = 0; i < M; i++) for (j = 0; j < N; j++) sum += a[i][j]; return sum; } Address Contents Access order 0 ¼¼ 4 ¼½ 8 ¼¾ 12 ½¼ 16 ½½ 20 ½¾ 1 2 3 4 5 6 (a) (b) Figure 6.18: (a) Another function with good locality. (b) Reference pattern for array a (Å ¾, Æ ¿). There is good spatial locality because the array is accessed in the same row-major order that it is stored in memory. it references the array in the same row-major order that the array is stored (Figure 6.18(b)). The result is a nice stride-1 reference pattern with excellent spatial locality. 6.2. LOCALITY 297 Seemingly trivial changes to a program can have a big impact on its locality. For example, the sumarraycols function in Figure 6.19(a) computes the same result as the sumarrayrows function in Figure 6.18(a). The only difference is that we have interchanged the and loops. What impact does interchanging the loops have on its locality? The sumarraycols function suffers from poor spatial locality 1 2 3 4 5 6 7 8 9 int sumarraycols(int a[M][N]) { int i, j, sum = 0; for (j = 0; j < N; j++) for (i = 0; i < M; i++) sum += a[i][j]; return sum; } Address Contents Access order 0 ¼¼ 4 ¼½ 8 ¼¾ 12 ½¼ 16 ½½ 20 ½¾ 1 3 5 2 4 6 (a) (b) Figure 6.19: (a) A function with poor spatial locality. (b) Reference pattern for array a (Å ¿). The function has poor spatial locality because it scans memory with a stride-´Æ ¢ × Þ Ó ´ reference pattern. Æ Òصµ ¾ , because it scans the array column-wise instead of row-wise. Since C arrays are laid out in memory row-wise, the result is a stride-(Æ ¢ × Þ Ó ´ Òصµ reference pattern, as shown in Figure 6.19(b). 6.2.2 Locality of Instruction Fetches Since program instructions are stored in memory and must be fetched (read) by the CPU, we can also evaluate the locality of a program with respect to its instruction fetches. For example, in Figure 6.17 the instructions in the body of the for loop are executed in sequential memory order, and thus the loop enjoys good spatial locality. Since the loop body is executed multiple times, it also enjoys good temporal locality. An important property of code that distinguishes it from program data is that it can not be modified at runtime. While a program is executing, the CPU only reads its instructions from memory. The CPU never overwrites or modifies these instructions. 6.2.3 Summary of Locality In this section we have introduced the fundamental idea of locality and we have identified some simple rules for qualitatively evaluating the locality in a program: ¯ ¯ Programs that repeatedly reference the same variables enjoy good temporal locality. For programs with stride- reference patterns, the smaller the stride the better the spatial locality. Programs with stride-1 reference patterns have good spatial locality. Programs that hop around memory with large strides have poor spatial locality. 298 CHAPTER 6. THE MEMORY HIERARCHY ¯ Loops have good temporal and spatial locality with respect to instruction fetches. The smaller the loop body and the greater the number of loop iterations, the better the locality. Later in this chapter, after we have learned about cache memories and how they work, we will show you how to quantify the idea of locality in terms of cache hits and misses. It will also become clear to you why programs with good locality typically run faster than programs with poor locality. Nonetheless, knowing how to glance at a source code and getting a high-level feel for the locality in the program is a useful and important skill for a programmer to master. Practice Problem 6.4: Permute the loops in the following function so that it scans the three-dimensional array with a stride-1 reference pattern. 1 2 3 4 5 6 7 8 9 10 11 12 13 int sumarray3d(int a[N][N][N]) { int i, j, k, sum = 0; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { for (k = 0; k < N; k++) { sum += a[k][i][j]; } } } return sum; } Practice Problem 6.5: The three functions in Figure 6.20 perform the same operation with varying degrees of spatial locality. Rank-order the functions with respect to the spatial locality enjoyed by each. Explain how you arrived at your ranking. 6.3 The Memory Hierarchy Sections 6.1 and 6.2 described some fundamental and enduring properties of storage technology and computer software: ¯ ¯ Different storage technologies have widely different access times. Faster technologies cost more per byte than slower ones and have less capacity. The gap between CPU and main memory speed is widening. Well-written programs tend to exhibit good locality. 6.3. THE MEMORY HIERARCHY 299 1 2 3 4 5 6 7 8 #define N 1000 typedef struct { int vel[3]; int acc[3]; } point; point p[N]; 1 2 3 4 5 6 7 8 9 10 11 void clear1(point *p, int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < 3; j++) p[i].vel[j] = 0; for (j = 0; j < 3; j++) p[i].acc[j] = 0; } } (a) An array of structs. 1 2 3 4 5 6 7 8 9 10 11 (b) The clear1 function. 1 2 3 4 5 6 7 8 9 10 11 void clear2(point *p, int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < 3; j++) { p[i].vel[j] = 0; p[i].acc[j] = 0; } } } void clear3(point *p, int n) { int i, j; for (j = 0; j < 3; j++) { for (i = 0; i < n; i++) p[i].vel[j] = 0; for (i = 0; i < n; i++) p[i].acc[j] = 0; } } (a) The clear2 function. (b) The clear3 function. Figure 6.20: Code examples for Practice Problem 6.5. 300 CHAPTER 6. THE MEMORY HIERARCHY In one of the happier coincidences of computing, these fundamental properties of hardware and software complement each other beautifully. Their complementary nature suggests an approach for organizing memory systems, known as the memory hierarchy, that is used in all modern computer systems. Figure 6.21 shows a typical memory hierarchy. In general, the storage devices get faster, cheaper, and larger as we move Smaller, faster, and costlier (per byte) storage devices L0: registers L1: L2: on-chip L1 cache (SRAM) off-chip L2 cache (SRAM) main memory (DRAM) CPU registers hold words retrieved from cache memory. L1 cache holds cache lines retrieved from the L2 cache. L2 cache holds cache lines retrieved from memory. L3: Larger, slower, and cheaper (per byte) storage devices Main memory holds disk blocks retrieved from local disks. L4: local secondary storage (local disks) Local disks hold files retrieved from disks on remote network servers. L5: remote secondary storage (distributed file systems, Web servers) Figure 6.21: The memory hierarchy. from higher to lower levels. At the highest level (L0) are a small number of fast CPU registers that the CPU can access in a single clock cycle. Next are one or more small to moderate-sized SRAM-based cache memories that can be accessed in a few CPU clock cycles. These are followed by a large DRAM-based main memory that can be accessed in tens to hundreds of clock cycles. Next are slow but enormous local disks. Finally, some systems even include an additional level of disks on remote servers that can be accessed over a network. For example, distributed file systems such as the Andrew File System (AFS) or the Network File System (NFS) allow a program to access files that are stored on remote network-connected servers. Similarly, the World Wide Web allows programs to access remote files stored on Web servers anywhere in the world. Aside: Other memory hierarchies. We have shown you one example of a memory hierarchy, but other combinations are possible, and indeed common. For example, many sites back up local disks onto archival magnetic tapes. At some of these sites, human operators manually mount the tapes onto tape drives as needed. At other sites, tape robots handle this task automatically. In either case, the collection of tapes represents a level in the memory hierarchy, below the local disk level, and the same general principles apply. Tapes are cheaper per byte than disks, which allows sites to archive multiple snapshots of their local disks. The tradeoff is that tapes take longer to access than disks. End Aside. 6.3. THE MEMORY HIERARCHY 301 6.3.1 Caching in the Memory Hierarchy In general, a cache (pronounced “cash”) is a small, fast storage device that acts as a staging area for the data objects stored in a larger, slower device. The process of using a cache is known as caching (pronounced “cashing”). The central idea of a memory hierarchy is that for each , the faster and smaller storage device at level serves as a cache for the larger and slower storage device at level · ½. In other words, each level in the hierarchy caches data objects from the next lower level. For example, the local disk serves as a cache for files (such as Web pages) retrieved from remote disks over the network, the main memory serves as a cache for data on the local disks, and so on, until we get to the smallest cache of all, the set of CPU registers. Figure 6.22 shows the general concept of caching in a memory hierarchy. The storage at level · ½ is partitioned into contiguous chunks of data objects called blocks. Each block has a unique address or name that distinguishes it from other blocks. Blocks can be either fixed-size (the usual case) or variable-sized (e.g., the remote HTML files stored on Web servers). For example, the level- · ½ storage in Figure 6.22 is partitioned into 16 fixed-sized blocks, numbered 0 to 15. Smaller, faster, more expensive device at level k caches a subset of the blocks from level k+1 Level k: 4 9 14 3 Data is copied between levels in block-sized transfer units 0 Level k+1: 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15 Larger, slower, cheaper storage device at level k+1 is partitioned into blocks. Figure 6.22: The basic principle of caching in a memory hierarchy. Similarly, the storage at level is partitioned into a smaller set of blocks that are the same size as the blocks at level · ½. At any point in time, the cache at level contains copies of a subset of the blocks from level · ½. For example, in Figure 6.22, the cache at level has room for four blocks and currently contains copies of blocks 4, 9, 14, and 3. Data is always copied back and forth between level and level · ½ in block-sized transfer units. It is important to realize that while the block size is fixed between any particular pair of adjacent levels in the hierarchy, other pairs of levels can have different block sizes. For example, in Figure 6.21, transfers between L1 and L0 typically use 1-word blocks. Transfers between L2 and L1 (and L3 and L2) typically use blocks of 4 to 8 words. And transfers between L4 and L3 use blocks with hundreds or thousands of bytes. In general, devices lower in the hierarchy (further from the CPU) have longer access times, and thus tend to use larger block sizes in order to amortize these longer access times. 302 CHAPTER 6. THE MEMORY HIERARCHY Cache Hits When a program needs a particular data object from level · ½, it first looks for in one of the blocks currently stored at level . If happens to be cached at level , then we have what is called a cache hit. The program reads directly from level , which by the nature of the memory hierarchy is faster than reading from level · ½. For example, a program with good temporal locality might read a data object from block 14, resulting in a cache hit from level . Cache Misses If, on the other hand, the data object is not cached at level , then we have what is called a cache miss. When there is a miss, the cache at level fetches the block containing from the cache at level · ½, possibly overwriting an existing block if the level cache is already full. This process of overwriting an existing block is known as replacing or evicting the block. The block that is evicted is sometimes referred to as a victim block. The decision about which block to replace is governed by the cache’s replacement policy. For example, a cache with a random replacement policy would choose a random victim block. A cache with a least-recently used (LRU) replacement policy would choose the block that was last accessed the furthest in the past. After the cache at level has fetched the block from level · ½, the program can read from level as before. For example, in Figure 6.22, reading a data object from block 12 in the level cache would result in a cache miss because block 12 is not currently stored in the level cache. Once it has been copied from level · ½ to level , block 12 will remain there in expectation of later accesses. Kinds of Cache Misses It is sometimes helpful to distinguish between different kinds of cache misses. If the cache at level is empty, then any access of any data object will miss. An empty cache is sometimes referred to as a cold cache, and misses of this kind are called compulsory misses or cold misses. Cold misses are important because they are often transient events that might not occur in steady state, after the cache has been warmed up by repeated memory accesses. Whenever there is a miss, the cache at level must implement some placement policy that determines where to place the block it has retrieved from level · ½. The most flexible placement policy is to allow any block from level · ½ to be stored in any block at level . For caches high in the memory hierarchy (close to the CPU) that are implemented in hardware and where speed is at a premium, this policy is usually too expensive to implement because randomly placed blocks are expensive to locate. Thus, hardware caches typically implement a more restricted placement policy that restricts a particular block at level · ½ to a small subset (sometimes a singleton) of the blocks at level . For example, in Figure 6.22, we might decide that a block at level · ½ must be placed in block ( mod 4) at level . For example, blocks 0, 4, 8, and 12 at level · ½ would map to block 0 at level , blocks 1, 5, 9, and 13 would map to block 1, and so on. Notice that our example cache in Figure 6.22 uses this policy. Restrictive placement policies of this kind lead to a type of miss known as a conflict miss, where the cache 6.3. THE MEMORY HIERARCHY 303 is large enough to hold the referenced data objects, but because they map to the same cache block, the cache keeps missing. For example, in Figure 6.22, if the program requests block 0, then block 8, then block 0, then block 8, and so on, each of the references to these two blocks would miss in the cache at level , even though this cache can hold a total of 4 blocks. Programs often run as a sequence of phases (e.g., loops) where each phase accesses some reasonably constant set of cache blocks. For example, a nested loop might access the elements of the same array over and over again. This set of blocks is called the working set of the phase. When the size of the working set exceeds the size of the cache, the cache will experience what are known as capacity misses. In other words, the cache is just too small to handle this particular working set. Cache Management As we have noted, the essence of the memory hierarchy is that the storage device at each level is a cache for the next lower level. At each level, some form of logic must manage the cache. By this we mean that something has to partition the cache storage into blocks, transfer blocks between different levels, decide when there are hits and misses, and then deal with them. The logic that manages the cache can be hardware, software, or a combination of the two. For example, the compiler manages the register file, the highest level of the cache hierarchy. It decides when to issue loads when there are misses, and determines which register to store the data in. The caches at levels L1 and L2 are managed entirely by hardware logic built into the caches. In a system with virtual memory, the DRAM main memory serves as a cache for data blocks stored on disk, and is managed by a combination of operating system software and address translation hardware on the CPU. For a machine with a distributed file system such as AFS, the local disk serves as a cache that is managed by the AFS client process running on the local machine. In most cases, caches operate automatically and do not require any specific or explicit actions from the program. 6.3.2 Summary of Memory Hierarchy Concepts To summarize, memory hierarchies based on caching work because slower storage is cheaper than faster storage and because programs tend to exhibit locality. ¯ ¯ Exploiting temporal locality. Because of temporal locality, the same data objects are likely to be reused multiple times. Once a data object has been copied into the cache on the first miss, we can expect a number of subsequent hits on that object. Since the cache is faster than the storage at the next lower level, these subsequent hits can be served much faster than the original miss. Exploiting spatial locality. Blocks usually contain multiple data objects. Because of spatial locality, we can expect that the cost of copying a block after a miss will be amortized by subsequent references to other objects within that block. Caches are used everywhere in modern systems. As you can see from Figure 6.23, caches are used in CPU chips, operating systems, distributed file systems, and on the World-Wide Web. They are built from and managed by various combinations of hardware and software. Note that there are a number of terms and 304 CHAPTER 6. THE MEMORY HIERARCHY acronyms in Figure 6.23 that we haven’t covered yet. We include them here to demonstrate how common caches are. Type CPU registers TLB L1 cache L2 cache Virtual memory Buffer cache Network buffer cache Browser cache Web cache What cached 4-byte word Address translations 32-byte block 32-byte block 4-KB page Parts of files Parts of files Web pages Web pages Where cached On-chip CPU registers On-chip TLB On-chip L1 cache Off-chip L2 cache Main memory Main memory Local disk Local disk Remote server disks Latency (cycles) 0 0 1 10 100 100 10,000,000 10,000,000 1,000,000,000 Managed by Compiler Hardware Hardware Hardware Hardware + OS OS AFS/NFS client Web browser Web proxy server Figure 6.23: The ubiquity of caching in modern computer systems. Acronyms: TLB: Translation Lookaside Buffer, MMU: Memory Management Unit, OS: Operating System, AFS: Andrew File System, NFS: Network File System. 6.4 Cache Memories The memory hierarchies of early computer systems consisted of only three levels: CPU registers, main DRAM memory, and disk storage. However, because of the increasing gap between CPU and main memory, system designers were compelled to insert a small SRAM memory, called an L1 cache (Level 1 cache), between the CPU register file and main memory. In modern systems, the L1 cache is located on the CPU chip (i.e., it is an on-chip cache), as shown in Figure 6.24. The L1 cache can be accessed nearly as fast as the registers, typically in one or two clock cycles. As the performance gap between the CPU and main memory continued to increase, system designers responded by inserting an additional cache, called an L2 cache, between the L1 cache and the main memory, that can be accessed in a few clock cycles. The L2 cache can be attached to the memory bus, or it can be attached to its own cache bus, as shown in Figure 6.24. Some high-performance systems, such as those based on the Alpha 21164, will even include an additional level of cache on the memory bus, called an L3 cache, which sits between the L2 cache and main memory in the hierarchy. While there is considerable variety in the arrangements, the general principles are the same. CPU chip register file L1 cache cache bus ALU system bus I/O bridge memory bus L2 cache bus interface Figure 6.24: Typical bus structure for L1 and L2 caches. 6.4. CACHE MEMORIES 305 6.4.1 Generic Cache Memory Organization Ñ Consider a computer system where each memory address has Ñ bits that form Å ¾ unique addresses. × As illustrated in Figure 6.25(a), a cache for such a machine is organized as an array of Ë ¾ cache sets. Each set consists of cache lines. Each line consists of a data block of ¾ bytes, a valid bit that indicates whether or not the line contains meaningful information, and Ø Ñ ´ · ×µ tag bits (a subset of the bits from the current block’s memory address) that uniquely identify the block stored in the cache line. 1 valid bit per line valid set 0: valid t tag bits per line tag tag 0 ••• 0 B = 2b bytes per cache block 1 1 ••• ••• B–1 E lines per set B–1 B–1 B–1 valid tag tag 0 ••• 0 ••• 1 1 ••• ••• S = 2s sets set 1: valid valid set S-1: valid tag tag 0 ••• 0 1 1 ••• ••• B–1 B–1 Cache size: C = B x E x S data bytes (a) t bits s bits b bits 0 Address: m-1 tag set index block offset (b) Figure 6.25: General organization of cache ´Ë ѵ. (a) A cache is an array of sets. Each set contains one or more lines. Each line contains a valid bit, some tag bits, and a block of data. (b) The cache organization induces a partition of the Ñ address bits into Ø tag bits, × set index bits, and block offset bits. In general, a cache’s organization can be characterized by the tuple ´Ë ѵ. The size (or capacity) of a cache, , is stated in terms of the aggregate size of all the blocks. The tag bits and valid bit are not included. Thus, Ë¢ ¢ . When the CPU is instructed by a load instruction to read a word from address of main memory, it sends the address to the cache. If the cache is holding a copy of the word at address , it sends the word immediately back to the CPU. So how does the cache know whether it contains a copy of the word at address ? The cache is organized so that it can find the requested word by simply inspecting the bits of the address, similar to a hash table with an extremely simple hash function. Here is how it works. 306 CHAPTER 6. THE MEMORY HIERARCHY The parameters Ë and induce a partitioning of the Ñ address bits into the three fields shown in Figure 6.25(b). The × set index bits in form an index into the array of Ë sets. The first set is set 0, the second set is set 1, and so on. When interpreted as an unsigned integer, the set index bits tell us which set the word must be stored in. Once we know which set the word must be contained in, the Ø tag bits in tell us which line (if any) in the set contains the word. A line in the set contains the word if and only if the valid bit is set and the tag bits in the line match the tag bits in the address . Once we have located the line identified by the tag in the set identified by the set index, then the block offset bits give us the offset of the word in the -byte data block. As you may have noticed, descriptions of caches use a lot of symbols. Figure 6.26 summarizes these symbols for your reference. Parameter Ë ¾× ¾ Ñ ÐÓ ¾ ´Å µ Fundamental parameters Description Number of sets Number of lines per set Block size (bytes) Number of physical (main memory) address bits Derived quantities Parameter Å × ¾Ñ ÐÓ ¾ ´Ë µ ÐÓ ¾ ´ µ Ñ ´× · µ Ø ¢¢ Ë Description Maximum number of unique memory addresses Number of set index bits Number of block offset bits Number of tag bits Cache size (bytes) not including overhead such as the valid and tag bits Figure 6.26: Summary of cache parameters. Practice Problem 6.6: The following table gives the parameters for a number of different caches. For each cache, determine the number of cache sets (Ë ), tag bits (Ø), set index bits (×), and block offset bits ( ). Cache 1. 2. 3. Ñ Ë Ø × 32 32 32 1024 1024 1024 4 8 32 1 4 32 6.4.2 Direct-Mapped Caches Caches are grouped into different classes based on , the number of cache lines per set. A cache with exactly one line per set ( ½) is known as a direct-mapped cache (see Figure 6.27). Direct-mapped 6.4. CACHE MEMORIES set 0: set 1: valid valid tag tag ••• set S-1: valid tag cache block cache block cache block 307 E=1 lines per set Figure 6.27: Direct-mapped cache ( ½ ). There is exactly one line per set. caches are the simplest both to implement and to understand, so we will use them to illustrate some general concepts about how caches work. Suppose we have a system with a CPU, a register file, an L1 cache, and a main memory. When the CPU executes an instruction that reads a memory word Û, it requests the word from the L1 cache. If the L1 cache has a cached copy of Û, then we have an L1 cache hit, and the cache quickly extracts Û and returns it to the CPU. Otherwise, we have a cache miss and the CPU must wait while the L1 cache requests a copy of the block containg Û from the main memory. When the requested block finally arrives from memory, the L1 cache stores the block in one of its cache lines, extracts word Û from the stored block, and returns it to the CPU. The process that a cache goes through of determining whether a request is a hit or a miss, and then extracting the requested word consists of three steps: (1) set selection, (2) line matching, and (3) word extraction. Set Selection in Direct-Mapped Caches In this step, the cache extracts the × set index bits from the middle of the address for Û. These bits are interpreted as an unsigned integer that corresponds to a set number. In other words, if we think of the cache as a one-dimensional array of sets, then the set index bits form an index into this array. Figure 6.28 shows how set selection works for a direct-mapped cache. In this example, the set index bits ¼¼¼¼½¾ are interpreted as an integer index that selects set 1. set 0: selected set set 1: valid valid tag tag ••• t bits m-1 cache block cache block tag s bits b bits 00 001 set index block offset set S-1: 0 valid tag cache block Figure 6.28: Set selection in a direct-mapped cache. Line Matching in Direct-Mapped Caches Now that we have selected some set in the previous step, the next step is to determine if a copy of the word Û is stored in one of the cache lines contained in set . In a direct-mapped cache, this is easy and fast because there is exactly one line per set. A copy of Û is contained in the line if and only if the valid bit is 308 CHAPTER 6. THE MEMORY HIERARCHY set and the tag in the cache line matches the tag in the address of Û. Figure 6.29 shows how line matching works in a direct-mapped cache. In this example, there is exactly one cache line in the selected set. The valid bit for this line is set, so we know that the bits in the tag and block are meaningful. Since the tag bits in the cache line match the tag bits in the address, we know that a copy of the word we want is indeed stored in the line. In other words, we have a cache hit. On the other hand, if either the valid bit were not set or the tags did not match, then we would have had a cache miss. =1? (1) The valid bit must be set 0 1 2 3 4 5 6 7 selected set (i): 1 0110 w0 w1 w2 w3 (2) The tag bits in the cache =? line must match the tag bits in the address t bits 0110 tag s bits b bits i 100 set index block offset (3) If (1) and (2), then cache hit, and block offset selects starting byte. 0 m-1 Figure 6.29: Line matching and word selection in a direct-mapped cache. Within the cache block, denotes the low-order byte of the word Û, Û½ the next byte, and so on. Û¼ Word Selection in Direct-Mapped Caches Once we have a hit, we know that Û is somewhere in the block. This last step determines where the desired word starts in the block. As shown in Figure 6.29, the block offset bits provide us with the offset of the first byte in the desired word. Similar to our view of a cache as an array of lines, we can think of a block as an array of bytes, and the byte offset as an index into that array. In the example, the block offset bits of ½¼¼¾ indicate that the copy of Û starts at byte 4 in the block. (We are assuming that words are 4 bytes long.) Line Replacement on Misses in Direct-Mapped Caches If the cache misses, then it needs to retrieve the requested block from the next level in the memory hierarchy and store the new block in one of the cache lines of the set indicated by the set index bits. In general, if the set is full of valid cache lines, then one of the existing lines must be evicted. For a direct-mapped cache, where each set contains exactly one line, the replacement policy is trivial: the current line is replaced by the newly fetched line. Putting it Together: A Direct-Mapped Cache in Action The mechanisms that a cache uses to select sets and identify lines are extremely simple. They have to be, because the hardware must perform them in only a few nanoseconds. However, manipulating bits in this way can be confusing to us humans. A concrete example will help clarify the process. Suppose we have a direct-mapped cache where ´ Ë Ñµ ´ ½¾ µ 6.4. CACHE MEMORIES 309 In other words, the cache has four sets, one line per set, 2 bytes per block, and 4-bit addresses. We will also assume that each word is a single byte. Of course, these assumptions are totally unrealistic, but they will help us keep the example simple. When you are first learning about caches, it can be very instructive to enumerate the entire address space and partition the bits, as we’ve done in Figure 6.30 for our 4-bit example. There are some interesting things Address (decimal equivalent) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Tag bits (Ø ½) 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 Address bits Index bits Offset bits (× ¾) ( ½) 00 0 00 1 01 0 01 1 10 0 10 1 11 0 11 1 00 0 00 1 01 0 01 1 10 0 10 1 11 0 11 1 Block number 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 Figure 6.30: 4-bit address for example direct-mapped cache to notice about this enumerated space. ¯ ¯ ¯ The concatenation of the tag and index bits uniquely identifies each block in memory. For example, block 0 consists of addresses 0 and 1, block 1 consists of addresses 2 and 3, block 2 consists of addresses 4 and 5, and so on. Since there are eight memory blocks but only four cache sets, multiple blocks map to the same cache set (i.e., they have the same set index). For example, blocks 0 and 4 both map to set 0, blocks 1 and 5 both map to set 1, and so on. Blocks that map to the same cache set are uniquely identified by the tag. For example, block 0 has a tag bit of 0 while block 4 has a tag bit of 1, block 1 has a tag bit of 0 while block 5 has a tag bit of 1. Let’s simulate the cache in action as the CPU performs a sequence of reads. Remember that for this example, we are assuming that the CPU reads 1-byte words. While this kind of manual simulation is tedious and you may be tempted to skip it, in our experience, students do not really understand how caches work until they work their way through a few of them. Initially, the cache is empty (i.e., each valid bit is 0). 310 set 0 1 2 3 valid 0 0 0 0 tag CHAPTER 6. THE MEMORY HIERARCHY block[0] block[1] Each row in the table represents a cache line. The first column indicates the set that the line belongs to, but keep in mind that this is provided for convenience and is not really part of the cache. The next three columns represent the actual bits in each cache line. Now let’s see what happens when the CPU performs a sequence of reads: 1. Read word at address 0. Since the valid bit for set 0 is zero, this is a cache miss. The cache fetches block 0 from memory (or a lower-level cache) and stores the block in set 0. Then the cache returns m[0] (the contents of memory location 0) from block[0] of the newly fetched cache line. set 0 1 2 3 valid 1 0 0 0 tag 0 block[0] m[0] block[1] m[1] 2. Read word at address 1. This is a cache hit. The cache immediately returns m[1] from block[1] of the cache line. The state of the cache does not change. 3. Read word at address 13. Since the cache line in set 2 is not valid, this is a cache miss. The cache loads block 6 into set 2 and returns m[13] from block[1] of the new cache line. set 0 1 2 3 valid 1 0 1 0 tag 0 1 block[0] m[0] m[12] block[1] m[1] m[13] 4. Read word at address 8. This is a miss. The cache line in set 0 is indeed valid, but the tags do not match. The cache loads block 4 into set 0 (replacing the line that was there from the read of address 0) and returns m[8] from block[0] of the new cache line. set 0 1 2 3 valid 1 0 1 0 tag 1 1 block[0] m[8] m[12] block[1] m[9] m[13] 5. Read word at address 0. This is another miss, due to the unfortunate fact that we just replaced block 0 during the previous reference to address 8. This kind of miss, where we have plenty of room in the cache but keep alternating references to blocks that map to the same set, is an example of a conflict miss. 6.4. CACHE MEMORIES set 0 1 2 3 valid 1 0 1 0 tag 0 1 block[0] m[0] m[12] block[1] m[1] m[13] 311 Conflict Misses in Direct-Mapped Caches Conflict misses are common in real programs and can cause baffling performance problems. Conflict misses in direct-mapped caches typically occur when programs access arrays whose sizes are a power of two. For example, consider a function that computes the dot product of two vectors: 1 2 3 4 5 6 7 8 9 float dotprod(float x[8], float y[8]) { float sum = 0.0; int i; for (i = 0; i < 8; i++) sum += x[i] * y[i]; return sum; } This function has good spatial locality with respect to x and y, and so we might expect it to enjoy a good number of cache hits. Unfortunately, this is not always true. Suppose that floats are 4 bytes, that x is loaded into the 32 bytes of contiguous memory starting at address 0, and that y starts immediately after x at address 32. For simplicity, suppose that a block is 16 bytes (big enough to hold four floats) and that the cache consists of two sets, for a total cache size of 32 bytes. We will assume that the variable sum is actually stored in a CPU register and thus doesn’t require a memory reference. Given these assumptions, each x[i] and y[i] will map to the identical cache set: Element x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] Address 0 4 8 12 16 20 24 28 Set index 0 0 0 0 1 1 1 1 Element y[0] y[1] y[2] y[3] y[4] y[5] y[6] y[7] Address 32 36 40 44 48 52 56 60 Set index 0 0 0 0 1 1 1 1 At runtime, the first iteration of the loop references x[0], a miss that causes the block containing x[0] – x[3] to be loaded into set 0. The next reference is to y[0], another miss that causes the block containing y[0]–y[3] to be copied into set 0, overwriting the values of x that were copied in by the previous reference. During the next iteration, the reference to x[1] misses, which causes the x[0]–x[3] block to be 312 CHAPTER 6. THE MEMORY HIERARCHY loaded back into set 0, overwriting the y[0]–y[3] block. So now we have a conflict miss, and in fact each subsequent reference to x and y will result in a conflict miss as we thrash back and forth between blocks of x and y. The term thrashing describes any situation where a cache is repeatedly loading and evicting the same sets of cache blocks. The bottom line is that even though the program has good spatial locality and we have room in the cache to hold the blocks for both x[i] and y[i], each reference results in a conflict miss because the blocks map to the same cache set. It is not unusual for this kind of thrashing to result in a slowdown by a factor of 2 or 3. And be aware that even though our example is extremely simple, the problem is real for larger and more realistic direct-mapped caches. Luckily, thrashing is easy for programmers to fix once they recognize what is going on. One easy solution is to put bytes of padding at the end of each array. For example, instead of defining x to be float x[8], we define it to be float x[12]. Assuming y starts immediately after x in memory, we have the following mapping of array elements to sets: Element x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] Address 0 4 8 12 16 20 24 28 Set index 0 0 0 0 1 1 1 1 Element y[0] y[1] y[2] y[3] y[4] y[5] y[6] y[7] Address 48 52 56 60 64 68 72 76 Set index 1 1 1 1 0 0 0 0 With the padding at the end of x, x[i] and y[i] now map to different sets, which eliminates the thrashing conflict misses. Practice Problem 6.7: In the previous dotprod example, what fraction of the total references to x and y will be hits once we have padded array x? Why Index With the Middle Bits? You may be wondering why caches use the middle bits for the set index instead of the high order bits. There is a good reason why the middle bits are better. Figure 6.31 shows why. If the high-order bits are used as an index, then some contiguous memory blocks will map to the same cache set. For example, in the figure, the first four blocks map to the first cache set, the second four blocks map to the second set, and so on. If a program has good spatial locality and scans the elements of an array sequentially, then the cache can only hold a block-sized chunk of the array at any point in time. This is an inefficient use of the cache. Contrast this with middle-bit indexing, where adjacent blocks always map to different cache lines. In this case, the cache can hold an entire -sized chunk of the array, where is the cache size. 6.4. CACHE MEMORIES High-Order Bit Indexing 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 set index bits 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Middle-Order Bit Indexing 313 4-set Cache 00 01 10 11 Figure 6.31: Why caches index with the middle bits. Practice Problem 6.8: In general, if the high-order × bits of an address are used as the set index, contiguous chunks of memory blocks are mapped to the same cache set. A. How many blocks are in each of these contiguous array chunks? B. Consider the following code that runs on a system with a cache of the form ´ ½¾ ½ ¿¾ ¿¾µ: int array[4096]; for (i = 0; i < 4096; i++) sum += array[i]; What is the maximum number of array blocks that are stored in the cache at any point in time? ´Ë ѵ 6.4.3 Set Associative Caches The problem with conflict misses in direct-mapped caches stems from the constraint that each set has exactly one line (or in our terminology, ½). A set associative cache relaxes this constraint so each set holds more than one cache line. A cache with ½ is often called an -way set associative cache. We will discuss the special case, where , in the next section. Figure 6.32 shows the organization of a two-way set associative cache. 314 valid valid valid valid tag tag tag tag ••• set S-1: valid valid tag tag CHAPTER 6. THE MEMORY HIERARCHY cache block cache block cache block cache block set 0: E=2 lines per set set 1: cache block cache block Figure 6.32: Set associative cache (½ ). In a set associative cache, each set contains more than one line. This particular example shows a 2-way set associative cache. Set Selection in Set Associative Caches Set selection is identical to a direct-mapped cache, with the set index bits identifying the set. Figure 6.33 summarizes this. set 0: valid valid valid valid tag tag tag tag ••• valid t bits m-1 cache block cache block cache block cache block Selected set set 1: tag tag cache block cache block tag s bits b bits 00 001 set index block offset set S-1: 0 valid Figure 6.33: Set selection in a set associative cache. Line Matching and Word Selection in Set Associative Caches Line matching is more involved in a set associative cache than in a direct-mapped cache because it must check the tags and valid bits of multiple lines in order to determine if the requested word is in the set. A conventional memory is an array of values that takes an address as input and returns the value stored at that address. An associative memory, on the other hand, is an array of (key,value) pairs that takes as input the key and returns a value from one of the (key,value) pairs that matches the input key. Thus, we can think of each set in a set associative cache as a small associative memory where the keys are the concatenation of the tag and valid bits, and the values are the contents of a block. Figure 6.34 shows the basic idea of line matching in an associative cache. An important idea here is that any line in the set can contain any of the memory blocks that map to that set. So the cache must search each line in the set, searching for a valid line whose tag matches the tag in the address. If the cache finds such a line, then we have a hit and the block offset selects a word from the block, as before. 6.4. CACHE MEMORIES =1? (1) The valid bit must be set. 0 1 2 3 4 5 6 7 315 1 selected set (i): 1 1001 0110 w0 w1 w2 w3 (2) The tag bits in one of the cache lines must match the tag bits in the address =? (3) If (1) and (2), then cache hit, and block offset selects starting byte. s bits b bits i 100 set index block offset m-1 t bits 0110 tag 0 Figure 6.34: Line matching and word selection in a set associative cache. Line Replacement on Misses in Set Associative Caches If the word requested by the CPU is not stored in any of the lines in the set, then we have a cache miss, and the cache must fetch the block that contains the word from memory. However, once the cache as retrieved the block, which line should it replace? Of course, if there is an empty line, then it would be a good candidate. But if there are no empty lines in the set, then we must choose one of them and hope that the CPU doesn’t reference the replaced line anytime soon. It is very difficult for programmers to exploit knowledge of the cache replacement policy in their codes, so we will not go into much detail. The simplest replacement policy is to choose the line to replace at random. Other more sophisticated policies draw on the principle of locality to try to minimize the probability that the replaced line will be referenced in the near future. For example, a least-frequently-used (LFU) policy will replace the line that has been referenced the fewest times over some past time window. A least-recently-used (LRU) policy will replace the line that was last accessed the furthest in the past. All of these policies require additional time and hardware. But as we move further down the memory hierarchy, away from the CPU, the cost of a miss becomes more expensive and it becomes more worthwhile to minimize misses with good replacement policies. 6.4.4 Fully Associative Caches A fully associative cache consists of a single set (i.e., Figure 6.35 shows the basic organization. valid set 0: valid valid tag tag ••• tag cache block cache block cache block ) that contains all of the cache lines. E = C/B lines in the one and only set Figure 6.35: Fully set associative cache ( of the lines. ). In a fully associative cache, a single set contains all 316 CHAPTER 6. THE MEMORY HIERARCHY Set Selection in Fully Associative Caches Set selection in a fully associative cache is trivial because there is only one set. Figure 6.36 summarizes. Notice that there are no set index bits in the address, which is partitioned into only a tag and a block offset. valid The entire cache is one set, so by default set 0 is always selected. t bits m-1 tag tag ••• tag cache block cache block cache block Set 0: valid valid b bits block offset 0 tag Figure 6.36: Set selection in a fully associative cache. Notice that there are no set index bits Line Matching and Word Selection in Fully Associative Caches Line matching and word selection in a fully associative cache work the same as with an associated cache, as we show in Figure 6.37. The difference is mainly a question of scale. Because the cache circuitry =1 ? (1) The valid bit must be set. 0 1 2 3 4 5 6 7 1 0 entire cache 1 0 1001 0110 0110 1110 w0 w1 w2 w3 (2) The tag bits in one of the cache lines must match the tag bits in the address =? t bits 0110 m-1 tag b bits 100 block offset (3) If (1) and (2), then cache hit, and block offset selects starting byte. 0 Figure 6.37: Line matching and word selection in a fully associative cache. must search for many matching tags in parallel, it is difficult and expensive to build an associative cache that is both large and fast. As a result, fully associative caches are only appropriate for small caches, such as the translation lookaside buffers (TLBs) in virtual memory systems that cache page table entries (Section 10.6.2). Practice Problem 6.9: The following problems will help reinforce your understanding of how caches work. Assume the following: ¯ ¯ The memory is byte addressable. Memory accesses are to 1-byte words (not 4-byte words). 6.4. CACHE MEMORIES 317 ¯ ¯ Addresses are 13 bits wide. The cache is 2-way set associative ( ¾), with a 4-byte block size ( ) and 8 sets (Ë ). The contents of the cache are as follows. All numbers are given in hexadecimal notation. 2-way Set Associative Cache Line 0 Line 1 Valid Byte 0 Byte 1 Byte 2 Byte 3 Tag Valid Byte 0 Byte 1 Byte 2 Byte 3 1 86 30 3F 10 00 0 – – – – 1 60 4F E0 23 38 1 00 BC 0B 37 0 – – – – 0B 0 – – – – 0 – – – – 32 1 12 08 7B AD 1 06 78 07 C5 05 1 40 67 C2 3B 1 0B DE 18 4B 6E 0 – – – – 1 A0 B7 26 2D F0 0 – – – – 0 – – – – DE 1 12 C0 88 37 Set Index 0 1 2 3 4 5 6 7 Tag 09 45 EB 06 C7 71 91 46 The box below shows the format of an address (one bit per box). Indicate (by labeling the diagram) the fields that would be used to determine the following: CO CI CT The cache block offset The cache set index The cache tag 12 11 10 9 8 7 6 5 4 3 2 1 0 Practice Problem 6.10: Suppose a program running on the machine in Problem 6.9 references the 1-byte word at address 0x0E34. Indicate the cache entry accessed and the cache byte value returned in hex. Indicate whether a cache miss occurs. If there is a cache miss, enter “–” for “Cache byte returned”. A. Address format (one bit per box): 12 11 10 9 8 7 6 5 4 3 2 1 0 B. Memory reference: Parameter Cache block offset (CO) Cache set index (CI) Cache tag (CT) Cache hit? (Y/N) Cache byte returned Value 0x 0x 0x 0x 318 Practice Problem 6.11: Repeat Problem 6.10 for memory address 0x0DD5. A. Address format (one bit per box): 12 11 10 9 8 7 6 CHAPTER 6. THE MEMORY HIERARCHY 5 4 3 2 1 0 B. Memory reference: Parameter Cache block offset (CO) Cache set index (CI) Cache tag (CT) Cache hit? (Y/N) Cache byte returned Value 0x 0x 0x 0x Practice Problem 6.12: Repeat Problem 6.10 for memory address 0x1FE4. A. Address format (one bit per box): 12 11 10 9 8 7 6 5 4 3 2 1 0 B. Memory reference: Parameter Cache block offset (CO) Cache set index (CI) Cache tag (CT) Cache hit? (Y/N) Cache byte returned Value 0x 0x 0x 0x Practice Problem 6.13: For the cache in Problem 6.9, list all of the hex memory addresses that will hit in Set 3. 6.4.5 Issues with Writes As we have seen, the operation of a cache with respect to reads is straightforward. First, look for a copy of the desired word Û in the cache. If there is a hit, return word Û to the CPU immediately. If there is a miss, fetch the block that contains word Û from memory, store the block in some cache line (possibly evicting a valid line), and then return word Û to the CPU. 6.4. CACHE MEMORIES 319 The situation for writes is a little more complicated. Suppose the CPU writes a word Û that is already cached (a write hit). After the cache updates its copy of Û, what does it do about updating the copy of Û in memory? The simplest approach, known as write-through, is to immediately write Û’s cache block to memory. While simple, write-through has the disadvantage of causing a write transaction on the bus with every store instruction. Another approach, known as write-back, defers the memory update as long as possible by writing the updated block to memory only when it is evicted from the cache by the replacement algorithm. Because of locality, write-back can significantly reduce the number of bus transactions, but it has the disadvantage of additional complexity. The cache must maintain an additional dirty bit for each cache line that indicates whether or not the cache block has been modified. Another issue is how to deal with write misses. One approach, known as write-allocate, loads the corresponding memory block into the cache and then updates the cache block. Write-allocate tries to exploit spatial locality of writes, but has the disadvantage that every miss results in a block transfer from memory to cache. The alternative, known as no-write-allocate, bypasses the cache and writes the word directly to memory. Write-through caches are typically no-write-allocate. Write-back caches are typically write-allocate. Optimizing caches for writes is a subtle and difficult issue, and we are only touching the surface here. The details vary from system to system and are often proprietary and poorly documented. To the programmer trying to write reasonably cache-friendly programs, we suggest adopting a mental model that assumes writeback write-allocate caches. There are several reasons for this suggestion. As a rule, caches at lower levels of the memory hierarchy are more likely to use write-back instead of write-through because of the larger transfer times. For example, virtual memory systems (which use main memory as a cache for the blocks stored on disk) use write-back exclusively. But as logic densities increase, the increased complexity of write-back is becoming less of an impediment and we are seeing write-back caches at all levels of modern systems. So this assumption matches current trends. Another reason for assuming a write-back write-allocate approach is that it is symmetric to the way reads are handled, in that write-back write-allocate tries to exploit locality. Thus, we can develop our programs at a high level to exhibit good spatial and temporal locality rather than trying to optimize for a particular memory system. 6.4.6 Instruction Caches and Unified Caches So far, we have assumed that caches hold only program data. But in fact, caches can hold instructions as well as data. A cache that holds instructions only is known as an i-cache. A cache that holds program data only is known as a d-cache. A cache that holds both instructions and data is known as a unified cache. A typical desktop systems includes an L1 i-cache and an L1 d-cache on the CPU chip itself, and a separate off-chip L2 unified cache. Figure 6.38 summarizes the basic setup. CPU Regs L1 d-cache L1 i-cache L2 Unified Cache Main Memory Disk Figure 6.38: A typical multi-level cache organization. 320 CHAPTER 6. THE MEMORY HIERARCHY Some higher-end systems, such as those based on the Alpha 21164, put the L1 and L2 caches on the CPU chip and have an additional off-chip L3 cache. Modern processors include separate on-chip i-caches and d-caches in order to improve performance. With two separate caches, the processor can read an instruction word and a data word during the same cycle. To our knowledge, no system incorporates an L4 cache, although as processor and memory speeds continue to diverge, it is likely to happen. Aside: What kind of cache organization does a real system have? Intel Pentium systems use the cache organization shown in Figure 6.38, with an on-chip L1 i-cache, an on-chip L1 d-cache, and an off-chip unified L2 cache. Figure 6.39 summarizes the basic parameters of these caches. End Aside. Cache type on-chip L1 i-cache on-chip L1 d-cache off-chip L2 unified cache Associativity ( ) 4 4 4 Block size ( ) 32 B 32 B 32 B Sets (Ë ) 128 128 1024–16384 Cache size ( ) 16 KB 16 KB 128 KB–2 MB Figure 6.39: Intel Pentium cache organization. 6.4.7 Performance Impact of Cache Parameters Cache performance is evaluated with a number of metrics: ¯ ¯ ¯ ¯ Miss rate. The fraction of memory references during the execution of a program, or a part of a program, that miss. It is computed as # misses # references. Hit rate. The fraction of memory references that hit. It is computed as ½ miss rate. Hit time. The time to deliver a word in the cache to the CPU, including the time for set selection, line identification, and word selection. Hit time is typically 1 to 2 clock cycle for L1 caches. Miss penalty. Any additional time required because of a miss. The penalty for L1 misses served from L2 is typically 5 to 10 cycles. The penalty for L1 misses served from main memory is typically 25 to 100 cycles. Optimizing the cost and performance trade-offs of cache memories is a subtle exercise that requires extensive simulation on realistic benchmark codes and is beyond our scope. However, it is possible to identify some of the qualitative tradeoffs. Impact of Cache Size On the one hand, a larger cache will tend to increase the hit rate. On the other hand, it is always harder to make big memories run faster. So larger caches tend to decrease the hit time. This is especially important for on-chip L1 caches that must have a hit time of one clock cycle. 6.4. CACHE MEMORIES 321 Impact of Block Size Large blocks are a mixed blessing. On the one hand, larger blocks can help increase the hit rate by exploiting any spatial locality that might exist in a program. However, for a given cache size, larger blocks imply a smaller number of cache lines, which can hurt the hit rate in programs with more temporal locality than spatial locality. Larger blocks also have a negative impact on the miss penalty, since larger blocks cause larger transfer times. Modern systems usually compromise with cache blocks that contain 4 to 8 words. Impact of Associativity The issue here is the impact of the choice of the parameter , the number of cache lines per set. The advantage of higher associativity (i.e., larger values of ) is that it decreases the vulnerability of the cache to thrashing due to conflict misses. However, higher associativity comes at a significant cost. Higher associativity is expensive to implement and hard to make fast. It requires more tag bits per line, additional LRU state bits per line, and additional control logic. Higher associativity can increase hit time, because of the increased complexity, and can also increase the miss penalty because of the increased complexity of choosing a victim line. The choice of associativity ultimately boils down to a trade-off between the hit time and the miss penalty. Traditionally, high-performance systems that pushed the clock rates would opt for direct-mapped L1 caches (where the miss penalty is only a few cycles) and a small degree of associativity (say 2 to 4) for the lower levels. But there are no hard and fast rules. In Intel Pentium systems, the L1 and L2 caches are all four-way set associative. In Alpha 21164 systems, the L1 instruction and data caches are direct-mapped, the L2 cache is three-way set associative, and the L3 cache is direct-mapped. Impact of Write Strategy Write-through caches are simpler to implement and can use a write buffer that works independently of the cache to update memory. Furthermore, read misses are less expensive because they do not trigger a memory write. On the other hand, write-back caches result in fewer transfers, which allows more bandwidth to memory for I/O devices that perform DMA. Further, reducing the number of transfers becomes increasingly important as we move down the hierarchy and the transfer times increase. In general, caches further down the hierarchy are more likely to use write-back than write-through. Aside: Cache lines, sets, and blocks: What’s the difference? It is easy to confuse the distinction between cache lines, sets, and blocks. Let’s review these ideas and make sure they are clear: ¯ ¯ ¯ A block is a fixed sized packet of information that moves back and forth between a cache and main memory (or a lower level cache). A line is a container in a cache that stores a block, as well as other information such as the valid bit and the tag bits. A set is a collection of one or more lines. Sets in direct-mapped caches consist of a single line. Sets in set associative and fully associative caches consist of multiple lines. 322 CHAPTER 6. THE MEMORY HIERARCHY In direct-mapped caches, sets and lines are indeed equivalent. However, in associative caches, sets and lines are very different things and the terms cannot be used interchangeably. Since a line always stores a single block, the terms “line” and “block” are often used interchangeably. For example, systems professionals usually refer to the “line size” of a cache, when what they really mean is the block size. This usage is very common, and shouldn’t cause any confusion, so long as you understand the distinction between blocks and lines. End Aside. 6.5 Writing Cache-friendly Code In Section 6.2 we introduced the idea of locality and talked in general terms about what constitutes good locality. But now that we understand how cache memories work, we can be more precise. Programs with better locality will tend to have lower miss rates, and programs with lower miss rates will tend to run faster than programs with higher miss rates. Thus, good programmers should always try to write code that is cache-friendly, in the sense that it has good locality. Here is the basic approach we use to try to ensure that our code is cache-friendly. 1. Make the common case go fast. Programs often spend most of their time in a few core functions. These functions often spend most of their time in a few loops. So focus on the inner loops of the core functions and ignore the rest. 2. Minimize the number of cache misses in each inner loop. All other things being equal, such as the total number of loads and stores, loops with better miss rates will run faster. To see how this works in practice, consider the sumvec function from Section 6.2. 1 2 3 4 5 6 7 8 int sumvec(int v[N]) { int i, sum = 0; for (i = 0; i < N; i++) sum += v[i]; return sum; } Is this function cache-friendly? First, notice that there is good temporal locality in the loop body with respect to the local variables i and sum. In fact, because these are local variables, any reasonable optimizing compiler will cache them in the register file, the highest level of the memory hierarchy. Now consider the stride-1 references to vector v. In general, if a cache has a block size of bytes, then a stride- reference pattern (where is in expressed in words) results in an average of Ñ Ò ´1 ´wordsize ¢ kµ Bµ misses per loop iteration. This is minimized for ½, so the stride-1 references to v are indeed cache-friendly. For example, suppose that v is block-aligned, words are 4-bytes, cache blocks are 4 words, and the cache is initially empty (a cold cache). Then regardless of the cache organization, the references to v will result in the following pattern of hits and misses: 6.5. WRITING CACHE-FRIENDLY CODE v[i] Access order, [h]it or [m]iss ¼ ½ ¾ ¿ 323 1 [m] 2 [h] 3 [h] 4 [h] 5 [m] 6 [h] 7 [h] 8 [h] In this example, the reference to v[0] misses and the corresponding block, which contains v[0]–v[3], is loaded into the cache from memory. Thus, the next three references are all hits. The reference to v[4] causes another miss as a new block is loaded into the cache, the next three references are hits, and so on. In general, three out of four references will hit, which is the best we can do in this case with a cold cache. To summarize, our simple sumvec example illustrates two important points about writing cache-friendly code: ¯ ¯ Repeated references to local variables are good because the compiler can cache them in the register file (temporal locality). Stride-1 reference patterns are good because caches at all levels of the memory hierarchy store data as contiguous blocks (spatial locality). Spatial locality is especially important in programs that operate on multidimensional arrays. For example, consider the sumarrayrows function from Section 6.2 that sums the elements of a two-dimensional array in row-major order. 1 2 3 4 5 6 7 8 9 int sumarrayrows(int a[M][N]) { int i, j, sum = 0; for (i = 0; i < M; i++) for (j = 0; j < N; j++) sum += a[i][j]; return sum; } Since C stores arrays in row-major order, the inner loop of this function has the same desirable stride-1 access pattern as sumvec. For example, suppose we make the same assumptions about the cache as for sumvec. Then the references to the array a will result in the following pattern of hits and misses: a[i][j] i=0 i=1 i=2 i=3 j=0 1 [m] 9 [m] 17 [m] 25 [m] j=1 2 [h] 10 [h] 18 [h] 26 [h] j=2 3 [h] 11 [h] 19 [h] 27 [h] j=3 4 [h] 12 [h] 20 [h] 28 [h] j=4 5 [m] 13 [m] 21 [m] 29 [m] j=5 6 [h] 14 [h] 22 [h] 30 [h] j=6 7 [h] 15 [h] 23 [h] 31 [h] j=7 8 [h] 16 [h] 24 [h] 32 [h] But consider what happens if we make the seemingly innocuous change of permuting the loops: 324 1 2 3 4 5 6 7 8 9 CHAPTER 6. THE MEMORY HIERARCHY int sumarraycols(int a[M][N]) { int i, j, sum = 0; for (j = 0; j < N; j++) for (i = 0; i < M; i++) sum += a[i][j]; return sum; } In this case we are scanning the array column by column instead of row by row. If we are lucky and the entire array fits in the cache, then we will enjoy the same miss rate of 1/4. However, if the array is larger than the cache (the more likely case), then each and every access of a[i][j] will miss! a[i][j] i=0 i=1 i=2 i=3 j=0 1 [m] 2 [m] 3 [m] 4 [m] j=1 5 [m] 6 [m] 7 [m] 8 [m] j=2 9 [m] 10 [m] 11 [m] 12 [m] j=3 13 [m] 14 [m] 15 [m] 16 [m] j=4 17 [m] 18 [m] 19 [m] 20 [m] j=5 21 [m] 22 [m] 23 [m] 24 [m] j=6 25 [m] 26 [m] 27 [m] 28 [m] j=7 29 [m] 30 [m] 31 [m] 32 [m] Higher miss rates can have a significant impact on running time. For example, on our desktop machine, sumarraycols runs in about 20 clock cycles per iteration, while sumarrayrows runs in about 10 cycles per iteration. To summarize, programmers should be aware of locality in their programs and try to write programs that exploit it. Practice Problem 6.14: Transposing the rows and columns of a matrix is an important problem in signal processing and scientific computing applications. It is also interesting from a locality point of view because its reference pattern is both row-wise and column-wise. For example, consider the following transpose routine: 1 2 3 4 5 6 7 8 9 10 11 12 typedef int array[2][2]; void transpose1(array dst, array src) { int i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { dst[j][i] = src[i][j]; } } } Assume this code runs on a machine with the following properties: ¯ sizeof(int) == 4. 6.5. WRITING CACHE-FRIENDLY CODE 325 ¯ ¯ ¯ ¯ The src array starts at address 0 and the dst array starts at address 16 (decimal). There is a single L1 data cache that is direct-mapped, write-through, and write-allocate, with a block size of 8 bytes. The cache has a total size of 16 data bytes and the cache is initially empty. Accesses to the src and dst arrays are the only sources of read and write misses, respectively. A. For each row and col, indicate whether the access to src[row][col] and dst[row][col] is a hit (h) or a miss (m). For example, reading src[0][0] is a miss and writing dst[0][0] is also a miss. dst array col 0 col 1 row 0 m row 1 src array col 0 col 1 row 0 m row 1 B. Repeat the problem for a cache with 32 data bytes. Practice Problem 6.15: The heart of the recent hit game SimAquarium is a tight loop that calculates the average position of 256 algae. You are evaluating its cache performance on a machine with a 1024-byte direct-mapped data cache with 16-byte blocks ( ½ ). You are given the following definitions: 1 2 3 4 5 6 7 8 struct algae_position { int x; int y; }; struct algae_position grid[16][16]; int total_x = 0, total_y = 0; int i, j; You should also assume: ¯ ¯ ¯ ¯ sizeof(int) == 4. grid begins at memory address 0. The cache is initially empty. The only memory accesses are to the entries of the array grid. Variables i, j, total x, and total y are stored in registers. Determine the cache performance for the following code: 1 2 3 4 5 for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { total_x += grid[i][j].x; } } 326 6 7 8 9 10 11 CHAPTER 6. THE MEMORY HIERARCHY for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { total_y += grid[i][j].y; } } A. What is the total number of reads? _______. B. What is the total number of reads that miss in the cache? _______ . C. What is the miss rate? _______. Practice Problem 6.16: Given the assumptions of Problem 6.15, determine the cache performance of the following code: 1 2 3 4 5 6 for (i = 0; i < for (j = 0; total_x total_y } } 16; i++){ j < 16; j++) { += grid[j][i].x; += grid[j][i].y; A. What is the total number of reads? _______. B. What is the total number of reads that miss in the cache? _______ . C. What is the miss rate? _______. D. What would the miss rate be if the cache were twice as big? Practice Problem 6.17: Given the assumptions of Problem 6.15, determine the cache performance of the following code: 1 2 3 4 5 6 for (i = 0; i < for (j = 0; total_x total_y } } 16; i++){ j < 16; j++) { += grid[i][j].x; += grid[i][j].y; A. What is the total number of reads? _______. B. What is the total number of reads that miss in the cache? _______ . C. What is the miss rate? _______. D. What would the miss rate be if the cache were twice as big? 6.6. PUTTING IT TOGETHER: THE IMPACT OF CACHES ON PROGRAM PERFORMANCE 327 6.6 Putting it Together: The Impact of Caches on Program Performance This section wraps up our discussion of the memory hierarchy by studying the impact that caches have on the performance of programs running on real machines. 6.6.1 The Memory Mountain The rate that a program reads data from the memory system is called the read throughput, or sometimes the read bandwidth. If a program reads Ò bytes over a period of × seconds, then the read throughput over that period is Ò ×, typically expressed in units of MBytes per second (MB/s). If we were to write a program that issued a sequence of read requests from a tight program loop, then the measured read throughput would give us some insight into the performance of the memory system for that particular sequence of reads. Figure 6.40 shows a pair of functions that measure the read throughput for a particular read sequence. code/mem/mountain/mountain.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 void test(int elems, int stride) /* The test function */ { int i, result = 0; volatile int sink; for (i = 0; i < elems; i += stride) result += data[i]; sink = result; /* So compiler doesn’t optimize away the loop */ } /* Run test(elems, stride) and return read throughput (MB/s) */ double run(int size, int stride, double Mhz) { double cycles; int elems = size / sizeof(int); test(elems, stride); /* warm up the cache */ cycles = fcyc2(test, elems, stride, 0); /* call test(elems,stride) */ return (size / stride) / (cycles / Mhz); /* convert cycles to MB/s */ } code/mem/mountain/mountain.c Figure 6.40: Functions that measure and compute read throughput. The test function generates the read sequence by scanning the first elems elements of an integer array with a stride of stride. The run function is a wrapper that calls the test function and returns the measured read throughput. The fcyc2 function in line 18 (not shown) estimates the running time of the test function, in CPU cycles, using the à -best measurement scheme described in Chapter 9. Notice that the size argument to the run function is in units of bytes, while the corresponding elems argument to 328 CHAPTER 6. THE MEMORY HIERARCHY the test function is in units of words. Also, notice that line 19 computes MB/s as ½¼ bytes/s, as opposed to ¾¾¼ bytes/s. The size and stride arguments to the run function allow us to control the degree of locality in the resulting read sequence. Smaller values of size result in a smaller working set size, and thus more temporal locality. Smaller values of stride result in more spatial locality. If we call the run function repeatedly with different values of size and stride, then we can recover a two-dimensional function of read bandwidth versus temporal and spatial locality called the memory mountain. Figure 6.41 shows a program, called mountain, that generates the memory mountain. code/mem/mountain/mountain.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include <stdio.h> #include "fcyc2.h" /* K-best measurement timing routines */ #include "clock.h" /* routines to access the cycle counter */ #define #define #define #define MINBYTES (1 << 10) /* Working set size ranges from 1 KB */ MAXBYTES (1 << 23) /* ... up to 8 MB */ MAXSTRIDE 16 /* Strides range from 1 to 16 */ MAXELEMS MAXBYTES/sizeof(int) /* The array we’ll be traversing */ int data[MAXELEMS]; int main() { int size; int stride; double Mhz; /* Working set size (in bytes) */ /* Stride (in array elements) */ /* Clock frequency */ init_data(data, MAXELEMS); /* Initialize each element in data to 1 */ Mhz = mhz(0); /* Estimate the clock frequency */ for (size = MAXBYTES; size >= MINBYTES; size >>= 1) { for (stride = 1; stride <= MAXSTRIDE; stride++) { printf("%.1f\t", run(size, stride, Mhz)); } printf("\n"); } exit(0); } code/mem/mountain/mountain.c Figure 6.41: mountain: A program that generates the memory mountain. The mountain program calls the run function with different working set sizes and strides. Working set sizes start at 1 KB, increasing by a factor of two, to a maximum of 8 MB. Strides range from 1 to 16. For each combination of working set size and stride, mountain prints the read throughout, in units of MB/s. The mhz function in line 19 (not shown) is a system-dependent routine that estimates the CPU clock frequency, using techniques described in Chapter 9. 6.6. PUTTING IT TOGETHER: THE IMPACT OF CACHES ON PROGRAM PERFORMANCE 329 Every computer has a unique memory mountain that characterizes the capabilities of its memory system. For example, Figure 6.42 shows the memory mountain for an Intel Pentium III Xeon system. 1200 read throughput (MB/s) 1000 L1 800 Pentium III Xeon 550 MHz 16 KB on-chip L1 d-cache 16 KB on-chip L1 i-cache 512 KB off-chip unified L2 cache 600 400 xe Slopes of Spatial Locality L2 200 Ridges of Temporal Locality 0 s1 s3 8k s5 2k working set size (bytes) mem s7 s9 512k s13 128k s11 32k stride (words) s15 Figure 6.42: The memory mountain. The geography of the Xeon mountain reveals a rich structure. Perpendicular to the size axis are three ridges that correspond to the regions of temporal locality where the working set fits entirely in the L1 cache, the L2 cache, and main memory respectively. Notice that there is an order of magnitude difference between the highest peak of the L1 ridge, where the CPU reads at a rate of 1 GB/s, and the lowest point of the main memory ridge, where the CPU reads at a rate of 80 MB/s. There are two features of the L1 ridge that should be pointed out. First, for a constant stride, notice how the read throughput plummets as the working set size decreases from 16 KB to 1 KB (falling off the back side of the ridge). Second, for a working set size of 16 KB, the peak of the L1 ridge line decreases with increasing stride. Since the L1 cache holds the entire working set, these features do not reflect the true L1 cache performance. They are artifacts of overheads of calling the test function and setting up to execute the loop. For the small working set sizes along the L1 ridge, these overheads are not amortized, as they are with the larger working set sizes. On the L2 and main memory ridges, there is a slope of spatial locality that falls downhill as the stride increases. This slope is steepest on the L2 ridge because of the large absolute miss penalty that the L2 cache suffers when it has to transfer blocks from main memory. Notice that even when the working set is too large to fit in either of the L1 or L2 caches, the highest point on the main memory ridge is a factor of two higher than its lowest point. So even when a program has poor temporal locality, spatial locality can still come to 8m 2m 330 the rescue and make a significant difference. CHAPTER 6. THE MEMORY HIERARCHY If we take a slice through the mountain, holding the stride constant as in Figure 6.43, we can see quite clearly the impact of cache size and temporal locality on performance. For sizes up to and including 16 KB, the working set fits entirely in the L1 d-cache, and thus reads are served from L1 at the peak throughput of about 1 GB/s. For sizes up to and including 256 KB, the working set fits entirely in the unified L2 cache. 1200 main memory region L2 cache region L1 cache region 1000 read througput (MB/s) 800 600 400 200 0 1024k 512k 256k 128k 8m 4m 2m 64k 32k 16k 8k 4k 2k 1k working set size (bytes) Figure 6.43: Ridges of temporal locality in the memory mountain. The graph shows a slice through Figure 6.42 with stride=1. Larger working set sizes are served primarily from main memory. The drop in read throughput between 256 KB and 512 KB is interesting. Since the L2 cache is 512 KB, we might expect the drop to occur at 512 KB instead of 256 KB. The only way to be sure is to perform a detailed cache simulation, but we suspect the reason lies in the fact that the Pentium III L2 cache is a unified cache that holds both instructions and data. What we might be seeing is the effect of conflict misses between instructions and data in L2 that make it impossible for the entire array to fit in the L2 cache. Slicing through the mountain in the opposite direction, holding the working set size constant, gives us some insight into the impact of spatial locality on the read throughput. For example, Figure 6.44 shows the slice for a fixed working set size of 256 KB. This slice cuts along the L2 ridge in Figure 6.42, where the working set fits entirely in the L2 cache, but is too large for the L1 cache. Notice how the read throughput decreases steadily as the stride increases from 1 to 8 words. In this region of the mountain, a read miss in L1 causes a block to be transferred from L2 to L1. This is followed by some number of hits on the block in L1, depending on the stride. As the stride increases, the ratio of L1 misses to L1 hits increases. Since misses are served slower than hits, the read throughput decreases. Once the stride reaches 8 words, which on this system equals the block size, every read request misses in L1 and must be served from L2. Thus the read throughput for strides of at least 8 words is a constant rate determined by the rate that cache blocks can be transferred from L2 into L1. To summarize our discussion of the memory mountain: The performance of the memory system is not characterized by a single number. Instead, it is a mountain of temporal and spatial locality whose elevations 6.6. PUTTING IT TOGETHER: THE IMPACT OF CACHES ON PROGRAM PERFORMANCE 800 700 read throughput (MB/s) 600 500 one access per cache line 400 300 200 100 0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 stride (words) 331 Figure 6.44: A slope of spatial locality. The graph shows a slice through Figure 6.42 with size=256 KB. can vary by over an order of magnitude. Wise programmers try to structure their programs so that they run in the peaks instead of the valleys. The aim is to exploit temporal locality so that heavily used words are fetched from the L1 cache, and to exploit spatial locality so that as many words as possible are accessed from a single L1 cache line. Practice Problem 6.18: The memory mountain in Figure 6.42 has two axes: stride and working set size. Which axis corresponds to spatial locality? Which axis corresponds to temporal locality? Practice Problem 6.19: As programmers who care about performance, it is important for us to know rough estimates of the access times to different parts of the memory hierarchy. Using the memory mountain in Figure 6.42, estimate the time, in CPU cycles, to read a 4-byte word from: A. The on-chip L1 d-cache. B. The off-chip L2 cache. C. Main memory. Assume that the read throughput at (size=16M, stride=16) is 80 MB/s. 6.6.2 Rearranging Loops to Increase Spatial Locality Consider the problem of multiplying a pair of Ò ¢ Ò matrices: ½½ ¾½ ½¾ ¾¾ ½½ ¾½ ½¾ ¾¾ ½½ ¾½ . For example, if Ò ½¾ ¾¾ ¾ , then 332 where ½½ ½¾ ¾½ ¾¾ ½½ ½½ · ½½ ½¾ · ¾½ ½½ · ¾½ ½¾ · CHAPTER 6. THE MEMORY HIERARCHY ½¾ ¾½ ½¾ ¾¾ ¾¾ ¾½ ¾¾ ¾¾ Matrix multiply is usually implemented using three nested loops, which are identified by their indexes , , and . If we permute the loops and make some other minor code changes, we can create the six functionally equivalent versions of matrix multiply shown in Figure 6.45. Each version is uniquely identified by the ordering of its loops. At a high level, the six versions are quite similar. If addition is associative, then each version computes an identical result.2 Each version performs Ç ´Ò¿ µ total operations and an identical number of adds and multiplies. Each of the Ò¾ elements of and is read Ò times. Each of the Ò¾ elements of is computed by summing Ò values. However, if we analyze the behavior of the innermost loop iterations, we find that there are differences in the number of accesses and the locality. For the purposes of our analysis, let’s make the following assumptions: ¯ ¯ ¯ ¯ Each array is an Ò ¢ Ò array of double, with sizeof(double) == 8. There is a single cache with a 32-byte block size ( ¿¾ ). The array size Ò is so large that a single matrix row does not fit in the L1 cache. The compiler stores local variables in registers, and thus references to local variables do not require any load or store instructions. Figure 6.46 summarizes the results of our inner loop analysis. Notice that the six versions pair up into three equivalence classes, which we denote by the pair of matrices that are accessed in the inner loop. For example, versions and are members of Class because they reference arrays and (but not ) in their innermost loop. For each class, we have counted the number of loads (reads) and stores (writes) in each inner loop iteration, the number of references to , , and that will miss in the cache in each loop iteration, and the total number of cache misses per iteration. The inner loops of the Class routines (Figure 6.45(a) and (b)) scan a row of array with a stride of 1. Since each cache block holds four doublewords, the miss rate for is 0.25 misses per iteration. On the other hand, the inner loop scans a column of with a stride of Ò. Since Ò is large, each access of array results in a miss, for a total of ½ ¾ misses per iteration. The inner loops in the Class routines (Figure 6.45(c) and (d)) have some problems. Each iteration performs two loads and a store (as opposed to the Class routines, which perform 2 loads and no stores). Second, the inner loop scans the columns of and with a stride of Ò. The result is a miss on each load, for As we learned in Chapter 2, floating-point addition is commutative, but in general not associative. In practice, if the matrices do not mix extremely large values with extremely small ones, as if often true when the matrices store physical properties, then the assumption of associativity is reasonable. 2 6.6. PUTTING IT TOGETHER: THE IMPACT OF CACHES ON PROGRAM PERFORMANCE code/mem/matmult/mm.c 1 2 3 4 5 6 7 333 code/mem/matmult/mm.c 1 2 3 4 5 6 7 for (i = 0; i < n; i++) for (j = 0; j < n; j++) { sum = 0.0; for (k = 0; k < n; k++) sum += A[i][k]*B[k][j]; C[i][j] += sum; } code/mem/matmult/mm.c for (j = 0; j < n; j++) for (i = 0; i < n; i++) { sum = 0.0; for (k = 0; k < n; k++) sum += A[i][k]*B[k][j]; C[i][j] += sum; } code/mem/matmult/mm.c (a) Version . code/mem/matmult/mm.c (b) Version . code/mem/matmult/mm.c 1 2 3 4 5 6 for (j = 0; j < n; j++) for (k = 0; k < n; k++) { r = B[k][j]; for (i = 0; i < n; i++) C[i][j] += A[i][k]*r; } code/mem/matmult/mm.c 1 2 3 4 5 6 for (k = 0; k < n; k++) for (j = 0; j < n; j++) { r = B[k][j]; for (i = 0; i < n; i++) C[i][j] += A[i][k]*r; } code/mem/matmult/mm.c (c) Version . code/mem/matmult/mm.c (d) Version . code/mem/matmult/mm.c 1 2 3 4 5 6 for (k = 0; k < n; k++) for (i = 0; i < n; i++) { r = A[i][k]; for (j = 0; j < n; j++) C[i][j] += r*B[k][j]; } code/mem/matmult/mm.c 1 2 3 4 5 6 for (i = 0; i < n; i++) for (k = 0; k < n; k++) { r = A[i][k]; for (j = 0; j < n; j++) C[i][j] += r*B[k][j]; } code/mem/matmult/mm.c (e) Version . (f) Version . Figure 6.45: Six versions of matrix multiply. Matrix multiply version (class) & ( ) & ( ) & ( ) Loads per iter 2 2 2 Stores per iter 0 1 1 A misses per iter 0.25 1.00 0.00 B misses per iter 1.00 0.00 0.25 C misses per iter 0.00 1.00 0.25 Total misses per iter 1.25 2.00 0.50 Figure 6.46: Analysis of matrix multiply inner loops. The six versions partition into three equivalence classes, denoted by the pair of arrays that are accessed in the inner loop. 334 CHAPTER 6. THE MEMORY HIERARCHY a total of two misses per iteration. Notice that interchanging the loops has decreased the amount of spatial locality compared to the Class routines. The routines (Figure 6.45(e) and (f)) present an interesting tradeoff. With two loads and a store, they require one more memory operation than the routines. On the other hand, since the inner loop scans both and row-wise with a stride-1 access pattern, the miss rate on each array is only 0.25 misses per iteration, for a total of 0.50 misses per iteration. Figure 6.47 summarizes the performance of different versions of matrix multiply on a Pentium III Xeon system. The graph plots the measured number of CPU cycles per inner loop iteration as a function of array size (Ò). 60 50 Cycles/iteration 40 30 20 kji jki kij ikj jik ijk 10 0 25 50 75 100 125 150 175 200 225 250 275 300 325 350 375 400 Array size (n) Figure 6.47: Pentium III Xeon matrix multiply performance. Legend: : Class ; and : Class There are a number of interesting points to notice about this graph: and : Class ; and ¯ ¯ ¯ ¯ For large Ò, the fastest version runs three times faster than the slowest version, even though each performs the same number of floating-point arithmetic operations. Versions with the same number and locality of memory accesses have roughly the same measured performance. The two versions with the worst memory behavior, in terms of the number of accesses and misses per iteration, run significantly slower than the other four versions, which have fewer misses or fewer accesses, or both. The Class routines — 2 memory accesses and 1.25 misses per iteration — perform somewhat better on this particular machine than the Class routines — 3 memory accesses and 0.5 misses per iteration — which trade off an additional memory reference for a lower miss rate. The point is that cache misses are not the whole story when it comes to performance. The number of memory accesses 6.6. PUTTING IT TOGETHER: THE IMPACT OF CACHES ON PROGRAM PERFORMANCE 335 is also important, and in many cases, finding the best performance involves a tradeoff between the two. Problems 6.32 and 6.33 delve into this issue more deeply. 6.6.3 Using Blocking to Increase Temporal Locality In the last section we saw how some simple rearrangements of the loops could increase spatial locality. But observe that even with good loop nestings, the time per loop iteration increases with increasing array size. What is happening is that as the array size increases, the temporal locality decreases, and the cache experiences an increasing number of capacity misses. To fix this, we can use a general technique called blocking. However, we must point out that, unlike the simple loop transformations for improving spatial locality, blocking makes the code harder to read and understand. For this reason it is best suited for optimizing compilers or frequently executed library routines. Still, the technique is interesting to study and understand because it is a general concept that can produce big performance gains. The general idea of blocking is to organize the data structures in a program into large chunks called blocks. (In this context, the term “block” refers to an application-level chunk of data, not a cache block.) The program is structured so that it loads a chunk into the L1 cache, does all the reads and writes that it needs to on that chunk, then discards the chunk, loads in the next chunk, and so on. Blocking a matrix multiply routine works by partitioning the matrices into submatrices and then exploiting the mathematical fact that these submatrices can be manipulated just like scalars. For example, if Ò , then we could partition each matrix into four ¢ submatrices: ½½ ¾½ ½¾ ¾¾ ½½ ¾½ ½¾ ¾¾ ½½ ¾½ ½¾ ¾¾ where ½½ ½¾ ¾½ ¾¾ ½½ ½½ ¾½ ¾½ ½½ · ½¾ · ½½ · ½¾ · ½¾ ½¾ ¾¾ ¾¾ ¾½ ¾¾ ¾½ ¾¾ Figure 6.48 shows one version of blocked matrix multiplication, which we call the version. The basic idea behind this code is to partition and into ½ ¢ bsize row slivers and to partition into bsize ¢ bsize blocks. The innermost ´ µ loop pair multiplies a sliver of by a block of and accumulates the result into a sliver of . The loop iterates through Ò row slivers of and , using the same block in . Figure 6.49 gives a graphical interpretation of the blocked code from Figure 6.48. The key idea is that it loads a block of into the cache, uses it up, and then discards it. References to enjoy good spatial locality because each sliver is accessed with a stride of 1. There is also good temporal locality because the entire sliver is referenced × Þ times in succession. References to enjoy good temporal locality because the entire × Þ ¢ × Þ block is accessed Ò times in succession. Finally, the references to have good spatial locality because each element of the sliver is written in succession. Notice that references to do not have good temporal locality because each sliver is only accessed one time. 336 CHAPTER 6. THE MEMORY HIERARCHY code/mem/matmult/bmm.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 void bijk(array A, array B, array C, int n, int bsize) { int i, j, k, kk, jj; double sum; int en = bsize * (n/bsize); /* Amount that fits evenly into blocks */ for (i = 0; i < n; i++) for (j = 0; j < n; j++) C[i][j] = 0.0; for (kk = 0; kk < en; kk += bsize) { for (jj = 0; jj < en; jj += bsize) { for (i = 0; i < n; i++) { for (j = jj; j < jj + bsize; j++) { sum = C[i][j]; for (k = kk; k < kk + bsize; k++) { sum += A[i][k]*B[k][j]; } C[i][j] = sum; } } } } } code/mem/matmult/bmm.c Figure 6.48: Blocked matrix multiply. A simple version that assumes that the array size ( n) is an integral multiple of the block size (bsize). kk bsize jj bsize bsize 1 jj 1 i kk bsize i A Use 1 x bsize row sliver bsize times B Use bsize x bsize block n times in succession C Update successive elements of 1 x bsize row sliver Figure 6.49: Graphical interpretation of blocked matrix multiply The innermost ´ tiplies a ½ ¢ bsize sliver of A by a bsize ¢ bsize block of B and accumulates into a C. ½ loop pair mul¢ bsize sliver of µ 6.6. PUTTING IT TOGETHER: THE IMPACT OF CACHES ON PROGRAM PERFORMANCE 337 Blocking can make code harder to read, but it can also pay big performance dividends. Figure 6.50 shows the performance of two versions of blocked matrix multiply on a Pentium III Xeon system ( × Þ ¾ ). Notice that blocking improves the running time by a factor of two over the best non-blocked version, from about 20 cycles per iteration down to about 10 cycles per iteration. The other interesting impact of blocking is that the time per iteration remains nearly constant with increasing array size. For small array sizes, the additional overhead in the blocked version causes it to run slower than the non-blocked versions. There is a crossover point, at about Ò ½¼¼, after which the blocked version runs faster. 60 50 Cycles/iteration 40 30 20 10 kji jki kij ikj jik ijk bijk (bsize = 25) bikj (bsize = 25) 0 25 50 75 100 125 150 175 200 225 250 275 300 325 350 375 400 Array size (n) Figure 6.50: Pentium III Xeon blocked matrix multiply performance. Legend: and : two different versions of blocked matrix multiply. Performance of the unblocked versions from Figure 6.47 is shown for reference. Aside: Caches and streaming media workloads Applications that process network video and audio data in real time are becoming increasingly important. In these applications, the data arrive at the machine in a steady stream from some input device such as a microphone, a camera, or a network connection (see Chapter 12). As the data arrive, they are processed, sent to an output device, and eventually discarded to make room for newly arriving data. How well suited is the memory hierarchy for these streaming media workloads? Since the data are processed sequentially as they arrive, we able to derive some benefit from spatial locality, as with our matrix multiply example from Section 6.6. However, since the data are processed once and then discarded, the amount of temporal locality is limited. To address this problem, system designers and compiler writers have pursued a strategy known as prefetching. The idea is to hide the latency of cache misses by anticipating which blocks will be accessed in the near future, and then fetching these blocks into the cache beforehand using special machine instructions. If the prefetching is done perfectly, then each block is copied into the cache just before the program references it, and thus every load instruction results in a cache hit. Prefetching entails risks, though. Since prefetching traffic shares the bus with the DMA traffic that is streaming from an I/O device to main memory, too much prefetching might interfere with the DMA traffic and slow down overall system performance. Another potential problem is that every prefetched cache block must evict an existing block. If we do too much prefetching, we run the risk of polluting the cache by evicting a previously prefetched block that the program has not referenced yet, but will in the near future. End Aside. 338 CHAPTER 6. THE MEMORY HIERARCHY 6.7 Summary The memory system is organized as a hierarchy of storage devices, with smaller, faster devices towards the top and larger, slower devices towards the bottom. Because of this hierarchy, the effective rate that a program can access memory locations is not characterized by a single number. Rather, it is a wildly varying function of program locality (what we have dubbed the memory mountain) that can vary by orders of magnitude. Programs with good locality access most of their data from fast L1 and L2 cache memories. Programs with poor locality access most of their data from the relatively slow DRAM main memory. Programmers who understand the nature of the memory hierarchy can exploit this understanding to write more efficient programs, regardless of the specific memory system organization. In particular, we recommend the following techniques: ¯ ¯ ¯ ¯ Focus your attention on the inner loops where the bulk of the computations and memory accesses occur. Try to maximize the spatial locality in your programs by reading data objects sequentially, in the order they are stored in memory. Try to maximize the temporal locality in your programs by using a data object as often as possible once it has been read from memory. Remember that miss rates are only one (albeit important) factor that determines the performance of your code. The number of memory accesses also plays an important role, and sometimes it is necessary to trade off between the two. Bibliographic Notes Memory and disk technologies change rapidly. In our experience, the best sources of technical information are the Web pages maintained by the manufacturers. Companies such as Micron, Toshiba, Hyundai, Samsung, Hitachi, and Kingston Technology provide a wealth of current technical information on memory devices. The pages for IBM, Maxtor, and Seagate provide similarly useful information about disks. Textbooks on circuit and logic design provide detailed information about memory technology [36, 58]. IEEE Spectrum published a series of survey articles on DRAM [33]. The International Symposium on Computer Architecture (ISCA) is a common forum for characterizations of DRAM memory performance [20, 21]. Wilkes wrote the first paper on cache memories [83]. Smith wrote a classic survey [68]. Przybylski wrote an authoritative book on cache design [56]. Hennessy and Patterson provide a comprehensive discussion of cache design issues [31]. Stricker introduced the idea of the memory mountain as a comprehensive characterization of the memory system in [78], and suggested the term “memory mountain” in later presentations of the work. Compiler researchers work to increase locality by automatically performing the kinds manual code transformations we discussed in Section 6.6 [13, 23, 42, 45, 51, 57, 85]. Carter and colleagues have proposed a cacheaware memory controller [10]. Seward developed an open-source cache profiler, called cacheprof, that characterizes the miss behavior of C programs on an arbitrary simulated cache (www.cacheprof.org). 6.7. SUMMARY 339 There is a large body of literature on building and using disk storage. Many storage researchers look for ways to aggregate individual disks into larger, more robust, and more secure storage pools [11, 26, 27, 54, 86]. Others look for ways to use caches and locality to improve the performance of disk accesses [6, 12]. Systems such as Exokernel provide increased user-level control of disk and memory resources [35]. Systems such as the Andrew File System [50] and Coda [63] extend the memory hierarchy across computer networks and mobile notebook computers. Schindler and Ganger have developed an interesting tool that automatically characterizes the geometry and performance of SCSI disk drives [64]. Homework Problems Homework Problem 6.20 [Category 2]: Suppose you are asked to design a diskette where the number of bits per track is constant. You know that the number of bits per track is determined by the circumference of the innermost track, which you can assume is also the circumference of the hole. Thus, if you make the hole in the center of the diskette larger, the number of bits per track increases, but the total number of tracks decreases. If you let Ö denote the radius of the platter, and Ü ¡ Ö the radius of the hole, what value of Ü maximizes the capacity of the diskette? Homework Problem 6.21 [Category 1]: The following table gives the parameters for a number of different caches. For each cache, determine the number of cache sets (Ë ), tag bits (Ø), set index bits (×), and block offset bits ( ). Cache 1. 2. 3. 4. 5. 6. Ñ Ë Ø × 32 32 32 32 32 32 1024 1024 1024 1024 1024 1024 4 4 8 8 32 32 4 256 1 128 1 4 Homework Problem 6.22 [Category 1]: This problem concerns the cache in Problem 6.9. A. List all of the hex memory addresses that will hit in Set 1. B. List all of the hex memory addresses that will hit in Set 6. Homework Problem 6.23 [Category 2]: Consider the following matrix transpose routine: 1 2 typedef int array[4][4]; 340 3 4 5 6 7 8 9 10 11 12 CHAPTER 6. THE MEMORY HIERARCHY void transpose2(array dst, array src) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { dst[j][i] = src[i][j]; } } } Assume this code runs on a machine with the following properties: ¯ ¯ ¯ ¯ ¯ sizeof(int) == 4. The src array starts at address 0 and the dst array starts at address 64 (decimal). There is a single L1 data cache that is direct-mapped, write-through, write-allocate,with a block size of 16 bytes. The cache has a total size of 32 data bytes and the cache is initially empty. Accesses to the src and dst arrays are the only sources of read and write misses, respectively. A. For each row and col, indicate whether the access to src[row][col] and dst[row][col] is a hit (h) or a miss (m). For example, reading src[0][0] is a miss and writing dst[0][0] is also a miss. dst array col 1 col 2 src array col 1 col 2 row 0 row 1 row 2 row 3 col 0 m col 3 row 0 row 1 row 2 row 3 col 0 m col 3 Homework Problem 6.24 [Category 2]: Repeat Problem 6.23 for a cache with a total size of 128 data bytes. dst array col 1 col 2 src array col 1 col 2 col 0 row 0 row 1 row 2 row 3 col 3 row 0 row 1 row 2 row 3 col 0 col 3 6.7. SUMMARY 341 Homework Problem 6.25 [Category 1]: 3M decides to make Post-Its by printing yellow squares on white pieces of paper. As part of the printing process, they need to set the CMYK (cyan, magenta, yellow, black) value for every point in the square. 3M hires you to determine the efficiency of the following algorithms on a machine with a 2048-byte directmapped data cache with 32-byte blocks. You are given the following definitions: 1 2 3 4 5 6 7 8 9 struct point_color { int c; int m; int y; int k; }; struct point_color square[16][16]; int i, j; Assume: ¯ ¯ ¯ ¯ sizeof(int) == 4. square begins at memory address 0. The cache is initially empty. The only memory accesses are to the entries of the array square. Variables i and j are stored in registers. Determine the cache performance of the following code: 1 2 3 4 5 6 7 8 for (i = 0; i < 16; i++){ for (j = 0; j < 16; j++) { square[i][j].c = 0; square[i][j].m = 0; square[i][j].y = 1; square[i][j].k = 0; } } A. What is the total number of writes? _______. B. What is the total number of writes that miss in the cache? _______ . C. What is the miss rate? _______. Homework Problem 6.26 [Category 1]: Given the assumptions in Problem 6.25, determine the cache performance of the following code: 342 1 2 3 4 5 6 7 8 CHAPTER 6. THE MEMORY HIERARCHY for (i = 0; i < 16; i++){ for (j = 0; j < 16; j++) { square[j][i].c = 0; square[j][i].m = 0; square[j][i].y = 1; square[j][i].k = 0; } } A. What is the total number of writes? _______. B. What is the total number of writes that miss in the cache? _______ . C. What is the miss rate? _______. Homework Problem 6.27 [Category 1]: Given the assumptions in Problem 6.25, determine the cache performance of the following code: 1 2 3 4 5 6 7 8 9 10 11 12 for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { square[i][j].y = 1; } } for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { square[i][j].c = 0; square[i][j].m = 0; square[i][j].k = 0; } } A. What is the total number of writes? _______. B. What is the total number of writes that miss in the cache? _______ . C. What is the miss rate? _______. Homework Problem 6.28 [Category 2]: You are writing a new 3D game that you hope will earn you fame and fortune. You are currently working on a function to blank the screen buffer before drawing the next frame. The screen you are working with is a ¼ ¢ ¼ array of pixels. The machine you are working on has a 64 KB direct-mapped cache with 4-byte lines. The C structures you are using are: 6.7. SUMMARY 1 2 3 4 5 6 7 8 9 10 11 343 struct pixel { char r; char g; char b; char a; }; struct pixel buffer[480][640]; int i, j; char *cptr; int *iptr; Assume: ¯ ¯ ¯ ¯ sizeof(char) == 1 and sizeof(int) == 4 buffer begins at memory address 0. The cache is initially empty. The only memory accesses are to the entries of the array buffer. Variables i, j, cptr, and iptr are stored in registers. What percentage of writes in the following code will miss in the cache? 1 2 3 4 5 6 7 8 for (j = 0; j < 640; j++) { for (i = 0; i < 480; i++){ buffer[i][j].r = 0; buffer[i][j].g = 0; buffer[i][j].b = 0; buffer[i][j].a = 0; } } Homework Problem 6.29 [Category 2]: Given the assumptions in Problem 6.28, what percentage of writes in the following code will miss in the cache? 1 2 3 char *cptr = (char *) buffer; for (; cptr < (((char *) buffer) + 640 * 480 * 4); cptr++) *cptr = 0; Homework Problem 6.30 [Category 2]: Given the assumptions in Problem 6.28, what percentage of writes in the following code will miss in the cache? 344 1 2 3 CHAPTER 6. THE MEMORY HIERARCHY int *iptr = (int *)buffer; for (; iptr < ((int *)buffer + 640*480); iptr++) *iptr = 0; Homework Problem 6.31 [Category 3]: Download the mountain program from the CS:APP Web site and run it on your favorite PC/Linux system. Use the results to estimate the sizes of the L1 and L2 caches on your system. Homework Problem 6.32 [Category 4]: In this assignment you will apply the concepts you learned in Chapters 5 and 6 to the problem of optimizing code for a memory intensive application. Consider a procedure to copy and transpose the elements of an Æ ¢ Æ matrix of type int. That is, for source matrix Ë and destination matrix , we want to copy each element × to . This code can be written with a simple loop: 1 2 3 4 5 6 7 8 void transpose(int *dst, int *src, int dim) { int i, j; for (i = 0; i < dim; i++) for (j = 0; j < dim; j++) dst[j*dim + i] = src[i*dim + j]; } where the arguments to the procedure are pointers to the destination (dst) and source (src) matrices, as well as the matrix size Æ (dim). Making this code run fast requires two types of optimizations. First, although the routine does a good job exploiting the spatial locality of the source matrix, it does a poor job for large values of Æ with the destination matrix. Second, the code generated by GCC is not very efficient. Looking at the assembly code, one sees that the inner loop requires 10 instructions, 5 of which reference memory—one for the source, one for the destination, and three to read local variables from the stack. Your job is to address these problems and devise a transpose routine that runs as fast as possible. Homework Problem 6.33 [Category 4]: This assignment is an intriguing variation of Problem 6.32. Consider the problem of converting a directed graph into its undirected counterpart ¼ . The graph ¼ has an edge from vertex Ù to vertex Ú iff there is an edge from Ù to Ú or from Ú to Ù in the original graph . The graph is represented by its adjacency matrix as follows. If Æ is the number of vertices in then is an Æ ¢ Æ matrix and its entries are all either 0 or 1. Suppose the vertices of are named Ú¼ Ú½ Ú¾ ÚÆ ½ . Then is 1 if there is an edge from Ú to Ú and 0 otherwise. Observe, that the elements on the diagonal of an adjacency matrix are always 1 and that the adjacency matrix of an undirected graph is symmetric. This code can be written with a simple loop: 1 2 3 4 5 6 7 void col_convert(int *G, int dim) { int i, j; for (i = 0; i < dim; i++) for (j = 0; j < dim; j++) G[j*dim + i] = G[j*dim + i] || G[i*dim + j]; } 6.7. SUMMARY 345 Your job is to devise a conversion routine that runs as fast as possible. As before, you will need to apply concepts you learned in Chapters 5 and 6 to come up with a good solution. 346 CHAPTER 6. THE MEMORY HIERARCHY Part II Running Programs on a System 347 Chapter 7 Linking Linking is the process of collecting and combining the various pieces of code and data that a program needs in order to be loaded (copied) into memory and executed. Linking can be performed at compile time, when the source code is translated into machine code, at load time, when the program is loaded into memory and executed by the loader, and even at run time, by application programs. On early computer systems, linking was performed manually. On modern systems, linking is performed automatically by programs called linkers. Linkers play a crucial role in software development because they enable separate compilation. Instead of organizing a large application as one monolithic source file, we can decompose it into smaller, more manageable modules that can be modified and compiled separately. When we change one of these modules, we simply recompile it and relink the application, without having to recompile the other files. Linking is usually handled quietly by the linker, and is not an important issue for students who are building small programs in introductory programming classes. So why bother learning about linking? ¯ ¯ Understanding linkers will help you build large programs. Programmers who build large programs often encounter linker errors caused by missing modules, missing libraries, or incompatible library versions. Unless you understand how a linker resolves references, what a library is, and how a linker uses a library to resolve references, these kinds of errors will be baffling and frustrating. Understanding linkers will help you avoid dangerous programming errors. The decisions that Unix linkers make when they resolve symbol references can silently affect the correctness of your programs. Programs that incorrectly define multiple global variables pass through the linker without any warnings in the default case. The resulting programs can exhibit baffling run-time behavior and are extremely difficult to debug. We will show you how this happens and how to avoid it. Understanding linking will help you understand how language scoping rules are implemented. For example, what is the difference between global and local variables? What does it really mean when you define a variable or function with the static attribute? Understanding linking will help you understand other important systems concepts. The executable object files produced by linkers play key roles in important systems functions such as loading and running programs, virtual memory, paging, and memory mapping. 349 ¯ ¯ 350 CHAPTER 7. LINKING ¯ Understanding linking will enable you to exploit shared libraries. For many years, linking was considered to be fairly straightforward and uninteresting. However, with the increased importance of shared libraries and dynamic linking in modern operating systems, linking is a sophisticated process that provides the knowledgeable programmer with significant power. For example, many software products use shared libraries to upgrade shrink-wrapped binaries at run time. Also, most Web servers rely on dynamic linking of shared libraries to serve dynamic content. This chapter is a thorough discussion of all aspects of linking, from traditional static linking, to dynamic linking of shared libraries at load time, to dynamic linking of shared libraries at run time. We will describe the basic mechanisms using real examples, and we will identify situations where linking issues can affect the performance and correctness of your programs. To keep things concrete and understandable, we will couch our discussion in the context of an IA32 machine running a version of Unix, such as Linux or Solaris, that uses the standard ELF object file format. However, it is important to realize that the basic concepts of linking are universal, regardless of the operating system, the ISA, or the object file format. Details may vary, but the concepts are the same. 7.1 Compiler Drivers Consider the C program in Figure 7.1. It consists of two source files, main.c and swap.c. Function main() calls swap, which swaps the two elements in the external global array buf. Granted, this is a strange way to swap two numbers, but it will serve as a small running example throughout this chapter that will allow us to make some important points about how linking works. Most compilation systems provide a compiler driver that invokes the language preprocessor, compiler, assembler, and linker, as needed on behalf of the user. For example, to build the example program using the GNU compilation system, we might invoke the GCC driver by typing the following command to the shell: unix> gcc -O2 -g -o p main.c swap.c Figure 7.2 summarizes the activities of the driver as it translates the example program from an ASCII source file into an executable object file. (If you want to see these steps for yourself, run GCC with the -v option.) The driver first runs the C preprocessor (cpp), which translates the C source file main.c into an ASCII intermediate file main.i: cpp [other arguments] main.c /tmp/main.i Next, the driver runs the C compiler (cc1), which translates main.i into an ASCII assembly language file main.s. cc1 /tmp/main.i main.c -O2 [other arguments] -o /tmp/main.s Then, the driver runs the assembler (as), which translates main.s into a relocatable object file main.o: as [other arguments] -o /tmp/main.o /tmp/main.s 7.2. STATIC LINKING 351 code/link/swap.c 1 code/link/main.c 1 2 3 4 5 6 7 8 9 10 /* main.c */ void swap(); int buf[2] = {1, 2}; int main() { swap(); return 0; } code/link/main.c 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /* swap.c */ extern int buf; int *bufp0 = &buf[0]; int *bufp1; void swap() { int temp; bufp1 = &buf[1]; temp = *bufp0; *bufp0 = *bufp1; *bufp1 = temp; } code/link/swap.c (a) main.c (b) swap.c Figure 7.1: Example program 1: The example program consists of two source files, main.c and swap.c. The main function initializes a two-element array of ints, and then calls the swap function to swap the pair. The driver goes through the same process to generate swap.o. Finally it runs the linker program ld, which combines main.o and swap.o, along with the necessary system object files, to create the executable object file p: ld -o p [system object files and args] /tmp/main.o /tmp/swap.o To run the executable p, we type its name on the Unix shell’s command line: unix> ./p The shell invokes a function in the operating system called the loader, which copies the code and data in the executable file p into memory, and then transfers control to the beginning of the program. 7.2 Static Linking Static linkers such as the Unix ld program take as input a collection of relocatable object files and command line arguments and generate as output a fully linked executable object file that can be loaded and run. The input relocatable object files consist of various code and data sections. Instructions are in one section, initialized global variables are in another section, and uninitialized variables are in yet another section. To build the executable, the linker must perform two main tasks: 352 main.c Translators (cpp, cc1, as) main.o Linker (ld) p swap.c Translators (cpp, cc1, as) swap.o CHAPTER 7. LINKING source files relocatable object files fully linked executable object file Figure 7.2: Static linking. The linker combines relocatable object files to form an executable object file p. ¯ ¯ Symbol resolution. Object files define and reference symbols. The purpose of symbol resolution is to associate each symbol reference with exactly one symbol definition. Relocation. Compilers and assemblers generate code and data sections that start at address zero. The linker relocates these sections by associating a memory location with each symbol definition, and then modifying all of the references to those symbols so that they point to this memory location. The following sections describe these tasks in more detail. As you read, keep in mind the basic facts of linkers: Object files are merely collections of blocks of bytes. Some of these blocks contain program code, others contain program data, and others contain data structures that guide the linker and loader. A linker concatenates blocks together, decides on run-time locations for the concatenated blocks, and modifies various locations within the code and data blocks. Linkers have minimal understanding of the target machine. The compilers and assemblers that generate the object files have already done most of the work. 7.3 Object Files Object files come in three forms: ¯ ¯ ¯ Relocatable object file. Contains binary code and data in a form that can be combined with other relocatable object files at compile time to create an executable object file. Executable object file. Contains binary code and data in a form that can be copied directly into memory and executed. Shared object file. A special type of relocatable object file that can be loaded into memory and linked dynamically, at either load time or run time. Compilers and assemblers generate relocatable object files (including shared object files). Linkers generate executable object files. Technically, an object module is a sequence of bytes, and an object file is an object module stored on disk in a file. However, we will use these terms interchangeably. 7.4. RELOCATABLE OBJECT FILES 353 Object file formats vary from system to system. The first Unix systems from Bell Labs used the a.out format. (To this day, executables are still referred to as a.out files.) Early versions of System V Unix used the Common Object File format (COFF). Windows NT uses a variant of COFF called the Portable Executable (PE) format. Modern Unix systems — such as Linux, later versions of System V Unix, BSD Unix variants, and Sun Solaris — use the Unix Executable and Linkable Format (ELF). Although our discussion will focus on ELF, the basic concepts are similar, regardless of the particular format. 7.4 Relocatable Object Files Figure 7.3 shows the format of a typical ELF relocatable object file. The ELF header begins with a 16-byte sequence that describes the word size and byte ordering of the system that generated the file. The rest of the ELF header contains information that allows a linker to parse and interpret the object file. This includes the size of the ELF header, the object file type (e.g., relocatable, executable, or shared), the machine type (e.g., IA32) the file offset of the section header table, and the size and number of entries in the section header table. The locations and sizes of the various sections are described by the section header table, which contains a fixed sized entry for each section in the object file. ELF header .text .rodata .data .bss .symtab sections .rel.text .rel.data .debug .line describes object file sections .strtab Section header table 0 Figure 7.3: Typical ELF relocatable object file. Sandwiched between the ELF header and the section header table are the sections themselves. A typical ELF relocatable object file contains the following sections: .text: The machine code of the compiled program. .rodata: Read-only data such as the format strings in printf statements, and jump tables for switch statements (see Problem 7.14). .data: Initialized global C variables. Local C variables are maintained at run time on the stack, and do not appear in either the .data or .bss sections. 354 CHAPTER 7. LINKING .bss: Uninitialized global C variables. This section occupies no actual space in the object file; it is merely a place holder. Object file formats distinguish between initialized and uninitialized variables for space efficiency: uninitialized variables do not have to occupy any actual disk space in the object file. .symtab: A symbol table with information about functions and global variables that are defined and referenced in the program. Some programmers mistakenly believe that a program must be compiled with the -g option to get symbol table information. In fact, every relocatable object file has a symbol table in .symtab. However, unlike the symbol table inside a compiler, the .symtab symbol table does not contain entries for local variables. .rel.text: A list of locations in the .text section that will need to be modified when the linker combines this object file with others. In general, any instruction that calls an external function or references a global variable will need to be modified. On the other hand, instructions that call local functions do not need to be modified. Note that relocation information is not needed in executable object files, and is usually omitted unless the user explicitly instructs the linker to include it. .rel.data: Relocation information for any global variables that are referenced or defined by the module. In general, any initialized global variable whose initial value is the address of a global variable or externally defined function will need to be modified. .debug: A debugging symbol table with entries for local variables and typedefs defined in the program, global variables defined and referenced in the program, and the original C source file. It is only present if the compiler driver is invoked with the -g option. .line: A mapping between line numbers in the original C source program and machine code instructions in the .text section. It is only present if the compiler driver is invoked with the -g option. .strtab: A string table for the symbol tables in the .symtab and .debug sections, and for the section names in the section headers. A string table is a sequence of null-terminated character strings. Aside: Why is uninitialized data called .bss? The use of the term .bss to denote uninitialized data is universal. It was originally an acronym for the “Block Storage Start” instruction from the IBM 704 assembly language (circa 1957) and the acronym has stuck. A simple way to remember the difference between the .data and .bss sections is to think of “bss” as an abbreviation for “Better Save Space!”. End Aside. 7.5 Symbols and Symbol Tables Each relocatable object module, Ñ, has a symbol table that contains information about the symbols that are defined and referenced by Ñ. In the context of a linker, there are three different kinds of symbols: ¯ ¯ Global symbols that are defined by module Ñ and that can be referenced by other modules. Global linker symbols correspond to nonstatic C functions and global variables that are defined without the C static attribute. Global symbols that are referenced by module Ñ but defined by some other module. Such symbols are called externals and correspond to C functions and variables that are defined in other modules. 7.5. SYMBOLS AND SYMBOL TABLES 355 ¯ Local symbols that are defined and referenced exclusively by module Ñ. Some local linker symbols correspond to C functions and global variables that are defined with the static attribute. These symbols are visible anywhere within module Ñ, but cannot be referenced by other modules. The sections in an object file and the name of the source file that corresponds module Ñ also get local symbols. It is important to realize that local linker symbols are not the same as local program variables. The symbol table in .symtab does not contain any symbols that correspond to local nonstatic program variables. These are managed at run time on the stack and are not of interest to the linker. Interestingly, local procedure variables that are defined with the C static attribute are not managed on the stack. Instead, the compiler allocates space in .data or .bss for each definition and creates a local linker symbol in the symbol table with a unique name. For example, suppose a pair of functions in the same module define a static local variable x: 1 2 3 4 5 6 7 8 9 10 11 int f() { static int x = 0; return x; } int g() { static int x = 1; return x; } In this case, the compiler allocates space for two integers in .bss and exports a pair of unique local linker symbols to the assembler. For example, it might use x.1 for the definition in function f and x.2 for the definition in function g. New to C? C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public, and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible. End Symbol tables are built by assemblers, using symbols exported by the compiler into the assembly language .s file. An ELF symbol table is contained in the .symtab section. It contains an array of entries. Figure 7.4 shows the format of each entry. The name is a byte offset into the string table that points to the null-terminated string name of the symbol. The value is the symbol’s address. For relocatable modules, the value is an offset from the beginning of the section where the object is defined. For executable object files, the value is an absolute run-time address. The size is the size (in bytes) of the object. The type is usually either data or function. The symbol table can also contain entries for the individual sections and for the path name of the original source file. So there 356 CHAPTER 7. LINKING code/link/elfstructs.c 1 2 3 4 5 6 7 8 9 10 typedef struct { int name; int value; int size; char type:4, binding:4; char reserved; char section; } Elf_Symbol; /* /* /* /* /* /* /* /* string table offset */ section offset, or VM address */ object size in bytes */ data, func, section, or src file name (4 bits) */ local or global (4 bits) */ unused */ section header index, ABS, UNDEF, */ or COMMON */ code/link/elfstructs.c Figure 7.4: ELF symbol table entry. type and binding are four bits each. are distinct types for these objects as well. The binding field indicates whether the symbol is local or global. Each symbol is associated with some section of the object file, denoted by the section field, which is an index into the section header table. There are three special pseudo-sections that don’t have entries in the section header table: ABS is for symbols that should not be relocated. UNDEF is for undefined symbols, that is, symbols that are referenced in this object module but defined elsewhere. COMMON is for uninitialized data objects that are not yet allocated. For COMMON symbols, the value field gives the alignment requirement, and size gives the minimum size. For example, here are the last three entries in the symbol table for main.o, as displayed by the GNU READELF tool. The first eight entries, which are not shown, are local symbols that the linker uses internally. Num: 8: 9: 10: Value 0 0 0 Size 8 17 0 Type OBJECT FUNC NOTYPE Bind Ot GLOBAL 0 GLOBAL 0 GLOBAL 0 Ndx 3 1 UND Name buf main swap In this example, we see an entry for the definition of global symbol buf, an 8-byte object located at an offset (i.e., value) of zero in the .data section. This is followed by the definition of the global symbol main, a 17-byte function located at an offset of zero in the .text section. The last entry comes from the reference for the external symbol swap. R EADELF identifies each section by an integer index. Ndx=1 denotes the .text section, and Ndx=3 denotes the .data section. Similarly, here are the symbol table entries for swap.o: Num: 8: 9: 10: 11: Value 0 0 0 4 Size 4 0 39 4 Type OBJECT NOTYPE FUNC OBJECT Bind Ot GLOBAL 0 GLOBAL 0 GLOBAL 0 GLOBAL 0 Ndx 3 UND 1 COM Name bufp0 buf swap bufp1 7.6. SYMBOL RESOLUTION 357 First, we see an entry for the definition of the global symbol bufp0, which is a 4-byte initialized object starting at offset 0 in .data. The next symbol comes from the reference to the external buf symbol in the initialization code for bufp0. This is followed by the global symbol swap, a 39-byte function at an offset of 0 in .text. The last entry is the global symbol bufp1, a 4-byte uninitialized data object (with a 4-byte alignment requirement) that will eventually be allocated as a .bss object when this module is linked. Practice Problem 7.1: This problem concerns the swap.o module from Figure 7.1(b). For each symbol that is defined or referenced in swap.o, indicate whether or not it will have a symbol table entry in the .symtab section in module swap.o. If so, indicate the module that defines the symbol (swap.o or main.o), the symbol type (local, global, or extern) and the section (.text, .data, or .bss) it occupies in that module. Symbol buf bufp0 bufp1 swap temp swap.o .symtab entry? Symbol type Module where defined Section 7.6 Symbol Resolution The linker resolves symbol references by associating each reference with exactly one symbol definition from the symbol tables of its input relocatable object files. Symbol resolution is straightforward for references to local symbols that are defined in the same module as the reference. The compiler allows only one definition of each local symbol per module. The compiler also ensures that static local variables, which get local linker symbols, have unique names. However, resolving references to global symbols is trickier. When the compiler encounters a symbol (either a variable or function name) that is not defined in the current module, it assumes that it is defined in some other module, generates a linker symbol table entry, and leaves it for the linker to handle. If the linker is unable to find a definition for the referenced symbol in any of its input modules, it prints an (often cryptic) error message and terminates. For example, if we try to compile and link the following source file on a Linux machine, 1 2 3 4 5 6 void foo(void); int main() { foo(); return 0; } then the compiler runs without a hitch, but the linker terminates when it cannot resolve the reference to foo: unix> gcc -Wall -O2 -o linkerror linkerror.c 358 /tmp/ccSz5uti.o: In function ‘main’: /tmp/ccSz5uti.o(.text+0x7): undefined reference to ‘foo’ collect2: ld returned 1 exit status CHAPTER 7. LINKING Symbol resolution for global symbols is also tricky because the same symbol might be defined by multiple object files. In this case, the linker must either flag an error, or somehow chose one of the definitions and discard the rest. The approach adopted by Unix systems involves cooperation between the compiler, assembler, and linker, and can introduce some baffling bugs to the unwary programmer. 7.6.1 How Linkers Resolve Multiply-Defined Global Symbols At compile time, the compiler exports each global symbol to the assembler as either strong or weak, and the assembler encodes this information implicitly in the symbol table of the relocatable object file. Functions and initialized global variables get strong symbols. Uninitialized global variables get weak symbols. For the example program in Figure 7.1, buf, bufp0, main, and swap are strong symbols; bufp1 is a weak symbol. Given this notion of strong and weak symbols, Unix linkers use the following rules for dealing with multiplydefined symbols: ¯ ¯ ¯ Rule 1: Multiple strong symbols are not allowed. Rule 2: Given a strong symbol and multiple weak symbols, choose the strong symbol. Rule 3: Given multiple weak symbols, choose any of the weak symbols. For example, suppose we attempt to compile and link the following two C modules: 1 2 3 4 5 /* foo1.c */ int main() { return 0; } 1 2 3 4 5 /* bar1.c */ int main() { return 0; } In this case the linker will generate an error message because the strong symbol main is defined multiple times (Rule 1): unix> gcc foo1.c bar1.c /tmp/cca015022.o: In function ‘main’: /tmp/cca015022.o(.text+0x0): multiple definition of ‘main’ /tmp/cca015021.o(.text+0x0): first defined here Similarly, the linker will generate an error message for the following modules because the strong symbol x is defined twice (Rule 1): 7.6. SYMBOL RESOLUTION 1 2 3 4 5 6 7 359 1 2 3 4 5 6 /* foo2.c */ int x = 15213; int main() { return 0; } /* bar2.c */ int x = 15213; void f() { } However, if x is uninitialized in one module, then the linker will quietly choose the strong symbol defined in the other (Rule 2): 1 2 3 4 5 6 7 8 9 10 11 12 /* foo3.c */ #include <stdio.h> void f(void); int x = 15213; int main() { f(); printf("x = %d\n", x); return 0; } 1 2 3 4 5 6 7 /* bar3.c */ int x; void f() { x = 15212; } At run time, function f changes the value of x from ½ ¾½¿ to ½ ¾½¾, which might come as a unwelcome surprise to the author of function main! Notice that the linker normally gives no indication that it has detected multiple definitions of x: unix> gcc -o foobar3 foo3.c bar3.c unix> ./foobar3 x = 15212 The same thing can happen if there are two weak definitions of x (Rule 3): 1 2 3 4 5 6 7 8 9 10 11 12 13 /* foo4.c */ #include <stdio.h> void f(void); int x; int main() { x = 15213; f(); printf("x = %d\n", x); return 0; } 1 2 3 4 5 6 7 /* bar4.c */ int x; void f() { x = 15212; } 360 CHAPTER 7. LINKING The application of Rules 2 and 3 can introduce some insidious run-time bugs that are incomprehensible to the unwary programmer, especially if the duplicate symbol definitions have different types. Consider the following example, where x is defined as an int in one module and a double in another: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* foo5.c */ #include <stdio.h> void f(void); int x = 15213; int y = 15212; int main() { f(); printf("x = 0x%x y = 0x%x \n", x, y); return 0; } 1 2 3 4 5 6 7 /* bar5.c */ double x; void f() { x = -0.0; } On an IA32/Linux machine, doubles are 8 bytes and ints are 4 bytes. Thus, the assignment x = -0.0 in line 5 of bar5.c will overwrite the memory locations for x and y (lines 5 and 6 in foo5.c) with the double-precision floating-point representation of negative one! linux> gcc -o foobar5 foo5.c bar5.c linux> ./foobar5 x = 0x0 y = 0x80000000 This is a subtle and nasty bug, especially because it occurs silently, with no warning from the compilation system, and because it typically manifests itself much later in the execution of the program, far away from where the error occurred. In a large system with hundreds of modules, a bug of this kind is extremely hard to fix, especially because many programmers are not aware of how linkers work. When in doubt, invoke the linker with a flag such as the GCC -warn-common flag, which instructs it to print a warning message when it resolves multiply-defined global symbol definitions. Practice Problem 7.2: In this problem, let REF(x.i) --> DEF(x.k) denote that the linker will associate an arbitrary reference to symbol x in module i to the definition of x in module k. For each example below, use this notation to indicate how the linker would resolve references to the multiply-defined symbol in each module. If there is a link-time error (Rule 1), write “ERROR”. If the linker arbitrarily chooses one of the definitions (Rule 3), write “UNKNOWN”. A. /* Module 1 */ int main() { } /* Module 2 */ int main; int p2() { } (a) REF(main.1) --> DEF(_____.___) 7.6. SYMBOL RESOLUTION (b) REF(main.2) --> DEF(_____.___) B. /* Module 1 */ void main() { } /* Module 2 */ int main=1; int p2() { } (a) REF(main.1) --> DEF(_____.___) (b) REF(main.2) --> DEF(_____.___) 361 /* Module 2 */ C. /* Module 1 */ double x=1.0; int x; int p2() void main() { { } } (a) REF(x.1) --> DEF(_____.___) (b) REF(x.2) --> DEF(_____.___) 7.6.2 Linking with Static Libraries So far we have assumed that the linker reads a collection of relocatable object files and links them together into an output executable file. In practice, all compilation systems provide a mechanism for packaging related object modules into a single file called a static library, which can then be supplied as input to the linker. When it builds the output executable, the linker copies only the object modules in the library that are referenced by the application program. Why do systems support the notion of libraries? Consider ANSI C, which defines an extensive collection of standard I/O, string manipulation, and integer math functions such as atoi, printf, scanf, strcpy, and random. They are available to every C program in the libc.a library. ANSI C also defines an extensive collection of floating point math functions such as sin, cos, and sqrt in the libm.a library. Consider the different approaches that compiler developers might use to provide these functions to users without the benefit of static libraries. One approach would be to have the compiler recognize calls to the standard functions and to generate the appropriate code directly. Pascal, which provides a small set of standard functions, takes this approach, but it is not feasible for C because of the large number of standard functions defined by the C standard. It would add significant complexity to the compiler and would require a new compiler version each time a function was added, deleted, or modified. To application programmers, however, this approach would be quite convenient because the standard functions would always be available. Another approach would be to put all of the standard C functions in a single relocatable object module, say libc.o, that application programmers could link into their executables: unix> gcc main.c /usr/lib/libc.o This approach has the advantage that it would decouple the implementation of the standard functions from the implementation of the compiler, and would still be reasonably convenient for programmers. However, a 362 CHAPTER 7. LINKING big disadvantage is that every executable file in a system would now contain a complete copy of the collection of standard functions, which would be extremely wasteful of disk space. (On a typical system, libc.a is about 8 MB and libm.a is about 1 MB.) Worse, each running program would now contain its own copy of these functions in memory, which would be extremely wasteful of memory. Another big disadvantage is that any change to any standard function, no matter how small, would require the library developer to recompile the entire source file, a time-consuming operation that would complicate the development and maintenance of the standard functions. We could address some of these problems by creating a separate relocatable file for each standard function and storing them in a well-known directory. However this approach would require application programmers to explicitly link the appropriate object modules into their executables, a process that would be error prone and time-consuming: unix> gcc main.c /usr/lib/printf.o /usr/lib/scanf.o ... The notion of a static library was developed to resolve the disadvantages of these various approaches. Related functions can be compiled into separate object modules and then packaged in a single static library file. Application programs can then use any of the functions defined in the library by specifying a single file name on the command line. For example, a program that uses functions from the standard C library and the math library could be compiled and linked with a command of the form: unix> gcc main.c /usr/lib/libm.a /usr/lib/libc.a At link time, the linker will only copy the object modules that are referenced by the program, which reduces the size of the executable on disk and in memory. On the other hand, the application programmer only needs to include the names of a few library files. (In fact, C compiler drivers always pass libc.a to the linker, so the reference to libc.a above is unnecessary.) On Unix systems, static libraries are stored on disk in a particular file format known as an archive. An archive is a collection of concatenated relocatable object files, with a header that describes the size and location of each member object file. Archive filenames are denoted with the .a suffix. To make our discussion of libraries concrete, suppose that we want to provide the vector routines in Figure 7.5 in a static library called libvector.a. To create the library, we would use the AR tool: unix> gcc -c addvec.c multvec.c unix> ar rcs libvector.a addvec.o multvec.o To use the library, we might write an application such as main2.c in Figure 7.6, which invokes the addvec library routine. (The include file vector.h defines the function prototypes for the routines in libvector.a.) To build the executable, we would compile and link the input files main.o and libvector.a: unix> gcc -O2 -c main2.c unix> gcc -static -o p2 main2.o ./libvector.a Figure 7.7 summarizes the activity of the linker. The -static argument tells the compiler driver that the linker should build a fully-linked executable object file that can be loaded into memory and run without 7.6. SYMBOL RESOLUTION 363 code/link/addvec.c 1 2 3 4 5 6 7 8 code/link/multvec.c 1 2 3 4 5 6 7 8 void addvec(int *x, int *y, int *z, int n) { int i; for (i = 0; i < n; i++) z[i] = x[i] + y[i]; } code/link/addvec.c void multvec(int *x, int *y, int *z, int n) { int i; for (i = 0; i < n; i++) z[i] = x[i] * y[i]; } code/link/multvec.c (a) addvec.o (a) multvec.o Figure 7.5: Member object files in libvector.a. code/link/main2.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* main2.c */ #include <stdio.h> #include "vector.h" int x[2] = {1, 2}; int y[2] = {3, 4}; int z[2]; int main() { addvec(x, y, z, 2); printf("z = [%d %d]\n", z[0], z[1]); return 0; } code/link/main2.c Figure 7.6: Example program 2: This program calls member functions in the static libvector.a library. 364 CHAPTER 7. LINKING any further linking at load time. When the linker runs, it determines that the addvec symbol defined by addvec.o is referenced by main.o, so it copies addvec.o into the executable. Since the program doesn’t reference any symbols defined by multvec.o, the linker does not copy this module into the executable. The linker also copies the printf.o module from libc.a, along with a number of other modules from the C run-time system. source files main2.c vector.h Translators (cpp, cc1, as) libvector.a libc.a static libraries relocatable object files main2.o addvec.o Linker (ld) printf.o and any other modules called by printf. o p2 fully linked executable object file Figure 7.7: Linking with static libraries. 7.6.3 How Linkers Use Static Libraries to Resolve References While static libraries are useful and essential tools, they are also a source of confusion to programmers because of the way the Unix linker uses them to resolve external references. During the symbol resolution phase, the linker scans the relocatable object files and archives left to right in the same sequential order that they appear on the compiler driver’s command line. (The driver automatically translates any .c files on the command line into .o files.) During this scan, the linker maintains a set of relocatable object files that will be merged to form the executable, a set Í of unresolved symbols (i.e., symbols referred to but not yet defined), and a set of symbols that have been defined in previous input files. Initially, , Í , and are empty. ¯ ¯ For each input file on the command line, the linker determines if is an object file or an archive. If is an object file, the linker adds to , updates Í and to reflect the symbol definitions and references in , and proceeds to the next input file. If is an archive, the linker attempts to match the unresolved symbols in Í against the symbols defined by the members of the archive. If some archive member, Ñ, defines a symbol that resolves a reference in Í , then Ñ is added to , and the linker updates Í and to reflect the symbol definitions and references in Ñ. This process iterates over the member object files in the archive until a fixed point is reached where Í and no longer change. At this point, any member object files not contained in are simply discarded and the linker proceeds to the next input file. is nonempty when the linker finishes scanning the input files on the command line, it prints an error and terminates. Otherwise it merges and relocates the object files in to build the output executable file. ¯ If Í 7.7. RELOCATION 365 Unfortunately, this algorithm can result in some baffling link-time errors because the ordering of libraries and object files on the command line is significant. If the library that defines a symbol appears on the command line before the object file that references that symbol, then the reference will not be resolved and linking will fail. For example: unix> gcc -static ./libvector.a main2.c /tmp/cc9XH6Rp.o: In function ‘main’: /tmp/cc9XH6Rp.o(.text+0x18): undefined reference to ‘addvec’ Here is what happened: When libvector.a is processed, Í is empty, so no member object files from libvector.a are added to . Thus the reference to addvec is never resolved, and the linker emits an error message and terminates.. The general rule for libraries is to place them at the end of the command line. If the members of the different libraries are independent, in that no member references a symbol defined by another member, then the libraries can be placed at the end of the command line in any order. On the other hand, if the libraries are not independent, then they must be ordered so that for each symbol × that is referenced externally by a member of an archive, at least one definition of × follows a reference to × on the command line. For example, suppose foo.c calls functions in libx.a and libz.a that call functions in liby.a. Then libx.a and libz.a must precede liby.a on the command line: unix> gcc foo.c libx.a libz.a liby.a Libraries can be repeated on the command line if necessary to satisfy the dependence requirements. For example, suppose foo.c calls a function in libx.a that calls a function in liby.a that calls a function in libx.a. Then libx.a must be repeated on the command line: unix> gcc foo.c libx.a liby.a libx.a Alternatively, we could combine libx.a and liby.a into a single archive. Practice Problem 7.3: Let a and b denote object modules or static libraries in the current directory, and let a b denote that a depends on b, in the sense that b defines a symbol that is referenced by a. For each of the following scenarios, show the minimal command line (i.e., one with the least number of file object file and library arguments) that will allow the static linker to resolve all symbol references. A. p.o B. p.o C. p.o libx.a. libx.a libx.a liby.a. liby.a and liby.a libx.a p.o. 7.7 Relocation Once the linker has completed the symbol resolution step, it has associated each symbol reference in the code with exactly one symbol definition (i.e., a symbol table entry in one of its input object modules). At 366 CHAPTER 7. LINKING this point, the linker knows the exact sizes of the code and data sections in its input object modules. It is now ready to begin the relocation step, where it merges the input modules and assigns run-time addresses to each symbol. Relocation consists of two steps: ¯ Relocating sections and symbol definitions. In this step, the linker merges all sections of the same type into a new aggregate section of the same type. For example, the .data sections from the input modules are all merged into one section that will become the .data section for the output executable object file. The linker then assigns run-time memory addresses to the new aggregate sections, to each section defined by the input modules, and to each symbol defined by the input modules. When this step is complete, every instruction and global variable in the program has a unique run-time memory address. Relocating symbol references within sections. In this step, the linker modifies every symbol reference in the bodies of the code and data sections so that they point to the correct run-time addresses. To perform this step, the linker relies on data structures in the relocatable object modules known as relocation entries, which we describe next. ¯ 7.7.1 Relocation Entries When an assembler generates an object module, it does not know where the code and data will ultimately be stored in memory. Nor does it know the locations of any externally defined functions or global variables that are referenced by the module. So whenever the assembler encounters a reference to an object whose ultimate location is unknown, it generates a relocation entry that tells the linker how to modify the reference when it merges the object file into an executable. Relocation entries for code are placed in .relo.text. Relocation entries for initialized data are placed in .relo.data. Figure 7.8 shows the format of an ELF relocation entry. The offset is the section offset of the reference that will need to be modified. The symbol identifies the symbol that the modified reference should point to. The type tells the linker how to the modify the new reference. code/link/elfstructs.c 1 2 3 4 5 typedef struct { int offset; int symbol:24, type:8; } Elf32_Rel; /* offset of the reference to relocate */ /* symbol the reference should point to */ /* relocation type */ code/link/elfstructs.c Figure 7.8: ELF relocation entry. Each entry identifies a reference that must be relocated. ELF defines 11 different relocation types, some quite arcane. We are concerned with only the two most basic relocation types: ¯ R 386 PC32: Relocate a reference that uses a 32-bit PC-relative address. Recall from Section 3.6.3 that a PC-relative address is an offset from the current run-time value of the program counter (PC). 7.7. RELOCATION 367 When the CPU executes an instruction using PC-relative addressing, it forms the effective address (e.g., the target of the call instruction) by adding the 32-bit value encoded in the instruction to the current run-time value of the PC, which is always the address of the next instruction in memory. ¯ R 386 32: Relocate a reference that uses a 32-bit absolute address. With absolute addressing, the CPU directly uses the 32-bit value encoded in the instruction as the effective address, without further modifications. 7.7.2 Relocating Symbol References Figure 7.9 shows the pseudo-code for the linker’s relocation algorithm. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 foreach section s { foreach relocation entry r { refptr = s + r.offset; /* ptr to reference to be relocated */ /* relocate a if (r.type == refaddr = *refptr = } PC-relative reference */ R_386_PC32) { ADDR(s) + r.offset; /* ref’s runtime address */ (unsigned) (ADDR(r.symbol) + *refptr - refaddr); /* relocate an absolute reference */ if (r.type == R_386_32) *refptr = (unsigned) (ADDR(r.symbol) + *refptr); } } Figure 7.9: Relocation algorithm. Lines 1 and 2 iterate over each section s and each relocation entry r associated with each section. For concreteness, assume that each section s is an array of bytes and that each relocation entry r is a struct of type Elf32 Rel, as defined in Figure 7.8. Also, assume that when the algorithm runs, the linker has already chosen run-time addresses for each section (denoted ADDR(s)), and each symbol (denoted ADDR(r.symbol)). Line 3 computes the address in the s array of the 4-byte reference that needs to be relocated. If this reference uses PC-relative addressing, then it is relocated by lines 5–9. If the reference uses absolute addressing, then it is relocated by lines 11–13. Relocating PC-Relative References Recall from our running example in Figure 7.1(a) that the main routine in the .text section of main.o calls the swap routine, which is defined in swap.o. Here is the disassembled listing for the call instruction, as generated by the GNU OBJDUMP tool: 6: e8 fc ff ff ff call 7 <main+0x7> 7: R_386_PC32 swap swap(); relocation entry 368 CHAPTER 7. LINKING From this listing we see that the call instruction begins at section offset 0x6 and consists of the 1-byte opcode 0xe8, followed by the 32-bit reference 0xfffffffc ( decimal), which is stored in little-endian byte order. We also see a relocation entry for this reference displayed on the following line. (Recall that relocation entries and instructions are actually stored in different sections of the object file. The OBJDUMP tool displays them together for convenience.) The relocation entry r consists of three fields: r.offset = 0x7 r.symbol = swap r.type = R_386_PC32 that tell the linker to modify the 32-bit PC-relative reference starting at offset 0x7 so that it will point to the swap routine at run time. Now suppose that the linker has determined that ADDR(s) = ADDR(.text) = 0x80483b4 and ADDR(r.symbol) = ADDR(swap) = 0x80483c8. Using the algorithm in Figure 7.9, the linker first computes the run-time address of the reference (line 7): refaddr = ADDR(s) + r.offset = 0x80483b4 + 0x7 = 0x80483bb and then updates the reference from its current value ( ) to 0x9 so that it will point to the swap routine at run time (line 8): *refptr = (unsigned) (ADDR(r.symbol) + *refptr - refaddr) = (unsigned) (0x80483c8 + (-4) - 0x80483bb) = (unsigned) (0x9) In the resulting executable object file, the call instruction has the following relocated form: 80483ba: e8 09 00 00 00 call 80483c8 <swap> swap(); At run time, the call instruction will be stored at address 0x80483ba. When the CPU executes the call instruction, the PC has a value of 0x80483bf, which is the address of the instruction immediately following the call instruction. To execute the instruction, the CPU performs the following steps: 1. push PC onto stack 2. PC <- PC + 0x9 = 0x80483bf + 0x9 = 0x80483c8 Thus, the next instruction to execute is the first instruction of the swap routine, which of course is what we want! You may wonder why the assembler created the reference in the call instruction with an initial value of . The assembler uses this value as a bias to account for the fact that the PC always points to the instruction following the current instruction. On a different machine with different instruction sizes and encodings, the assembler for that machine would use a different bias. This is powerful trick that allows the linker to blindly relocate references, blissfully unaware of the instruction encodings for a particular machine. 7.7. RELOCATION 369 Relocating Absolute References Recall that in our example program in Figure 7.1, the swap.o module initializes the global pointer bufp0 to the address of the first element of the global buf array: int *bufp0 = &buf[0]; Since bufp0 is an initialized data object, it will be stored in the .data section of the swap.o relocatable object module. Since it is initialized to the address of a global array, it will need to be relocated. Here is the disassembled listing of the .data section from swap.o: 00000000 <bufp0>: 0: 00 00 00 00 0: R_386_32 buf int *bufp0 = &buf[0]; relocation entry We see that the .data section contains a single 32-bit reference, the bufp0 pointer, which has a value of 0x0. The relocation entry tells the linker that this is a 32-bit absolute reference, beginning at offset 0, which must relocated so that it points to the symbol buf. Now suppose that the linker has determined that ADDR(r.symbol) = ADDR(buf) = 0x8049454 The linker updates the reference using line 13 of the algorithm in Figure 7.9: *refptr = (unsigned) (ADDR(r.symbol) + *refptr) = (unsigned) (0x8049454 + 0) = (unsigned) (0x8049454) In the resulting executable object file, the reference has the following relocated form: 0804945c <bufp0>: 804945c: 54 94 04 08 Relocated! In words, the linker has decided that at run time, the variable bufp0 will be located at memory address 0x804945c and will be initialized to 0x8049454, which is the run-time address of the buf array. The .text section in the swap.o module contains five absolute references that are relocated in a similar way (See Problem 7.12). Figure 7.10 shows the relocated .text and .data sections in the final executable object file. Practice Problem 7.4: This problem concerns the relocated program in Figure 7.10. A. What is the hex address of the relocated reference to swap in line 5? B. What is the hex value of the relocated reference to swap in line 5? C. Suppose the linker had decided for some reason to locate the .text section at 0x80483b8 instead of 0x80483b4. What would the hex value of the relocated reference in line 5 be in this case? 370 CHAPTER 7. LINKING code/link/p-exe.d 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 080483b4 <main>: 80483b4: 55 80483b5: 89 e5 80483b7: 83 ec 08 80483ba: e8 09 00 00 00 80483bf: 31 c0 80483c1: 89 ec 80483c3: 5d 80483c4: c3 80483c5: 90 80483c6: 90 80483c7: 90 080483c8 <swap>: 80483c8: 55 80483c9: 8b 15 80483cf: a1 58 80483d4: 89 e5 80483d6: c7 05 80483dd: 94 04 80483e0: 89 ec 80483e2: 8b 0a 80483e4: 89 02 80483e6: a1 48 80483eb: 89 08 80483ed: 5d 80483ee: c3 push mov sub call xor mov pop ret nop nop nop %ebp %esp,%ebp $0x8,%esp 80483c8 <swap> %eax,%eax %ebp,%esp %ebp swap(); 5c 94 04 08 94 04 08 48 95 04 08 58 08 push mov mov mov movl mov mov mov mov mov pop ret %ebp 0x804945c,%edx 0x8049458,%eax %esp,%ebp $0x8049458,0x8049548 %ebp,%esp (%edx),%ecx %eax,(%edx) 0x8049548,%eax %ecx,(%eax) %ebp Get *bufp0 Get buf[1] bufp1 = &buf[1] 95 04 08 Get *bufp1 code/link/p-exe.d (a) Relocated .text section. code/link/pdata-exe.d 1 2 3 4 08049454 <buf>: 8049454: 01 00 00 00 02 00 00 00 0804945c <bufp0>: 804945c: 54 94 04 08 Relocated! code/link/pdata-exe.d (b) Relocated .data section. Figure 7.10: Relocated .text and data sections for executable file p The original C code is in Figure 7.1. 7.8. EXECUTABLE OBJECT FILES 371 7.8 Executable Object Files We have seen how the linker merges multiple object modules into a single executable object file. Our C program, which began life as a collection of ASCII text files, has been transformed into a single binary file that contains all of the information needed to load the program into memory and run it. Figure 7.11 summarizes the kinds of information in a typical ELF executable file. 0 maps contiguous file sections to runtime memory segments ELF header Segment header table .init .text .rodata .data .bss .symtab .debug .line describes object file sections .strtab Section header table symbol table and debugging info are not loaded into memory read/write memory segment (data segment) read-only memory segment (code segment) Figure 7.11: Typical ELF executable object file The format of an executable object file is similar to that of a relocatable object file. The ELF header describes the overall format of the file. It also includes the program’s entry point, which is the address of the first instruction to execute when the program runs. The .text, .rodata, and .data sections are similar to those in a relocatable object file, except that these sections have been relocated to their eventual run-time memory addresses. The .init section defines a small function, called init, that will be called by the program’s initialization code. Since the executable is fully linked (relocated), it needs no .relo sections. ELF executables are designed to be easy to load into memory, with contiguous chunks of the executable file mapped to contiguous memory segments. This mapping is described by the segment header table. Figure 7.12 shows the segment header table for our example executable p, as displayed by OBJDUMP. From the segment header table, we see that two memory segments will be initialized with the contents of the executable object file. Lines 1 and 2 tell us that the first segment (the code segment) is aligned to a 4 KB (¾½¾ ) boundary, has read/execute permissions, starts at memory address 0x08048000, has a total memory size of 0x448 bytes, and is initialized with the first 0x448 bytes of the executable object file, which includes the ELF header, the segment header table, and the .init, .text, and .rodata sections. Lines 3 and 4 tell us that the second segment (the data segment) is aligned to a 4 KB boundary, has read/write permissions, starts at memory address 0x08049448, has a total memory size of 0x104 bytes, and is initialized with the 0xe8 bytes starting at file offset 0x448, which in this case is the beginning of the .data section. The remaining bytes in the segment correspond to .bss data that will initialized to zero at run time. 372 CHAPTER 7. LINKING code/link/p-exe.d Read-only code segment 1 2 LOAD off 0x00000000 vaddr 0x08048000 paddr 0x08048000 align 2**12 filesz 0x00000448 memsz 0x00000448 flags r-x Read/write data segment 3 4 LOAD off 0x00000448 vaddr 0x08049448 paddr 0x08049448 align 2**12 filesz 0x000000e8 memsz 0x00000104 flags rwcode/link/p-exe.d Figure 7.12: Segment header table for the example executable p. Legend: off: file offset, vaddr/paddr: virtual/physical address, align:, segment alignment, filesz: segment size in the object file, memsz: segment size in memory, flags: run-time permissions. 7.9 Loading Executable Object Files To run an executable object file p, we can type its name to the Unix shell’s command line: unix> ./p Since p does not correspond to a built-in shell command, the shell assumes that p is an executable object file, which it runs for us by invoking some memory-resident operating system code known as the loader. Any Unix program can invoke the loader by calling the execve function, which we will describe in detail in Section 8.4.6. The loader copies the code and data in the executable object file from disk into memory, and then runs the program by jumping to its first instruction, or entry point. This process of copying the program into memory and then running it is known as loading. Every Unix program has a run-time memory image similar to the one in Figure 7.13. On Linux systems, the code segment always starts at address 0x08048000. The data segment follows at the next 4-KB aligned address. The run-time heap follows on the first 4-KB aligned address past the read/write segment and grows up via calls to the malloc library. (We will describe malloc and the heap in detail in Section 10.9). The segment starting at address 0x40000000 is reserved for shared libraries. The user stack always starts at address 0xbfffffff and grows down (towards lower memory addresses). The segment starting above the stack at address 0xc0000000 is reserved for the code and data in the memory-resident part of the operating system known as the kernel. When the loader runs, it creates the memory image shown in Figure 7.13. Guided by the segment header table in the executable, it copies chunks of the executable into the code and data segments. Next, the loader jumps to the program’s entry point, which is always the address of the start symbol. The startup code at the start address is defined in the object file crt1.o and is the same for all C programs. Figure 7.14 shows the specific sequence of calls in the startup code. After calling initialization routines in from the .text and .init sections, the startup code calls the atexit routine, which appends a list of routines that should be called when the application calls the exit function. The exit function runs the functions registered by atexit, and then returns control to the operating system by calling exit). Next, the startup code calls the application’s main routine, which begins executing our C code. After the application returns, the startup code calls the exit routine, which returns control to the operating system. 7.9. LOADING EXECUTABLE OBJECT FILES 373 0xc0000000 kernel virtual memory user stack (created at runtime) memory invisible to user code %esp (stack pointer) 0x40000000 memory mapped region for shared libraries brk run-time heap (created at runtime by malloc) read/write segment (.data, .bss) read-only segment (.init, .text, .rodata) unused loaded from the executable file 0x08048000 0 Figure 7.13: Linux run-time memory image 1 2 3 4 5 6 7 0x080480c0 <_start>: /* entry point in .text */ call __libc_init_first /* startup code in .text */ call _init /* startup code in .init */ call atexit /* startup code in .text */ call main /* application main routine */ call _exit /* returns control to OS */ /* control never reaches here */ Figure 7.14: Pseudo-code for the crt1.o startup routine in every C program. Note: The code that pushes the arguments for each function is not shown. 374 CHAPTER 7. LINKING Aside: How do loaders really work? Our description of loading is conceptually correct, but intentionally not entirely accurate. To understand how loading really works, you must understand concepts of processes, virtual memory, and memory mapping that we haven’t discussed yet. As we encounter these concepts later in Chapters 8 and 10, we will revisit loading and gradually reveal the mystery to you. For the impatient reader, here is a preview of how loading really works: Each program in a Unix system runs in the context of a process with its own virtual address space. When the shell runs a program, the parent shell process forks a child process that is a duplicate of the parent. The child process invokes the loader via the execve system call. The loader deletes the child’s existing virtual memory segments, and creates a new set of code, data, heap, and stack segments. The new stack and heap segments are initialized to zero. The new code and data segments are initialized to the contents of the executable file by mapping pages in the virtual address space to page-sized chunks of the executable file. Finally, the loader jumps to the start address, which eventually calls the application’s main routine. Aside from some header information, there is no copying of data from disk to memory during loading. The copying is deferred until the CPU references a mapped virtual page, at which point the operating system automatically transfers the page from disk to memory using its paging mechanism. End Aside. Practice Problem 7.5: A. Why does every C program need a routine called main? B. Have you ever wondered why a C main routine can end with a call to exit, a return statement, or neither, and yet the program still terminates properly? Explain. 7.10 Dynamic Linking with Shared Libraries The static libraries that we studied in Section 7.6.2 address many of the issues associated with making large collections of related functions available to application programs. However, static libraries still have some significant disadvantages. Static libraries, like all software, need to be maintained and updated periodically. If application programmers want to use the most recent version of a library, they must somehow become aware that the library has changed, and then explicitly relink their programs against the updated library. Another issue is that almost every C program uses standard I/O functions such as printf and scanf. At run time, the code for these functions is duplicated in the text segment of each running process. On a typical system that is running 50–100 processes, this can be a significant waste of scarce memory system resources. (An interesting property of memory is that it is always a scarce resource, regardless of how much there is in a system. Disk space and kitchen trash cans share this same property.) Shared libraries are a modern innovation that address the disadvantages of static libraries. A shared library is an object module that, at run time, can be loaded at an arbitrary memory address and linked with a program in memory. This process is known as dynamic linking, and is performed by a program called a dynamic linker. Shared libraries are also referred to as shared objects and on Unix systems are typically denoted by the .so suffix. Microsoft operating systems refer to shared libraries as DLLs (dynamic link libraries). Shared libraries are “shared” in two different ways. First, in any given file system, there is exactly one .so file for a particular library. The code and data in this .so file are shared by all of the executable object files that reference the library, as opposed to the contents of static libraries, which are copied and embedded 7.10. DYNAMIC LINKING WITH SHARED LIBRARIES 375 in the executables that reference them. Second, a single copy of the .text section of a shared library in memory can be shared by different running processes. We will explore this in more detail when we study virtual memory in Chapter 10. Figure 7.15 summarizes the dynamic linking process for the example program in Figure 7.6. To build a shared library libvector.so of our example vector arithmetic routines in Figure 7.5, we would invoke the compiler driver with a special directive to the linker: unix> gcc -shared -fPIC -o libvector.so addvec.c multvec.c The -fPIC flag directs the compiler to generate position independent code (more on this in the next section). The -shared flag directs the linker to create a shared object file. main2.c vector.h Translators (cpp, cc1, as) libc.so libvector.so relocatable main2.o Linker (ld) relocation and symbol table info partially linked executable object file p2 Loader (execve) libc.so libvector.so code and data fully linked executable in memory Dynamic linker (ld-linux.so) Figure 7.15: Dynamic linking with shared libraries. Once we have created the library, we would then link it into our example program in Figure 7.6. unix> gcc -o p2 main2.c ./libvector.so This creates an executable object file p2 in a form that can be linked with libvector.so at run time. The basic idea is to do some of the linking statically when the executable file is created, and then complete the linking process dynamically when the program is loaded. It is important to realize that none of the code or data sections from libvector.so are actually copied into the executable p2 at this point. Instead, the linker copies some relocation and symbol table information that will allow references to code and data in libvector.so to be resolved at run time. When the loader loads and runs the executable p2, it loads the partially linked executable p2, using the techniques discussed in Section 7.9. Next, it notices that p2 contains a .interp section, which contains the path name of the dynamic linker, which is itself a shared object (e.g., LD - LINUX . SO on Linux systems). 376 CHAPTER 7. LINKING Instead of passing control to the application, as it would normally do, the loader loads and runs the dynamic linker. The dynamic linker then finishes the linking task by: ¯ ¯ ¯ Relocating the text and data of libc.so into some memory segment. On IA32/Linux systems, shared libraries are loaded in the area starting at address 0x40000000 (See Figure 7.13). Relocating the text and data of libvector.so into another memory segment. Relocating any references in p2 to symbols defined by libc.so and libvector.so. Finally, the dynamic linker passes control to the application. From this point on, the locations of the shared libraries are fixed and do not change during execution of the program. 7.11 Loading and Linking Shared Libraries from Applications To this point we have discussed the scenario where the dynamic linker loads and links shared libraries when an application is loaded, just before it executes. However, it is also possible for an application to request the dynamic linker to load and link arbitrary shared libraries while the application is running, without having to linked the applications against those libraries at compile time. Dynamic linking is a powerful and useful technique. For example, developers of Microsoft Windows applications frequently use shared libraries to distribute software updates. They generate a new copy of a shared library, which users can then download and use a replacement for the current version. The next time they run their application, it will automatically link and load the new shared library. Another example: the servers at many Web sites generate a great deal of dynamic content such as personalized Web pages, account balances, and banner ads. The earliest Web servers generated dynamic content by using fork and execve to create a child process and run a “CGI program” in the context of the child. However, modern Web servers generate dynamic content using a more efficient and sophisticated approach based on dynamic linking. The idea is to package each function that generates dynamic content in a shared library. When a request arrives from a Web browser, the server dynamically loads and links the appropriate function and then calls it directly, as opposed to using fork and execve to run the function in the context of a child process. The function remains in the server’s address space, so subsequent requests can be handled at the cost of a simple function call. This can have a significant impact on the throughput of a busy site. Further, existing functions can be updated and new functions can be added at run-time, without stopping the server. Linux and Solaris systems provide a simple interface to the dynamic linker that allows application programs to load and link shared libraries at run time. #include <dlfcn.h> void *dlopen(const char *filename, int flag); returns: ptr to handle if OK, NULL on error 7.12. *POSITION-INDEPENDENT CODE (PIC) 377 The dlopen function loads and links the shared library filename. The external symbols in filename are resolved using libraries previously opened with the RTLD GLOBAL flag. If the current executable was compiled with the -rdynamic flag, then its global symbols are also available for symbol resolution. The flag argument must include either RTLD NOW, which tells the linker to resolve references to external symbols immediately, or the RTLD LAZY flag, which instructs the linker to defer symbol resolution until code from the library is executed. Either of these values can be or’d with the RTLD GLOBAL flag. #include <dlfcn.h> void *dlsym(void *handle, char *symbol); returns: ptr to symbol if OK, NULL on error The dlsym function takes a handle to a previously opened shared library and a symbol name, and returns the address of the symbol, if it exists, or NULL otherwise. #include <dlfcn.h> int dlclose (void *handle); returns: 0 if OK, -1 on error The dlclose function unloads the shared library if no other shared libraries are still using it. #include <dlfcn.h> const char *dlerror(void); returns: error msg if previous call to dlopen, dlsym, or dlclose failed, NULL if previous call was OK The dlerror function returns a string describing the most recent error that occurred as a result of calling dlopen, dlsym, or dlclose, or NULL if no error occurred. Figure 7.16 shows how we would use this interface to dynamically link our libvector.so shared library (Figure 7.5), and then invoke its addvec routine. To compile the program, we would invoke GCC in the following way: unix> gcc -rdynamic -O2 -o p3 main3.c -ldl 7.12 *Position-Independent Code (PIC) A key motivation for shared libraries is to allow multiple running processes to share the same library code in memory, and thus save precious memory resources. So how might multiple processes share a single copy of a program? One approach would be to assign a priori a dedicated chunk of the address space to each shared library, and then require the loader to always load the shared library at that address. While 378 CHAPTER 7. LINKING code/link/dll.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #include <stdio.h> #include <dlfcn.h> int x[2] = {1, 2}; int y[2] = {3, 4}; int z[2]; int main() { void *handle; void (*addvec)(int *, int *, int *, int); char *error; /* dynamically load the shared library that contains addvec() */ handle = dlopen("./libvector.so", RTLD_LAZY); if (!handle) { fprintf(stderr, "%s\n", dlerror()); exit(1); } /* get a pointer to the addvec() function we just loaded */ addvec = dlsym(handle, "addvec"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); exit(1); } /* Now we can call addvec() it just like any other function */ addvec(x, y, z, 2); printf("z = [%d %d]\n", z[0], z[1]); /* unload the shared library */ if (dlclose(handle) < 0) { fprintf(stderr, "%s\n", dlerror()); exit(1); } return 0; } code/link/dll.c Figure 7.16: An application program that dynamically loads and links the shared library libvector.so. 7.12. *POSITION-INDEPENDENT CODE (PIC) 379 straightforward, this approach creates some serious problems. It would be an inefficient use of the address space since portions of the space would be allocated even if a process didn’t use the library. Second, it would difficult to manage. We would have to ensure that none of the chunks overlapped. Every time a library was modified we would have to make sure that it still fit in its assigned chunk. If not, then we would have to find a new chunk. And if we created a new library, we would have to find room for it. Over time, given the hundreds of libraries and versions of libraries in a system, it would be difficult to keep the address space from fragmenting into lots of small unused but unusable holes. Even worse, the assignment of libraries to memory would be different for each system, thus creating even more management headaches. A better approach is to compile library code so that it can be loaded and executed at any address without being modified by the linker. Such code is known as position-independent code (PIC). Users direct GNU compilation systems to generate PIC code with the -fPIC option to GCC. On IA32 systems, calls to procedures in the same object module require no special treatment, since the references are PC-relative, with known offsets, and hence are already PIC (see Problem 7.4). However, calls to externally-defined procedures and references to global variables are not normally PIC, since they require relocation at link time. PIC Data References Compilers generate PIC references to global variables by exploiting the following interesting fact: No matter where we load an object module (including shared object modules) in memory, the data segment is always allocated immediately after the code segment. Thus, the distance between any instruction in the code segment and any variable in the data segment is a run-time constant, independent of the absolute memory locations of the code and data segments. To exploit this fact, the compiler creates a table called the global offset table (GOT) at the beginning of the data segment. The GOT contains an entry for each global data object that is referenced by the object module. The compiler also generates a relocation record for each entry in the GOT. At load time, the dynamic linker relocates each entry in the GOT so that it contains the appropriate absolute address. Each object module that references global data has its own GOT. At run time, each global variable is referenced indirectly through the GOT using code of the form: call L1: popl addl movl movl L1 %ebx; $VAROFF, %ebx (%ebx), %eax (%eax), %eax # ebx contains the current PC # ebx points to the GOT entry for var # reference indirect through the GOT In this fascinating piece of code, the call to L1 pushes the return address (which happens to be the address of the popl instruction) on the stack. The popl instruction then pops this address into %ebx. The net effect of these two instructions is to move the value of the PC into register %ebx. The addl instruction adds a constant offset to %ebx so that it points to the appropriate entry in the GOT, which contains the absolute address of the data item. At this point, the global variable can be referenced indirectly through the GOT entry contained in %ebx. In the example above, the two movl instructions load the contents of the global variable (indirectly through the GOT) into register %eax. 380 CHAPTER 7. LINKING PIC code has performance disadvantages. Each global variable reference now requires five instructions instead of one, with an additional memory reference to the GOT. Also, PIC code uses an additional register to hold the address of the GOT entry. On machines with large register files, this is not a major issue. But on register-starved IA32 systems, losing even one register can trigger spilling of the registers onto the stack. PIC Function Calls It would certainly be possible for PIC code to use the same approach for resolving external procedure calls: call L1: popl addl call L1 %ebx; $PROCOFF, %ebx *(%ebx) # ebx contains the current PC # ebx points to GOT entry for proc # call indirect through the GOT However, this approach would require three additional instructions for each run-time procedure call. Instead, ELF compilation systems use an interesting technique, called lazy binding, that defers the binding of procedure addresses until the first time the procedure is called. There is a nontrivial run-time overhead the first time the procedure is called, but each call thereafter only costs a single instruction and a memory reference for the indirection. Lazy binding is implemented with a compact yet somewhat complex interaction between two data structures: the GOT and the procedure linkage table (PLT). If an object module calls any functions that are defined in shared libraries, then it has its own GOT and PLT. The GOT is part of the .data section. The PLT is part of the .text section. Figure 7.17 shows the format of the GOT for the example program main2.o from Figure 7.6. The first three GOT entries are special: GOT[0] contains the address of the .dynamic segment, which contains information that the dynamic linker uses to bind procedure addresses, such as the location of the symbol table and relocation information. GOT[1] contains some information that defines this module. GOT[2] contains an entry point into the lazy binding code of the dynamic linker. Address 08049674 08049678 0804967c 08049680 08049684 Entry GOT[0] GOT[1] GOT[2] GOT[3] GOT[4] Contents 0804969c 4000a9f8 4000596f 0804845a 0804846a Description address of .dynamic section identifying info for the linker entry point in dynamic linker address of pushl in PLT[1] (printf) address of pushl in PLT[2] (addvec) Figure 7.17: The global offset table (GOT) for executable p2. The original code is in Figures 7.5 and 7.6. Each procedure that is defined in a shared object and called by main2.o gets an entry in the GOT, starting with entry GOT[3]. For the example program, we have shown the GOT entries for printf, which is defined in libc.so and addvec, which is defined in libvector.so. Figure 7.18 shows the PLT for our example program p2. The PLT is an array of 16-byte entries. The first entry, PLT[0], is a special entry that jumps into the dynamic linker. Each called procedure has an entry in the 7.13. TOOLS FOR MANIPULATING OBJECT FILES 381 PLT, starting at PLT[1]. In the figure, PLT[1] corresponds to printf and PLT[2] corresponds to addvec. PLT[0] 08048444: 804844a: 8048450: 8048452: ff ff 00 00 35 78 96 04 08 25 7c 96 04 08 00 00 pushl 0x8049678 jmp *0x804967c # # # # push &GOT[1] jmp to *GOT[2](linker) padding padding PLT[1] <printf> 8048454: ff 25 80 96 04 08 804845a: 68 00 00 00 00 804845f: e9 e0 ff ff ff PLT[2] <addvec> 8048464: ff 25 84 96 04 08 804846a: 68 08 00 00 00 804846f: e9 d0 ff ff ff <other PLT entries> jmp pushl jmp *0x8049680 $0x0 8048444 # jmp to *GOT[3] # ID for printf # jmp to PLT[0] jmp pushl jmp *0x8049684 $0x8 8048444 # jump to *GOT[4] # ID for addvec # jmp to PLT[0] Figure 7.18: The procedure linkage table (PLT) for executable p2. The original code is in Figures 7.5 and 7.6. Initially, after the program has been dynamically linked and begins executing, procedures printf and addvec are bound to the first instruction in their respective PLT entries. For example, the call to addvec has the form: 80485bb: e8 a4 fe ff ff call 8048464 <addvec> When addvec is called the first time, control passes to the first instruction in PLT[2], which does an indirect jump through GOT[4]. Initially, each GOT entry contains the address of the pushl entry in the corresponding PLT entry. So the indirect jump in the PLT simply transfers control back to the next instruction in PLT[2]. This instruction pushes an ID for the addvec symbol onto the stack. The last instruction jumps to PLT[0], which pushes another word of identifying information on the stack from GOT[1], and then jumps into the dynamic linker indirectly through GOT[2]. The dynamic linker uses the two stack entries to determine the location of addvec, overwrites GOT[4] with this address, and passes control to addvec. The next time addvec is called in the program, control passes to PLT[2] as before. However, this time the indirect jump through GOT[4] transfers control to addvec. The only additional overhead from this point on is the memory reference for the indirect jump. 7.13 Tools for Manipulating Object Files There are a number of tools available on Unix systems to help you understand and manipulate object files. In particular, the GNU binutils package is especially helpful and runs on every Unix platform. 382 AR : CHAPTER 7. LINKING Creates static libraries, and inserts, deletes, lists, and extracts members. Lists all of the printable strings contained in an object file. STRINGS: STRIP: NM : SIZE: Deletes symbol table information from an object file. Lists the symbols defined in the symbol table of an object file. Lists the names and sizes of the sections in an object file. Displays the complete structure of an object file, including all of the information encoded in the ELF header. Subsumes the functionality of SIZE and NM. The mother of all binary tools. Can display all of the information in an object file. Its most useful function is disassembling the binary instructions in the .text section. READELF: OBJDUMP: Unix systems also provide the ldd program for manipulating shared libraries: LDD : Lists the shared libraries that an executable needs at run time. 7.14 Summary We have learned that linking can be performed at compile time by static linkers, and at load time and run time by dynamic linkers. The main tasks of linkers are symbol resolution, where each global symbol is bound to a unique definition, and relocation, where the ultimate memory address for each symbol is determined and where references to those objects are modified. Static linkers combine multiple relocatable object files into a single executable object file. Multiple object files can define the same symbol, and the rules that linkers use for silently resolving these multiple definitions can introduce subtle bugs in user programs. Multiple object files can be concatenated in a single static library. Linkers use libraries to resolve symbol references in other object modules. The left-to-right sequential scan that many linkers use to resolve symbol references is another source of confusing link-time errors. Loaders map the contents of executable files into memory and run the program. Linkers can also produce partially linked executable object files with unresolved references to the routines and data defined in shared library. At load time, the loader maps the partially linked executable into memory and then calls a dynamic linker, which completes the linking task by loading the shared library and relocating the references in the program. Shared libraries that are compiled as position-independent code can be loaded anywhere and shared at run time by multiple processes. Applications can also use the dynamic linker at run time in order to load, link, and access the functions and data in shared libraries. Bibliographic Notes Linking is not well documented in the computer science literature. We think there are several reasons for this. First, linking lies at the intersection of compilers, computer architecture, and operating systems, 7.14. SUMMARY 383 requiring understanding of code generation, machine language programming, program instantiation, and virtual memory. It does not fit neatly into any of the usual computer science specialties, and thus is not well covered well by the classic texts in these areas. However, Levine’s monograph is a good general reference on the subject [44]. The original specifications for ELF and DWARF (a specification for the contents of the .debug and .line sections) are described in [32]. Some interesting research and commercial activity centers around the notion of binary translation, where the contents of an object file are parsed, analyzed, and modified. Binary translation is typically for three purposes [43]: to emulate one system on another system, to observe program behavior, or to perform systemdependent optimizations that are not possible at compile time. Commercial products such as VTune, Purify, and BoundsChecker use binary translation to provide programmers with detailed observations of their programs. The Atom system provides a flexible mechanism for instrumenting Alpha executable object files and shared libraries with arbitrary C functions [70]. Atom has been used to build a myriad of analysis tools that trace procedure calls, profile instruction counts and memory referencing patterns, simulate memory system behavior, and isolate memory referencing errors. Etch [62] and EEL [43] provide roughly similar capabilities on different platforms. The Shade system uses binary translation for instruction profiling. [14]. Dynamo [2] and Dyninst [7] provide mechanisms for instrumenting and optimizing executables in memory, at run time. Smith and his colleagues have investigated binary translation for program profiling and optimization. [87]. Homework Problems Homework Problem 7.6 [Category 1]: Consider the following version of the swap.c function that counts the number of times it has been called. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 extern int buf; int *bufp0 = &buf[0]; static int *bufp1; static void incr() { static int count=0; count++; } void swap() { int temp; incr(); bufp1 = &buf[1]; temp = *bufp0; 384 20 21 22 CHAPTER 7. LINKING *bufp0 = *bufp1; *bufp1 = temp; } For each symbol that is defined and referenced in swap.o, indicate if it will have a symbol table entry in the .symtab section in module swap.o. If so, indicate the module that defines the symbol (swap.o or main.o), the symbol type (local, global, or extern) and the section (.text, .data, or .bss) it occupies in that module. Symbol buf bufp0 bufp1 swap temp incr count swap.o .symtab entry? Symbol type Module where defined Section Homework Problem 7.7 [Category 1]: Without changing any variable names, modify bar5.c on Page 360 so that foo5.c prints the correct values of x and y (i.e., the hex representations of integers 15213 and 15212). Homework Problem 7.8 [Category 1]: In this problem, let REF(x.i) --> DEF(x.k) denote that the linker will associate an arbitrary reference to symbol x in module i to the definition of x in module k. For each example below, use this notation to indicate how the linker would resolve references to the multiply-defined symbol in each module. If there is a link-time error (Rule 1), write “ERROR”. If the linker arbitrarily chooses one of the definitions (Rule 3), write “UNKNOWN”. A. /* Module 1 */ int main() { } /* Module 2 */ static int main=1; int p2() { } (a) REF(main.1) --> DEF(_____.___) (b) REF(main.2) --> DEF(_____.___) B. /* Module 1 */ int x; void main() { } /* Module 2 */ double x; int p2() { } 7.14. SUMMARY (a) REF(x.1) --> DEF(_____.___) (b) REF(x.2) --> DEF(_____.___) 385 C. /* Module 1 */ int x=1; void main() { } /* Module 2 */ double x=1.0; int p2() { } (a) REF(x.1) --> DEF(_____.___) (b) REF(x.2) --> DEF(_____.___) Homework Problem 7.9 [Category 1]: Consider the following program, which consists of two object modules: 1 2 3 4 5 6 7 8 /* foo6.c */ void p2(void); int main() { p2(); return 0; } 1 2 3 4 5 6 7 8 9 /* bar6.c */ #include <stdio.h> char main; void p2() { printf("0x%x\n", main); } When this program is compiled and executed on a Linux system, it prints the string “0x55\n” and terminates normally, even though p2 never initializes variable main. Can you explain this? Homework Problem 7.10 [Category 1]: Let a and b denote object modules or static libraries in the current directory, and let a b denote that a depends on b, in the sense that b defines a symbol that is referenced by a. For each of the following scenarios, show the minimal command line (i.e., one with the least number of file object file and library arguments) that will allow the static linker to resolve all symbol references. A. p.o B. p.o C. p.o libx.a libx.a libx.a p.o. liby.a and liby.a liby.a libx.a. libx.a libz.a. libz.a and liby.a Homework Problem 7.11 [Category 1]: 386 CHAPTER 7. LINKING The segment header in Figure 7.12 indicates that the data segment occupies 0x104 bytes in memory. However, only the first 0xe8 bytes of these come from the sections of the executable file. Why the discrepancy? Homework Problem 7.12 [Category 2]: The swap routine in Figure 7.10 contains five relocated references. For each relocated reference, give its line number in Figure 7.10, its run-time memory address, and its value. The original code and relocation entries in the swap.o module are shown in Figure 7.19. Line # in Fig.7.10 Address Value 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 00000000 <swap>: 0: 55 1: 8b 15 00 00 00 00 7: c: e: 15: a1 04 00 00 00 89 e5 c7 05 00 00 00 00 04 00 00 00 push %ebp mov 0x0,%edx 3: R_386_32 bufp0 mov 0x4,%eax 8: R_386_32 buf mov %esp,%ebp movl $0x4,0x0 10: R_386_32 bufp1 14: R_386_32 buf mov %ebp,%esp mov (%edx),%ecx mov %eax,(%edx) mov 0x0,%eax 1f: R_386_32 bufp1 mov %ecx,(%eax) pop %ebp ret get *bufp0=&buf[0] relocation entry get buf[1] relocation entry bufp1 = &buf[1]; relocation entry relocation entry temp = buf[0]; buf[0]=buf[1]; get *bufp1=&buf[1] relocation entry buf[1]=temp; 18: 1a: 1c: 1e: 23: 25: 26: 89 8b 89 a1 ec 0a 02 00 00 00 00 89 08 5d c3 Figure 7.19: Code and relocation entries for Problem 7.13 Homework Problem 7.13 [Category 3]: Consider the C code and corresponding relocatable object module in Figure 7.20. A. Determine which instructions in .text will need to be modified by the linker when the module is relocated. For each such instruction, list the information in its relocation entry: section offset, relocation type, and symbol name. 7.14. SUMMARY 387 B. Determine which data objects in .data will need to be modified by the linker when the module is relocated. For each such instruction, list the information in its relocation entry: section offset, relocation type, and symbol name. Feel free to use tools such as OBJDUMP to help you solve this problem. Homework Problem 7.14 [Category 3]: Consider the C code and corresponding relocatable object module in Figure 7.21. A. Determine which instructions in .text will need to be modified by the linker when the module is relocated. For each such instruction, list the information in its relocation entry: section offset, relocation type, and symbol name. B. Determine which data objects in .rodata will need to be modified by the linker when the module is relocated. For each such instruction, list the information in its relocation entry: section offset, relocation type, and symbol name. Feel free to use tools such as OBJDUMP to help you solve this problem. Homework Problem 7.15 [Category 3]: Performing the following tasks will help you become more familiar with the various tools for manipulating object files. A. How many object files are contained in the versions of libc.a and libm.a on your system? B. Does gcc -O2 produce different executable code than gcc -O2 -g? C. What shared libraries does the GCC driver on your system use? 388 CHAPTER 7. LINKING 1 2 3 4 5 6 7 8 9 10 extern int p3(void); int x = 1; int *xp = &x; void p2(int y) { } void p1() { p2(*xp + p3()); } (a) C code. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 00000000 <p2>: 0: 55 1: 89 e5 3: 89 ec 5: 5d 6: c3 00000008 <p1>: 8: 55 9: 89 e5 b: 83 ec 08 e: 83 c4 f4 11: e8 fc ff ff ff 16: 89 c2 18: a1 00 00 00 00 1d: 03 10 1f: 52 20: e8 fc ff ff ff 25: 89 ec 27: 5d 28: c3 push mov mov pop ret %ebp %esp,%ebp %ebp,%esp %ebp push mov sub add call mov mov add push call mov pop ret %ebp %esp,%ebp $0x8,%esp $0xfffffff4,%esp 12 <p1+0xa> %eax,%edx 0x0,%eax (%eax),%edx %edx 21 <p1+0x19> %ebp,%esp %ebp (b) .text section of relocatable object file. 1 2 3 4 00000000 <x>: 0: 01 00 00 00 00000004 <xp>: 4: 00 00 00 00 (c) .data section of relocatable object file. Figure 7.20: Example code for Problem 7.13. 7.14. SUMMARY 389 1 2 3 4 5 6 7 8 9 10 11 12 13 14 int relo3(int val) { switch (val) { case 100: return(val); case 101: return(val+1); case 103: case 104: return(val+3); case 105: return(val+5); default: return(val+6); } } (a) C code. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 00000000 <relo3>: 0: 55 1: 89 e5 3: 8b 45 08 6: 8d 50 9c 9: 83 fa 05 c: 77 17 e: ff 24 95 00 00 00 00 15: 40 16: eb 10 18: 83 c0 03 1b: eb 0b 1d: 8d 76 00 20: 83 c0 05 23: eb 03 25: 83 c0 06 28: 89 ec 2a: 5d 2b: c3 push mov mov lea cmp ja jmp inc jmp add jmp lea add jmp add mov pop ret %ebp %esp,%ebp 0x8(%ebp),%eax 0xffffff9c(%eax),%edx $0x5,%edx 25 <relo3+0x25> *0x0(,%edx,4) %eax 28 <relo3+0x28> $0x3,%eax 28 <relo3+0x28> 0x0(%esi),%esi $0x5,%eax 28 <relo3+0x28> $0x6,%eax %ebp,%esp %ebp (b) .text section of relocatable object file. This is the jump table for the switch statement 1 2 0000 28000000 15000000 25000000 18000000 0010 18000000 20000000 4 words at offsets 0x0,0x4,0x8, and 0xc 2 words at offsets 0x10 and 0x14 (c) .rodata section of relocatable object file. Figure 7.21: Example code for Problem 7.14. 390 CHAPTER 7. LINKING Chapter 8 Exceptional Control Flow From the time you first apply power to a processor until the time you shut it off, the program counter assumes a sequence of values ¼ ½ Ò ½ where each is the address of some corresponding instruction Á . Each transition from to ·½ is called a control transfer. A sequence of such control transfers is called the flow of control, or control flow of the processor. The simplest kind of control flow is a smooth sequence where each Á and Á ·½ are adjacent in memory. Typically, abrupt changes to this smooth flow, where Á ·½ is not adjacent to Á , are caused by familiar program instructions such as jumps, calls, and returns. Such instructions are necessary mechanisms that allow programs to react to changes in internal program state represented by program variables. But systems must also be able to react to changes in system state that are not captured by internal program variables and are not necessarily related to the execution of the program. For example, a hardware timer goes off at regular intervals and must be dealt with. Packets arrive at the network adapter and must be stored in memory. Programs request data from a disk and then sleep until they are notified that the data are ready. Parent processes that create child processes must be notified when their children terminate. Modern systems react to these situations by making abrupt changes in the control flow. We refer to these abrupt changes in general as exceptional control flow. Exceptional control flow occurs at all levels of a computer system. For example, at the hardware level, events detected by the hardware trigger abrupt control transfers to exception handlers. At the operating systems level, the kernel transfers control from one user process to another via context switches. At the application level, a process can send a Unix signal to another process that abruptly transfers control to a signal handler in the recipient. An individual program can react to errors by sidestepping the usual stack discipline and making nonlocal jumps to arbitrary locations in other functions (similar to the exceptions supported by C++ and Java). This chapter describes these various forms of exceptional control, and shows you how to use them in your C programs. The techniques you will learn about — creating processes, reaping terminated processes, sending and receiving signals, making non-local jumps — are the foundation of important programs such as Unix shells (Problem 8.20) and Web servers (Chapter 12). 391 392 CHAPTER 8. EXCEPTIONAL CONTROL FLOW 8.1 Exceptions Exceptions are a form of exceptional control flow that are implemented partly by the hardware and partly by the operating system. Because they are partly implemented in hardware, the details vary from system to system. However, the basic ideas are the same for every system. Our aim in this section is to give you a general understanding of exceptions and exception handling, and to help demystify what is often a confusing aspect of modern computer systems. An exception is an abrupt change in the control flow in response to some change in the processor’s state. Figure 8.1 shows the basic idea. Application program event occurs here Exception handler exception exception processing exception return (optional) Icurr Inext Figure 8.1: Anatomy of an exception. A change in the processor’s state (event) triggers an abrupt control transfer (an exception) from the application program to an exception handler. After it finishes processing, the handler either returns control to the interrupted program or aborts. In the figure, the processor is executing some current instruction Á ÙÖÖ when a significant change in the processor’s state occurs. The state is encoded in various bits and signals inside the processor. The change in state is known as an event. The event might be directly related to the execution of the current instruction. For example, a virtual memory page fault occurs, an arithmetic overflow occurs, or an instruction attempts a divide by zero. On the other hand, the event might be unrelated to the execution of the current instruction. For example, a system timer goes off or an I/O request completes. In any case, when the processor detects that the event has occurred, it makes an indirect procedure call (the exception), through a jump table called an exception table, to an operating system subroutine (the exception handler) that is specifically designed to process this particular kind of event. When the exception handler finishes processing, one of three things happens, depending on the type of event that caused the exception: 1. The handler returns control to the current instruction the event occurred. 2. The handler returns control to ÁÒ not occurred. ÜØ Á ÙÖÖ , the instruction that was executing when , the instruction that would have executed next had the exception 3. The handler aborts the interrupted program. Section 8.1.2 says more about these possibilities. 8.1. EXCEPTIONS 393 8.1.1 Exception Handling Exceptions can be difficult to understand because handling them involves close cooperation between hardware and software. It is easy to get confused about which component performs which task. Let’s look at the division of labor between hardware and software in more detail. Each type of possible exception in a system is assigned a unique non-negative integer exception number. Some of these numbers are assigned by the designers of the processor. Other numbers are assigned by the designers of the operating system kernel (the memory-resident part of the operating system). Examples of the former include divide by zero, page faults, memory access violations, breakpoints, and arithmetic overflows. Examples of the latter include system calls and signals from external I/O devices. At system boot time (when the computer is reset or powered on) the operating system allocates and initializes a jump table called an exception table, so that entry contains the address of the handler for exception . Figure 8.2 shows the format of an exception table. code for code for exception handler 00 exception handler exception table 0 1 2 n-1 code for code for exception handler 11 exception handler code for code for exception handler 22 exception handler ... ... code for code for exception handler n-1 exception handler n-1 Figure 8.2: Exception table. The exception table is a jump table where entry handler code for exception . contains the address of the At runtime (when the system is executing some program), the processor detects that an event has occurred and determines the corresponding exception number . The processor then triggers the exception by making an indirect procedure call, through entry of the exception table, to the corresponding handler. Figure 8.3 shows how the processor uses the exception table to form the address of the appropriate exception handler. The exception number is an index into the exception table, whose starting address is contained in a special CPU register called the exception table base register. exception number (x 4) Address of entry for exception # k 0 1 2 n-1 exception table exception table base register + ... Figure 8.3: Generating the address of an exception handler. The exception number is an index into the exception table. 394 CHAPTER 8. EXCEPTIONAL CONTROL FLOW An exception is akin to a procedure call, but with some important differences. ¯ ¯ ¯ ¯ As with a procedure call, the processor pushes a return address on the stack before branching to the handler. However, depending on the class of exception, the return address is either the current instruction (the instruction that was executing when the event occurred) or the next instruction (the instruction that would have executed after the current instruction had the event not occurred). The processor also pushes some additional processor state onto the stack that will be necessary to restart the interrupted program when the handler returns. For example, an IA32 system pushes the EFLAGS register containing, among other things, the current condition codes, onto the stack. If control is being transferred from a user program to the kernel, all of the above items are pushed on the kernel’s stack rather than the user’s stack. Exception handlers run in kernel mode (Section 8.2.3, which means they have complete access to all system resources. Once the hardware triggers the exception, the rest of the work is done in software by the exception handler. After the handler has processed the event, it optionally returns to the interrupted program by executing a special “return from interrupt” instruction, which pops the appropriate state back into the processor’s control and data registers, restores the state to user mode (Section 8.2.3) if the exeption interrupted a user program, and then returns control to the interrupted program. 8.1.2 Classes of Exceptions Exceptions can be divided into four classes: interrupts, traps, faults, and aborts. Figure 8.4 summarizes the attributes of these classes. Class Interrupt Trap Fault Abort Cause Signal from I/O device Intentional exception Potentially recoverable error Nonrecoverable error Async/Sync Async Sync Sync Sync Return behavior always returns to next instruction Always returns to next instruction Might return to current instruction Never returns Figure 8.4: Classes of exceptions. Asynchronous exceptions occur as a result of events external to the processor. Synchronous exceptions occur as a direct result of executing an instruction. Interrupts Interrupts occur asynchronously as a result of signals from I/O devices that are external to the processor. Hardware interrupts are asynchronous in the sense that they are not caused by the execution of any particular instruction. Exception handlers for hardware interrupts are often called interrupt handlers. 8.1. EXCEPTIONS 395 Figure 8.5 summarizes the processing for an interrupt. I/O devices such as network adapters, disk controllers, and timer chips trigger interrupts by signalling a pin on the processor chip and placing the exception number on the system bus that identifies the device that caused the interrupt. (1) interrupt pin goes high during I curr execution of Inext current instruction (2) control passes to handler after current instruction finishes (3) interrupt handler runs (4) handler returns to next instruction Figure 8.5: Interrupt handling. The interrupt handler returns control to the next instruction in the application program’s control flow. After the current instruction finishes executing, the processor notices that the interrupt pin has gone high, reads the exception number from the system bus, and then calls the appropriate interrupt handler. When the handler returns, it returns control to the next instruction (i.e., the instruction that would have followed the current instruction in the control flow had the interrupt not occurred). The effect is that the program continues executing as though the interrupt had never happened. The remaining classes of exceptions (traps, faults, and aborts) occur synchronously as a result of executing the current instruction. We refer to this instruction as the faulting instruction. Traps Traps are intentional exceptions that occur as a result of executing an instruction. Like interrupt handlers, trap handlers return control to the next instruction. The most important use of traps is to provide a procedurelike interface between user programs and the kernel known as a system call. User programs often need to request services from the kernel such as reading a file ( read), creating a new process (fork), loading a new program (execve), or terminating the current process (exit). To allow controlled access to such kernel services, processors provide a special “syscall Ò” instruction that user programs can execute when they want to request service Ò. Executing the syscall instruction causes a trap to an exception handler that decodes the argument and calls the appropriate kernel routine. Figure 8.6 summarizes the processing for a system call. From a programmer’s perspective, a system call is identical (1) Application syscall makes a Inext system call (2) control passes to handler (3) trap handler runs (4) handler returns to instruction following the syscall Figure 8.6: Trap handling. The trap handler returns control to the next instruction in the application program’s control flow. to a regular function call. However, their implementations are quite different. Regular functions run in 396 CHAPTER 8. EXCEPTIONAL CONTROL FLOW user mode, which restricts the types of instructions they can execute, and they access the same stack as the calling function. A system call runs in kernel mode, which allows it to execute instructions, and accesses a stack defined in the kernel. Section 8.2.3 discusses user and kernel modes in more detail. Faults Faults result from error conditions that a handler might be able to correct. When a fault occurs, the processor transfers control to the fault handler. If the handler is able to correct the error condition, it returns control to the faulting instruction, thereby reexecuting it. Otherwise, the handler returns to an abort routine in the kernel that terminates the application program that caused the fault. Figure 8.7 summarizes the processing for a fault. (1) Current Icurr instruction causes a fault (2) control passes to handler (3) fault handler runs (4) handler either reexecutes current instruction or aborts. abort Figure 8.7: Fault handling. Depending on the whether the fault can be repaired or not, the fault handler either re-executes the faulting instruction or aborts. A classic example of a fault is the page fault exception, which occurs when an instruction references a virtual address whose corresponding physical page is not resident in memory and must be retrieved from disk. As we will see in Chapter 10, a page is contiguous block (typically 4 KB) of virtual memory. The page fault handler loads the appropriate page from disk and then returns control to the instruction that caused the fault. When the instruction executes again, the appropriate physical page is resident in memory and the instruction is able to run to completion without faulting. Aborts Aborts result from unrecoverable fatal errors, typically hardware errors such as parity errors that occur when DRAM or SRAM bits are corrupted. Abort handlers never return control to the application program. As shown in Figure 8.8, the handler returns control to an abort routine that terminates the application program. (1) fatal hardware I curr error occurs (2) control passes to handler (3) abort handler runs (4) handler returns to abort routine abort Figure 8.8: Abort handling. The abort handler passes control to a kernel abort routine that terminates the application program. 8.1. EXCEPTIONS 397 8.1.3 Exceptions in Intel Processors To help make things more concrete, let’s look at some of the exceptions defined for Intel systems. A Pentium system can have up to 256 different exception types. Numbers in the range 0 to 31 correspond to exceptions that are defined by the Pentium architecture, and thus are identical for any Pentium-class system. Numbers in the range 32 to 255 correspond to interrupts and traps that are defined by the operating system. Figure 8.9 shows a few examples. Exception Number 0 13 14 18 32–127 128 (0x80) 129–255 Description divide error general protection fault page fault machine check OS-defined exceptions system call OS-defined exceptions Exception Class fault fault fault abort interrupt or trap trap interrupt or trap Figure 8.9: Examples of exceptions in Pentium systems. A divide error (exception 0) occurs when an application attempts to divide by zero, or when the result of a divide instruction is too big for the destination operand. Unix does not attempt to recover from divide errors, opting instead to abort the program. Unix shells typically report divide errors as “Floating exceptions”. The infamous general protection fault (exception 13) occurs for many reasons, usually because a program references an undefined area of virtual memory, or because the program attempts to write to a read-only text segment. Unix does not attempt to recover from this fault. Unix shells typically report general protection faults as “Segmentation faults”. A page fault (exception 14) is an example of an exception where the faulting instruction is restarted. The handler maps the appropriate page of physical memory on disk into a page of virtual memory, and then restarts the faulting instruction. We will see how this works in detail in Chapter 10. A machine check (exception 18) occurs as a result of a fatal hardware error that is detected during the execution of the faulting instruction. Machine check handlers never return control to the application program. System calls are provided on IA32 systems via a trapping instruction called INT Ò, where Ò can be the index of any of the 256 entries in the exception table. Historically, systems calls are provided through exception 128 (0x80). Aside: A note on terminology. The terminology for the various classes of exceptions varies from system to system. Processor macro-architecture specifications often distinguish between asynchronous “interrupts” and synchronous “exceptions”, yet provide no umbrella term to refer to these very similar concepts. To avoid having to constantly refer to “exceptions and interrupts” and “exceptions or interrupts”, we use the word “exception” as the general term and distinguish between asynchronous exceptions (interrupts) and synchronous exceptions (traps, faults, and aborts) only when it is appropriate. As we have noted, the basic ideas are the same for every system, but you should be aware that some manufacturers’ manuals use the word “exception” to refer only to those changes in control flow caused by synchronous events. End Aside. 398 CHAPTER 8. EXCEPTIONAL CONTROL FLOW 8.2 Processes Exceptions provide the basic building blocks that allow the operating system to provide the notion of a process, one of the most profound and successful ideas in computer science. When we run a program on a modern system, we are presented with the illusion that our program is the only one currently running in the system. Our program appears to have exclusive use of both the processor and the memory. The processor appears to execute the instructions in our program, one after the other, without interruption. And the code and data of our program appear to be the only objects in the system’s memory. These illusions are provided to us by the notion of a process. The classic definition of a process is an instance of a program in execution. Each program in the system runs in the context of some process. The context consists of the state that the program needs to run correctly. This state includes the program’s code and data stored in memory, its stack, the contents of its general-purpose registers, its program counter, environment variables, and the set of open file descriptors. Each time a user runs a program by typing the name of an executable object file to the shell, the shell creates a new process and then runs the executable object file in the context of this new process. Application programs can also create new processes and run either their own code or other applications in the context of the new process. A detailed discussion of how operating systems implement processes is beyond our scope. Instead we will focus on the key abstractions that a process provides to the application: ¯ ¯ An independent logical control flow that provides the illusion that our program has exclusive use of the processor. A private address space that provides the illusion that our program has exclusive use of the memory system. Let’s look more closely at these abstractions. 8.2.1 Logical Control Flow A process provides each program with the illusion that it has exclusive use of the processor, even though many other programs are typically running on the system. If we were to use a debugger to single step the execution of our program, we would observe a series of program counter (PC) values that corresponded exclusively to instructions contained in our program’s executable object file or in shared objects linked into our program dynamically at run time. This sequence of PC values is known as a logical control flow. Consider a system that runs three processes, as shown in Figure 8.10. The single physical control flow of the processor is partitioned into three logical flows, one for each process. Each vertical line represents a portion of the logical flow for a process. In the example, process A runs for a while, followed by B, which runs to completion. Then C runs for awhile, followed by A, which runs to completion. Finally, C is able to run to completion. The key point in Figure 8.10 is that processes take turns using the processor. Each process executes a portion of its flow and then is preempted (temporarily suspended) while other processes take their turns. To 8.2. PROCESSES Process A Process B Process C 399 Time Figure 8.10: Logical control flows. Processes provide each program with the illusion that it has exclusive use of the processor. Each vertical bar represents a portion of the logical control flow for a process. a program running in the context of one of these processes, it appears to have exclusive use of the processor. The only evidence to the contrary is that if we were to precisely measure the elapsed time of each instruction (see Chapter 9), we would notice that the CPU appears to periodically stall between the execution of some of the instructions in our program. However, each time the processor stalls, it subsequently resumes execution of our program without any change to the contents of the program’s memory locations or registers. In general, each logical flow is independent of any other flow in the sense that the logical flows associated with different processes do not affect the states of any other processes. The only exception to this rule occurs when processes use interprocess communication (IPC) mechanisms such as pipes, sockets, shared memory, and semaphores to explicitly interact with each other. Any process whose logical flow overlaps in time with another flow is called a concurrent process, and the two processes are said to run concurrently. For example, in Figure 8.10, processes A and B run concurrently, as do A and C. On the other hand, B and C do not run concurrently because the last instruction of B executes before the first instruction of C. The notion of processes taking turns with other processes is known as multitasking. Each time period that a process executes a portion of its flow is called a time slice. Thus, multitasking is also referred to as time slicing. 8.2.2 Private Address Space A process also provides each program with the illusion that it has exclusive use of the system’s address space. On a machine with Ò-bit addresses, the address space is the set of ¾Ò possible addresses, ¼, ½, . . . , Ò ¾ ½. A process provides each program with its own private address space. This space is private in the sense that a byte of memory associated with a particular address in the space cannot in general be read or written by any other process. Although the contents of the memory associated with each private address space is different in general, each such space has the same general organization. For example, Figure 8.11 shows the organization of the address space for a Linux process. The bottom three-fourths of the address space is reserved for the user program, with the usual text, data, heap, and stack segments. The top quarter of the address space is reserved for the kernel. This portion of the address space contains the code, data, and stack that the kernel 400 0xffffffff CHAPTER 8. EXCEPTIONAL CONTROL FLOW kernel virtual memory (code, data, heap, stack) 0xc0000000 memory invisible to user code %esp (stack pointer) user stack (created at runtime) 0x40000000 memory mapped region for shared libraries brk run-time heap (created at runtime by malloc) read/write segment (.data, .bss) read-only segment (.init, .text, .rodata) unused loaded from the executable file 0x08048000 0 Figure 8.11: Process address space. uses when it executes instructions on behalf of the process (e.g., when the application program executes a system call). 8.2.3 User and Kernel Modes In order for the operating system kernel to provide an airtight process abstraction, the processor must provide a mechanism that restricts the instructions that an application can execute, as well as the portions of the address space that it can access. Processors typically provide this capability with a mode bit in some control register that characterizes the privileges that the process currently enjoys. When the mode bit is set, the process is running in kernel mode (sometimes called supervisor mode). A process running in kernel mode can execute any instruction in the instruction set and access any memory location in the system. When the mode bit is not set, the process is running in user mode. A process in user mode is not allowed to execute privileged instructions that do things such as halt the processor, change the mode bit, or initiate an I/O operation. Nor is it allowed to directly reference code or data in the kernel area of the address space. Any such attempt results in a fatal protection fault. Instead, user programs must access kernel code and data indirectly via the system call interface. A process running application code is initially in user mode. The only way for the process to change from user mode to kernel mode is via an exception such as an interrupt, a fault, or a trapping system call. When the exception occurs, and control passes to the exception handler, the processor changes the mode from user mode to kernel mode. The handler runs in kernel mode. When it returns to the application code, the processor changes the mode from kernel mode back to user mode. 8.2. PROCESSES 401 Linux and Solaris provides a clever mechanism, called the /proc filesystem, that allows user mode processes to access the contents of kernel data structures. The /proc filesystem exports the contents of many kernel data structures as a hierarchy of ASCII files that can read by user programs. For example, you can use the Linux proc filesystem to find out general system attributes such as CPU type (/proc/cpuinfo), or the memory segments used by a particular process (/proc/<process id>/maps). 8.2.4 Context Switches The operating system kernel implements multitasking using a higher-level form of exceptional control flow known as a context switch. The context switch mechanism is built on top of the lower-level exception mechanism that we discussed in Section 8.1. The kernel maintains a context for each process. The context is the state that the kernel needs to restart a preempted process. It consists of the values of objects such as the general-purpose registers, the floatingpoint registers, the program counter, user’s stack, status registers, kernel’s stack, and various kernel data structures such as a page table that characterizes the address space, a process table that contains information about the current process, and a file table that contains information about the files that the process has opened. At certain points during the execution of a process, the kernel can decide to preempt the current process and restart a previously preempted process. This decision is known as scheduling, and is handled by a part of the kernel called the scheduler. When the kernel selects a new process to run, we say that the kernel has scheduled that process. After the kernel has scheduled a new process to run, it preempts the current process and transfers control to the new process using a mechanism called a context switch that (1) saves the context of the current process, (2) restores the saved context of some previously preempted process, and (3) passes control to this newly restored process. A context switch can occur while the kernel is executing a system call on behalf of the user. If the system call blocks because it is waiting for some event to occur, then the kernel can put the current process to sleep and switch to another process. For example, if a read system call requires a disk access, the kernel can opt to perform a context switch and run another process instead of waiting for the data to arrive from the disk. Another example is the sleep system call, which is an explicit request to put the calling process to sleep. In general, even if a system call does not block, the kernel can decide to perform a context switch rather than return control to the calling process. A context switch can also occur as a result of an interrupt. For example, all systems have some mechanism for generating periodic timer interrupts, typically every 1 ms or 10 ms. Each time a timer interrupt occurs, the kernel can decide that the current process has run long enough and switch to a new process. Figure 8.12 shows an example of context switching between a pair of processes A and B. In this example, initially process A is running in user mode until it traps to the kernel by executing a read system call. The trap handler in the kernel requests a DMA transfer from the disk controller and arranges for the disk to interrupt the processor after the disk controller has finished transferring the data from disk to memory. The disk will take a relatively long time to fetch the data (on the order of tens of milliseconds), so instead of waiting and doing nothing in the interim, the kernel performs a context switch from process A to B. Note that before the switch, the kernel is executing instructions in user mode on behalf of process A. During the 402 Process A Time CHAPTER 8. EXCEPTIONAL CONTROL FLOW Process B user code kernel code read() disk interrupt context switch context switch user code kernel code user code Figure 8.12: Anatomy of a context switch. first part of the switch, the kernel is executing instructions in kernel mode on behalf of process A. Then at some point it begins executing instructions (still in kernel mode) on behalf of process B. And after the switch, the kernel is executing instructions in user mode on behalf of process B. Process B then runs for a while in user mode until the disk sends an interrupt to signal that data has been transferred from disk to memory. The kernel decides that process B has run long enough and performs a context switch from process B to A, returning control in process A to the instruction immediately following the read system call. Process A continues to run until the next exception occurs, and so on. 8.3 System Calls and Error Handling Unix systems provide a variety of systems calls that application programs use when they want to request services from the kernel such as reading a file or creating a new process. For example, Linux provides about 160 system calls. Typing “man syscalls” will give you the complete list. C programs can invoke any system call directly by using the syscall macro described in “man 2 intro”. However, it is usually neither necessary nor desirable to invoke system calls directly. The standard C library provides a set of convenient wrapper functions for the most frequently used system calls. The wrapper functions package up the arguments, trap to the kernel with the appropriate system call, and then pass the return status of the system call back to the calling program. In our discussion in the following sections, we will refer to system calls and their associated wrapper functions interchangeably as system-level functions. When Unix system-level functions encounter an error, they typically return ½ and set the global integer variable errno to indicate what went wrong. Programmers should always check for errors, but unfortunately, many skip error checking because it bloats the code and makes it harder to read. For example, here is how we might check for errors when we call the Unix fork function: 1 2 3 4 if ((pid = fork()) < 0) { fprintf(stderr, "fork error: %s\n", strerror(errno)); exit(0); } The strerror function returns a text string that describes the error associated with a particular value of errno. We can simplify this code somewhat by defining the following error-reporting function: 8.4. PROCESS CONTROL 1 2 3 4 5 403 void unix_error(char *msg) /* unix-style error */ { fprintf(stderr, "%s: %s\n", msg, strerror(errno)); exit(0); } Given this function, our call to fork reduces from four lines to two lines: 1 2 if ((pid = fork()) < 0) unix_error("fork error"); We can simplify our code even further by using a error-handling wrappers. For a given base function foo, we define a wrapper function Foo with identical arguments, but with the first letter of the name capitalized. The wrapper calls the base function, checks for errors and terminates if there are any problems. For example, here is the error-handling wrapper for the fork function: 1 2 3 4 5 6 7 8 pid_t Fork(void) { pid_t pid; if ((pid = fork()) < 0) unix_error("Fork error"); return pid; } Given this wrapper, our call to fork shrinks to a single compact line: 1 pid = Fork(); We will use error-handling wrappers throughout the remainder of this book. They allow us to keep our code examples concise, without giving you the mistaken impression that it is permissible to ignore errorchecking. Note that when we discuss system-level functions in the text, we will always refer to them by their lower-case base names, rather than by their upper-case wrapper names. See Appendix A for a discussion of Unix error-handling and the error-handling wrappers used throughout the book. The wrappers are defined in a file called csapp.c and their prototypes are defined in a header file called csapp.h. For your reference, Appendix A provides the sources for these files. 8.4 Process Control Unix provides a number of system calls for manipulating processes from C programs. This section describes the important functions and gives examples of how they are used. 404 CHAPTER 8. EXCEPTIONAL CONTROL FLOW 8.4.1 Obtaining Process ID’s Each process has a unique positive (non-zero) process ID (PID). The getpid function returns the PID of the calling process. The getppid function returns the PID of its parent (i.e., the process that created the calling process). #include <unistd.h> #include <sys/types.h> pid t getpid(void); pid t getppid(void); returns: PID of either the caller or the parent The getpid and getppid routines return an integer value of type pid t, which on Linux systems is defined in types.h as an int. 8.4.2 Creating and Terminating Processes From a programmer’s perspective, we can think of a process as being in one of three states: ¯ ¯ ¯ Running. The process is either executing on the CPU, or is waiting to be executed and will eventually be scheduled. Stopped. The execution of the process is suspended and will not be scheduled. A process stops as a result of receiving a SIGSTOP, SIGTSTP, SIGTTIN, or SIGTTOU signal, and it remains stopped until it receives a SIGCONT signal, at which point is becomes running again. (A signal is a form of software interrupt that is described in detail in Section 8.5.) Terminated. The process is stopped permanently. A process becomes terminated for one of three reasons: (1) receiving a signal whose default action is to terminate the process; (2) returning from the main routine; or (3) calling the exit function: #include <stdlib.h> void exit(int status); this function does not return The exit function terminates the process with an exit status of status. (The other way to set the exit status is to return an integer value from the main routine.) A parent process creates a new running child process by calling the fork function. 8.4. PROCESS CONTROL #include <unistd.h> #include <sys/types.h> pid t fork(void); 405 returns: 0 to child, PID of child to parent, -1 on error The newly created child process is almost, but not quite, identical to the parent. The child gets an identical (but separate) copy of the parent’s user-level virtual address space, including the text, data, and bss segments, heap, and user stack. The child also gets identical copies of any of the parent’s open file descriptors, which means the child can read and write any files that were open in the parent when it called fork. The most significant difference between the parent and the newly created child is that they have different PIDs. The fork function is interesting (and often confusing) because it is called once but it returns twice: once in the calling process (the parent), and once in the newly created child process. In the parent, fork returns the PID of the child. In the child, fork returns a value of 0. Since the PID of the child is always nonzero, the return value provides an unambiguous way to tell whether the program is executing in the parent or the child. Figure 8.13 shows a simple example of a parent process that uses fork to create a child process. When the fork call returns in line 8, x has a value of 1 in both the parent and child. The child increments and prints its copy of x in line 10. Similarly, the parent decrements and prints its copy of x in line 15. code/ecf/fork.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include "csapp.h" int main() { pid_t pid; int x = 1; pid = Fork(); if (pid == 0) { /* child */ printf("child : x=%d\n", ++x); exit(0); } /* parent */ printf("parent: x=%d\n", --x); exit(0); } code/ecf/fork.c Figure 8.13: Using fork to create a new process. When we run the program on our Unix system, we get the following result: 406 unix> ./fork parent: x=0 child : x=2 CHAPTER 8. EXCEPTIONAL CONTROL FLOW There are some subtle aspects to this simple example. ¯ ¯ Call once, return twice. The fork function is called once by the parent, but it returns twice: once to the parent and once to the newly created child. This is fairly straightforward for programs that create a single child. But programs with multiple instances of fork can be confusing and need to be reasoned about carefully. Concurrent execution. The parent and the child are separate processes that run concurrently. The instructions in their logical control flows can be interleaved by the kernel in an arbitrary way. When we run the program on our system, the parent process completes its printf statement first, followed by the child. However, on another system the reverse might be true. In general, as programmers we can never make assumptions about the interleaving of the instructions in different processes. Duplicate but separate address spaces. If we could halt both the parent and the child immediately after the fork function returned in each process, we would see that the address space of each process is identical. Each process has the same user stack, the same local variable values, the same heap, the same global variable values, and the same code. Thus, in our example program, local variable x has a value of 1 in both the parent and the child when the fork function returns in line 8. However, since the parent and the child are separate processes, they each have their own private address spaces. Any subsequent changes that a parent or child makes to x are private and are not reflected in the memory of the other process. This is why the variable x has different values in the parent and child when they call their respective printf statements. Shared files. When we run the example program, we notice that both parent and child print their output on the screen. The reason is that the child inherits all of the parent’s open files. When the parent calls fork, the stdout file is open and directed to the screen. The child inherits this file and thus its output is also directed to the screen. ¯ ¯ When you are first learning about the fork function, it is often helpful to draw a picture of the process hierarchy. The process hierarchy is a labeled directed graph, where each node is a process and each directed arc denotes that is the parent of and that created by executing the Ø lexical instance of the fork function in the source code. For example, how many lines of output would the program in Figure 8.14(a) generate? Figure 8.14(b) shows the corresponding process hierarchy. The parent creates the child when it executes the first (and only) fork in the program. Both and call printf once, so the program prints two output lines. Now what if we were to call fork twice, as shown in Figure 8.14(c)? As we see from the process hierarchy in Figure 8.14(d), the parent creates child when it calls the first fork function. Then both and execute the second fork function, which results in the creations of and , for a total of four processes. Each process calls printf, so the program generates four output lines. Continuing this line of thought, what would happen if we were to call fork three times, as in Figure 8.14(e)? As we see from the process hierarchy in Figure 8.14(f), the first fork creates one process, the second fork 8.4. PROCESS CONTROL 407 1 2 3 4 5 6 7 8 #include "csapp.h" int main() { Fork(); printf("hello!\n"); exit(0); } a 1 b (a) Calls fork once. (b) Prints two output lines. 1 2 3 4 5 6 7 8 9 #include "csapp.h" int main() { Fork(); Fork(); printf("hello!\n"); exit(0); } a 1 b 2 2 c d (c) Calls fork twice. (d) Prints four output lines. 1 2 3 4 5 6 7 8 9 10 #include "csapp.h" int main() { Fork(); Fork(); Fork(); printf("hello!\n"); exit(0); } 3 e f g h a 1 b 2 2 c d 3 3 3 (e) Calls fork three times. (f) Prints eight output lines. Figure 8.14: Examples of programs and their process hierarchies. 408 CHAPTER 8. EXCEPTIONAL CONTROL FLOW creates two processes, and the third fork creates four processes, for a total of eight processes. Each process calls printf, so the program produces eight output lines. Practice Problem 8.1: Consider the following program: code/ecf/forkprob0.c 1 2 3 4 5 6 7 8 9 10 11 #include "csapp.h" int main() { int x = 1; if (Fork() == 0) printf("printf1: x=%d\n", ++x); printf("printf2: x=%d\n", --x); exit(0); } code/ecf/forkprob0.c A. What is the output of the child process? B. What is the output of the parent process? Practice Problem 8.2: How many “hello” output lines does this program print? code/ecf/forkprob1.c 1 2 3 4 5 6 7 8 9 10 11 #include "csapp.h" int main() { int i; for (i = 0; i < 2; i++) Fork(); printf("hello!\n"); exit(0); } code/ecf/forkprob1.c Practice Problem 8.3: How many “hello” output lines does this program print? code/ecf/forkprob4.c 8.4. PROCESS CONTROL 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 409 #include "csapp.h" void doit() { Fork(); Fork(); printf("hello\n"); return; } int main() { doit(); printf("hello\n"); exit(0); } code/ecf/forkprob4.c 8.4.3 Reaping Child Processes When a process terminates for any reason, the kernel does not remove it from the system immediately. Instead, the process is kept around in a terminated state until it is reaped by its parent. When the parent reaps the terminated child, the kernel passes the child’s exit status to the parent, and then discards the terminated process, at which point it ceases to exist. A terminated process that has not yet been reaped is called a zombie. Aside: Why are terminated children called zombies? In folklore, a zombie is a living corpse, an entity that is half-alive and half-dead. A zombie process is similar in the sense that while it has already terminated, the kernel maintains some of its state until it can be reaped by the parent. End Aside. If the parent process terminates without reaping its zombie children, the kernel arranges for the init process to reap them. The init process has a PID of 1 and is created by the kernel during system initialization. Long-running programs such as shells or servers should always reap their zombie children. Even though zombies are not running, they still consume system memory resources. A process waits for its children to terminate or stop by calling the waitpid function. #include <sys/types.h> #include <sys/wait.h> pid t waitpid(pid t pid, int *status, int options); returns: PID of child if OK, 0 (if WNOHANG) or -1 on error The waitpid function is complicated. By default (when options = 0), waitpid suspends execution of the calling process until a child process in its wait set terminates. If a process in the wait set has already 410 CHAPTER 8. EXCEPTIONAL CONTROL FLOW terminated at the time of the call, then waitpid returns immediately. In either case, waitpid returns the PID of the terminated child that caused waitpid to return, and the terminated child is removed from the system. Determining the Members of the Wait Set The members of the wait set are determined by the pid argument: ¯ ¯ If pid > 0, then the wait set is the singleton child process whose process ID is equal to pid. If pid = -1, then the wait set consists of all of the parent’s child processes. Aside: Waiting on sets of processes. The waitpid function also supports other kinds of wait sets, involving Unix process groups, that we will not discuss. End Aside. Modifying the Default Behavior The default behavior can be modified by setting options to various combinations of the WNOHANG and WUNTRACED constants: ¯ ¯ ¯ WNOHANG: Return immediately (with a return value of 0) if the none of the child processes in the wait set has terminated yet. WUNTRACED: Suspend execution of the calling process until a process in the wait set becomes terminated or stopped. Return the PID of the terminated or stopped child that caused the return. WNOHANG|WUNTRACED : Suspend execution of the calling process until a child in the wait set terminates or stops, and then return the PID of the stopped or terminated child that caused the return. Also, return immediately (with a return value of 0) if none of the processes in the wait set is terminated or stopped. Checking the Exit Status of a Reaped Child If the status argument is non-NULL, then waitpid encodes status information about the child that caused the return in the status argument. The wait.h include file defines several macros for interpreting the status argument: ¯ ¯ ¯ WIFEXITED(status): Returns true if the child terminated normally, via a call to exit or a return. WEXITSTATUS(status): Returns the exit status of a normally terminated child. This status is only defined if WIFEXITED returned true. WIFSIGNALED(status): Returns true if the child process terminated because of a signal that was not caught. (Signals are explained in Section 8.5.) 8.4. PROCESS CONTROL 411 ¯ ¯ ¯ WTERMSIG(status): Returns the number of the signal that caused the child process to terminate. This status is only defined if WIFSIGNALED(status) returned true. WIFSTOPPED(status): Returns true if the child that caused the return is currently stopped. WSTOPSIG(status): Returns the number of the signal that caused the child to stop. This status is only defined if WIFSTOPPED(status) returned true. Error Conditions If the calling process has no children, then waitpid returns ½ and sets errno to ECHILD. If the waitpid function was interrupted by a signal, then it returns ½ and sets errno to EINTR. Aside: Constants associated with Unix functions. Constants such as WNOHANG and WUNTRACED are defined by system header files. For example, WNOHANG and WUNTRACED are defined (indirectly) by the wait.h header file: /* Bits in the third argument to ‘waitpid’. */ #define WNOHANG 1 /* Don’t block waiting. */ #define WUNTRACED 2 /* Report status of stopped children. */ In order to use these constants, you must include the wait.h header file in your code: #include <sys/wait.h> The man page for each Unix function lists the header files to include whenever you use that function in your code. Also, in order to check return codes such as ECHILD and EINTR, you must include errno.h. To simplify our code examples, we include a single header file called csapp.h that includes the header files for all of the functions used in the book. The csapp.h header file is listed in Appendix A. End Aside. Examples Figure 8.15 shows a program that creates Æ children, uses waitpid to wait for them to terminate, and then checks the exit status of each terminated child. When we run the program on our Unix system, it produces the following output: unix> ./waitpid1 child 22966 terminated normally with exit status=100 child 22967 terminated normally with exit status=101 Notice that the program reaps the children in no particular order. Figure 8.16 shows how we might use waitpid to reap the children from Figure 8.15 in the same order that they were created by the parent. Practice Problem 8.4: Consider the following program: code/ecf/waitprob1.c 412 CHAPTER 8. EXCEPTIONAL CONTROL FLOW code/ecf/waitpid1.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include "csapp.h" #define N 2 int main() { int status, i; pid_t pid; for (i = 0; i < N; i++) if ((pid = Fork()) == 0) exit(100+i); /* child */ /* parent waits for all of its children to terminate */ while ((pid = waitpid(-1, &status, 0)) > 0) { if (WIFEXITED(status)) printf("child %d terminated normally with exit status=%d\n", pid, WEXITSTATUS(status)); else printf("child %d terminated abnormally\n", pid); } if (errno != ECHILD) unix_error("waitpid error"); exit(0); } code/ecf/waitpid1.c Figure 8.15: Using the waitpid function to reap zombie children. 8.4. PROCESS CONTROL 413 code/ecf/waitpid2.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include "csapp.h" #define N 2 int main() { int status, i; pid_t pid[N+1], retpid; for (i = 0; i < N; i++) if ((pid[i] = Fork()) == 0) exit(100+i); /* child */ /* parent reaps N children in order */ i = 0; while ((retpid = waitpid(pid[i++], &status, 0)) > 0) { if (WIFEXITED(status)) printf("child %d terminated normally with exit status=%d\n", retpid, WEXITSTATUS(status)); else printf("child %d terminated abnormally\n", retpid); } /* The only normal termination is if there are no more children */ if (errno != ECHILD) unix_error("waitpid error"); exit(0); } code/ecf/waitpid2.c Figure 8.16: Using waitpid to reap zombie children in the order they were created. 414 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 CHAPTER 8. EXCEPTIONAL CONTROL FLOW #include "csapp.h" int main() { int status; pid_t pid; printf("Hello\n"); pid = Fork(); printf("%d\n", !pid); if (pid != 0) { if (waitpid(-1, &status, 0) > 0) { if (WIFEXITED(status) != 0) printf("%d\n", WEXITSTATUS(status)); } } printf("Bye\n"); exit(2); } code/ecf/waitprob1.c A. How many output lines does this program generate? B. What is one possible ordering of these output lines? 8.4.4 Putting Processes to Sleep The sleep function suspends a process for some period of time. #include <unistd.h> unsigned int sleep(unsigned int secs); returns: seconds left to sleep Sleep returns zero if the requested amount of time has elapsed, and the number of seconds still left to sleep otherwise. The latter case is possible if the sleep function returns prematurely because it was interrupted by a signal. We will discuss signals in detail in Section 8.5. Another function that we will find useful is the pause function, which puts the calling function to sleep until a signal is received by the process. #include <unistd.h> int pause(void); always returns -1 8.4. PROCESS CONTROL Practice Problem 8.5: Write a wrapper function for sleep, called snooze, with the following interface: unsigned int snooze(unsigned int secs); The snooze function behaves exactly as the sleep function, except that it prints a message describing how long the process actually slept. For example, Slept for 4 of 5 secs. 415 8.4.5 Loading and Running Programs The execve function loads and runs a new program in the context of the current process. #include <unistd.h> int execve(char *filename, char *argv, char *envp); does not return if OK, returns -1 on error The execve function loads and runs the executable object file filename with the argument list argv and the environment variable list envp. Execve returns to the calling program only if there is an error such as not being able to find filename. So unlike fork, which is called once but returns twice, execve is called once and never returns. The argument list is represented by the data structure shown in Figure 8.17. The argv variable points to argv argv argv[0] argv[1] ... argv[argc-1] NULL "ls" "-lt" "/usr/include" Figure 8.17: Organization of an argument list. a null-terminated array of pointers, each of which points to an argument string. By convention argv[0] is the name of the executable object file. The list of environment variables is represented by a similar data structure, shown in Figure 8.18. The envp variable points to a null-terminated array of pointers to environment variable strings, each of which is a name-value pair of the form ”NAME=VALUE”. After execve loads filename, it calls the startup code described in Section 7.9. The startup code sets up the stack and passes control to the main routine of the new program, which has a prototype of the form int main(int argc, char **argv, char **envp); or equivalently 416 envp envp envp[0] envp[1] ... envp[n-1] NULL CHAPTER 8. EXCEPTIONAL CONTROL FLOW "PWD=/usr/droh" "PRINTER=iron" "USER=droh" Figure 8.18: Organization of an environment variable list. int main(int argc, char *argv, char *envp); When main begins executing on a Linux system, the user stack has the organization shown in Figure 8.19. Let’s work our way from the bottom of the stack (the highest address) to the top (the lowest address). First 0xbfffffff null-terminated environment variable strings null-terminated command-line arg strings (unused) envp[n] == NULL envp[n-1] bottom of stack ... envp[0] argv[argc] = NULL argv[argc-1] environ ... argv[0] (dynamic linker variables) envp argv argc 0xbffffa7c stack frame for main top of stack Figure 8.19: Typical organization of the user stack when a new program starts. are the argument and environment strings, which are stored contiguously on the stack, one after the other without any gaps. These are followed further up the stack by a null-terminated array of pointers, each of which points to an environment variable string on the stack. The global variable environ points to the first of these pointers, envp[0]. The environment array is followed immediately by the null-terminated argv array, with each element pointing to an argument string on the stack. At the top of the stack are the three arguments to the main routine: (1) envp, which points the envp array, (2) argv, which points to the argv array, and (3) argc, which gives the number of non-null pointers in the argv array. Unix provides several functions for manipulating the environment array. 8.4. PROCESS CONTROL #include <stdlib.h> char *getenv(const char *name); 417 returns: ptr to name if exists, NULL if no match. The getenv function searches the environment array for a string “name=value”. If found, it returns a pointer to value, otherwise it returns NULL. #include <stdlib.h> int setenv(const char *name, const char *newvalue, int overwrite); returns: 0 on success, -1 on error. void unsetenv(const char *name); returns: nothing. If the environment array contains a string of the form “name=oldvalue” then unsetenv deletes it and setenv replaces oldvalue with newvalue, but only if overwrite is nonzero. If name does not exist, then setenv adds “name=newvalue” to the array. Aside: Setting environment variables in Solaris systems Solaris provides the putenv function in place of the setenv function. It provides no counterpart to the unsetenv function. End Aside. Aside: Programs vs. processes. This is a good place to stop and make sure you understand the distinction between a program and a process. A program is a collection of code and data; programs can exist as object modules on disk or as segments in an address space. A process is a specific instance of a program in execution; a program always runs in the context of some process. Understanding this distinction is important if you want to understand the fork and execve functions. The fork function runs the same program in a new child process that is a duplicate of the parent. The execve function loads and runs a new program in the context of the current process. While it overwrites the address space of the current process, it does not create a new process. The new program still has the same PID, and it inherits all of the file descriptors that were open at the time of the call to the execve function. End Aside. Practice Problem 8.6: Write a program, called myecho, that prints its command line arguments and environment variables. For example: unix> ./myecho arg1 arg2 Command line arguments: argv[ 0]: myecho argv[ 1]: arg1 argv[ 2]: arg2 Environment variables: envp[ 0]: PWD=/usr0/droh/ics/code/ecf envp[ 1]: TERM=emacs 418 ... CHAPTER 8. EXCEPTIONAL CONTROL FLOW envp[25]: USER=droh envp[26]: SHELL=/usr/local/bin/tcsh envp[27]: HOME=/usr0/droh 8.4.6 Using fork and execve to Run Programs Programs such as Unix shells and Web servers (Chapter 12) make heavy use of the fork and execve functions. A shell is an interactive application-level program that runs other programs on behalf of the user. The original shell was the sh program, which was followed by variants such as csh, tcsh, ksh, and bash. A shell performs a sequence of read/evaluate steps, and then terminates. The read step reads a command line from the user. The evaluate step parses the command line and runs programs on behalf of the user. Figure 8.20 shows the main routine of a simple shell. The shell print a command-line prompt, waits for the code/ecf/shellex.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include "csapp.h" #define MAXARGS 128 /* function prototypes */ void eval(char*cmdline); int parseline(const char *cmdline, char **argv); int builtin_command(char **argv); int main() { char cmdline[MAXLINE]; /* command line */ while (1) { /* read */ printf("> "); Fgets(cmdline, MAXLINE, stdin); if (feof(stdin)) exit(0); /* evaluate */ eval(cmdline); } } code/ecf/shellex.c Figure 8.20: The main routine for a simple shell program. user to type a command line on stdin, and then evaluates the command line. 8.5. SIGNALS 419 Figure 8.21 shows the code that evaluates the command line. Its first task is to call the parseline function (Figure 8.22), which parses the space-separated command-line arguments and builds the argv vector that will eventually be passed to execve. The first argument is assumed to be either the name of a built-in shell command that is interpreted immediately, or an executable object file that will be loaded and run in the context of a new child process. If the last argument is a “&” character, then parseline returns 1, indicating that the program should be executed in the background (the shell does not wait for it to complete). Otherwise it returns 0, indicating that the program should be run in the foreground (the shell waits for it to complete). After parsing the command line, the eval function calls the builtin command function, which checks whether the first command line argument is a built-in shell command. If so, it interprets the command immediately and returns 1. Otherwise, it returns 0. Our simple shell has just one built-in command, the quit command, which terminates the shell. Real shells have numerous commands, such as pwd, jobs, and fg. If builtin command returns 0, then the shell creates a child process and executes the requested program inside the child. If the user has asked for the program to run in the background, then the shell returns to the top of the loop and waits for the next command line. Otherwise the shell uses the waitpid function to wait for the job to terminate. When the job terminates, the shell goes on to the next iteration. Notice that this simple shell is flawed because it does not reap any of its background children. Correcting this flaw requires the use of signals, which we describe in the next section. 8.5 Signals To this point in our study of exceptional control flow, we have seen how hardware and software cooperate to provide the fundamental low-level exception mechanism. We have also seen how the operating system uses exceptions to support a higher-level form of exceptional control flow known as the context switch. In this section we will study a higher-level software form of exception, known as a Unix signal, that allows processes to interrupt other processes. A signal is a message that notifies a process that an event of some type has occurred in the system. For example, Figure 8.23 shows the 30 different types of signals that are supported on Linux systems. Each signal type corresponds to some kind of system event. Low-level hardware exceptions are processed by the kernel’s exception handlers and would not normally be visible to user processes. Signals provide a mechanism for exposing the occurrence of such exceptions to user processes. For example, if a process attempts to divide by zero, then the kernel sends it a SIGFPE signal (number 8). If a process executes an illegal instruction, the kernel sends it a SIGILL signal (number 4). If a process makes an illegal memory reference, the kernel sends it a SIGSEGV signal (number 11). Other signals correspond to higher-level software events in the kernel or in other user processes. For example, if you type a ctrl-c (i.e., press the ctrl key and the c key at the same time) while a process is running in the foreground, then the kernel sends a SIGINT (number 2) to the foreground process. A process can forcibly terminate another process by sending it a SIGKILL signal (number 9). When a child process terminates or stops, the kernel sends a SIGCHLD signal (number 17) to the parent. 420 CHAPTER 8. EXCEPTIONAL CONTROL FLOW code/ecf/shellex.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 /* eval - evaluate a command line */ void eval(char *cmdline) { char *argv[MAXARGS]; /* argv for execve() */ int bg; /* should the job run in bg or fg? */ pid_t pid; /* process id */ bg = parseline(cmdline, argv); if (argv[0] == NULL) return; /* ignore empty lines */ if (!builtin_command(argv)) { if ((pid = Fork()) == 0) { /* child runs user job */ if (execve(argv[0], argv, environ) < 0) { printf("%s: Command not found.\n", argv[0]); exit(0); } } /* parent waits for foreground job to terminate */ if (!bg) { int status; if (waitpid(pid, &status, 0) < 0) unix_error("waitfg: waitpid error"); } else printf("%d %s", pid, cmdline); } return; } /* if first arg is a builtin command, run it and return true */ int builtin_command(char **argv) { if (!strcmp(argv[0], "quit")) /* quit command */ exit(0); if (!strcmp(argv[0], "&")) /* ignore singleton & */ return 1; return 0; /* not a builtin command */ } code/ecf/shellex.c Figure 8.21: eval: evaluates the shell command line. 8.5. SIGNALS 421 code/ecf/shellex.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 /* parseline - parse the int parseline(const char { char array[MAXLINE]; char *buf = array; char *delim; int argc; int bg; command line and build the argv array */ *cmdline, char **argv) /* /* /* /* /* holds local copy of command line */ ptr that traverses command line */ points to first space delimiter */ number of args */ background job? */ strcpy(buf, cmdline); buf[strlen(buf)-1] = ’ ’; /* replace trailing ’\n’ with space */ while (*buf && (*buf == ’ ’)) /* ignore leading spaces */ buf++; /* build the argv list */ argc = 0; while ((delim = strchr(buf, ’ ’))) { argv[argc++] = buf; *delim = ’\0’; buf = delim + 1; while (*buf && (*buf == ’ ’)) /* ignore spaces */ buf++; } argv[argc] = NULL; if (argc == 0) return 1; /* ignore blank line */ /* should the job run in the background? */ if ((bg = (*argv[argc-1] == ’&’)) != 0) argv[--argc] = NULL; return bg; } code/ecf/shellex.c Figure 8.22: parseline: parses a line of input for the shell. 422 CHAPTER 8. EXCEPTIONAL CONTROL FLOW Number 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Name SIGHUP SIGINT SIGQUIT SIGILL SIGTRAP SIGABRT SIGBUS SIGFPE SIGKILL SIGUSR1 SIGSEGV SIGUSR2 SIGPIPE SIGALRM SIGTERM SIGSTKFLT SIGCHLD SIGCONT SIGSTOP SIGTSTP SIGTTIN SIGTTOU SIGURG SIGXCPU SIGXFSZ SIGVTALRM SIGPROF SIGWINCH SIGIO SIGPWR Default action terminate terminate terminate terminate terminate and dump core terminate and dump core terminate terminate and dump core terminate* terminate terminate and dump core terminate terminate terminate terminate terminate ignore ignore stop until next SIGCONT* stop until next SIGCONT stop until next SIGCONT stop until next SIGCONT ignore terminate terminate terminate terminate ignore terminate terminate Corresponding event Terminal line hangup Interrupt from keyboard Quit from keyboard Illegal instruction Trace trap Abort signal from abort function Bus error Floating point exception Kill program User-defined signal 1 Invalid memory reference (seg fault) User-defined signal 2 Wrote to a pipe with no reader Timer signal from alarm function Software termination signal Stack fault on coprocessor A child process has stopped or terminated Continue process if stopped Stop signal not from terminal Stop signal from terminal Background process read from terminal Background process wrote to terminal Urgent condition on socket CPU time limit exceeded File size limit exceeded Virtual timer expired Profiling timer expired Window size changed I/O now possible on a descriptor. Power failure Figure 8.23: Linux signals. Other Unix versions are similar. Notes: (1) *This signal can neither be caught nor ignored. (2) Years ago, main memory was implemented with a technology known as core memory. “Dumping core” is an historical term that means writing an image of the code and data memory segments to disk. 8.5. SIGNALS 423 8.5.1 Signal Terminology The transfer of a signal to a destination process occurs in two distinct steps: ¯ Sending a signal. The kernel sends (delivers) a signal to a destination process by updating some state in the context of the destination process. The signal is delivered for one of two reasons: (1) the kernel has detected a system event such as a divide-by-zero error or the termination of a child process; (2) A process has invoked the kill function (discussed in the next section) to explicitly request the kernel to send a signal to the destination process. A process can send a signal to itself. Receiving a signal. A destination process receives a signal when it is forced by the kernel to react in some way to the delivery of the signal. The process can either ignore the signal, terminate, or catch the signal by executing a user-level function called a signal handler. ¯ A signal that has been sent but not yet received is called a pending signal. At any point in time, there can be at most one pending signal of a particular type. If a process has a pending signal of type , then any subsequent signals of type sent to that process are not queued; they are simply discarded. A process can selectively block the receipt of certain signals. When a signal is blocked, it can be delivered, but the resulting pending signal will not be received until the process unblocks the signal. A pending signal is received at most once. For each process, the kernel maintains the set of pending signals in the pending bit vector, and the set of blocked signals in the blocked bit vector. The kernel sets bit in pending whenever a signal of type is delivered and clears bit in pending whenever a signal of type is received. 8.5.2 Sending Signals Unix systems provide a number of mechanisms for sending signals to processes. All of the mechanisms rely on the notion of a process group. Process Groups Every process belongs to exactly one process group, which is identified by a positive integer process group ID. The getpgrp function returns the process group ID of the current process. #include <unistd.h> pid t getpgrp(void); returns: process group ID of calling process By default, a child process belongs to the same process group as its parent. A process can change the process group of itself or another process by using the setpgid function: 424 #include <unistd.h> pid t setpgid(pid t pid, pid t pgid); CHAPTER 8. EXCEPTIONAL CONTROL FLOW returns: 0 on success, -1 on error. The setpgid function changes the process group of process pid to pgid. If pid is zero, the PID of the current process is used. If pgid is zero, the PID of the process specified by pid is used for the process group ID. For example, if process 15213 is the calling process, then setpgid(0, 0); creates a new process group whose process group ID is 15213, and adds process 15213 to this new group. Sending Signals With the kill Program The /bin/kill program sends an arbitrary signal to another process. For example unix> kill -9 15213 sends signal 9 (SIGKILL) to process 15213. A negative PID causes the signal to be sent to every process in process group PID. For example, unix> kill -9 -15213 sends a SIGKILL signal to every process in process group 15213. Sending Signals From the Keyboard Unix shells use the abstraction of a job to represent the processes that are created as a result of evaluating a single command line. At any point in time, there is at most one foreground job and zero or more background jobs. For example, typing unix> ls | sort creates a foreground job consisting of two processes connected by a Unix pipe: one running the ls program, the other running the sort program. The shell creates a separate process group for each job. Typically, the process group ID is taken from one of the parent processes in the job. For example, Figure 8.24 shows a shell with one foreground job and two background jobs. The parent process in the foreground job has a PID of 20 and a process group ID of 20. The parent process has created two children, each of which are also members of process group 20. Typing ctrl-c at the keyboard causes a SIGINT signal to be sent to the shell. The shell catches the signal (see Section 8.5.3) and then sends a SIGINT to every process in the foreground process group. In the default case, the result is to terminate the foreground job. Similarly, typing crtl-z sends a SIGTSTP signal to the shell, which catches it and sends a SIGTSTP signal to every process in the foreground process group. In the default case, the result is to stop (suspend) the foreground job. 8.5. SIGNALS 425 pid=10 pgid=10 shell pid=20 pgid=20 foreground job background job #1 pid=32 pgid=32 background job #2 pid=40 pgid=40 child pid=21 pgid=20 child pid=22 pgid=20 background process group 32 backgroud process group 40 foreground process group 20 Figure 8.24: Foreground and background process groups. Sending Signals With the kill Function Processes send signals to other processes (including themselves) by calling the kill function. #include <sys/types.h> #include <signal.h> int kill(pid t pid, int sig); returns: 0 if OK, -1 on error If pid is greater than zero, then the kill function sends signal number sig to process pid. If pid is less than zero, than kill sends signal sig to every process in process group abs(pid). Figure 8.25 shows an example of a parent that uses the kill function to send a SIGKILL signal to its child. Sending Signals With the alarm Function A process can send SIGALRM signals to itself by calling the alarm function. #include <unistd.h> unsigned int alarm(unsigned int secs); returns: remaining secs of previous alarm, or 0 if no previous alarm The alarm function arranges for the kernel to send a SIGALRM signal to the calling process in secs seconds. If secs is zero, then no new alarm is scheduled. In any event, the call to alarm cancels any pending alarms, and returns the number of seconds remaining until any pending alarm was due to be delivered (had 426 CHAPTER 8. EXCEPTIONAL CONTROL FLOW code/ecf/kill.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include "csapp.h" int main() { pid_t pid; /* child sleeps until SIGKILL signal received, then dies */ if ((pid = Fork()) == 0) { Pause(); /* wait for a signal to arrive */ printf("control should never reach here!\n"); exit(0); } /* parent sends a SIGKILL signal to a child */ Kill(pid, SIGKILL); exit(0); } code/ecf/kill.c Figure 8.25: Using the kill function to send a signal to a child. not this call to alarm cancelled it), or 0 if there were no pending alarms. Figure 8.26 shows a program called alarm that arranges to be interrupted by a SIGALRM signal every second for five seconds. When the sixth SIGALRM is delivered it terminates. When we run the program in Figure 8.26, we get the following output: a “BEEP” every second for five seconds, followed by a “BOOM” when the program terminates. unix> ./alarm BEEP BEEP BEEP BEEP BEEP BOOM! Notice that the program in Figure 8.26 uses the signal function to install a signal handler function (handler) that is called asynchronously, interrupting the infinite while loop in main, whenever the process receives a SIGALRM signal. When the handler function returns, control passes back to main, which picks up where it was interrupted by the arrival of the signal. Installing and using signal handlers can be quite subtle, and is the topic of the next three sections. 8.5.3 Receiving Signals When the kernel is returning from an exception handler and is ready to pass control to process Ô, it checks the set of unblocked pending signals (pending & ˜blocked). If this set is empty (the usual case), then 8.5. SIGNALS 427 code/ecf/alarm.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include "csapp.h" void handler(int sig) { static int beeps = 0; printf("BEEP\n"); if (++beeps < 5) Alarm(1); /* next SIGALRM will be delivered in 1s */ else { printf("BOOM!\n"); exit(0); } } int main() { Signal(SIGALRM, handler); /* install SIGALRM handler */ Alarm(1); /* next SIGALRM will be delivered in 1s */ while (1) { ; /* signal handler returns control here each time */ } exit(0); } code/ecf/alarm.c Figure 8.26: Using the alarm function to schedule periodic events. 428 the kernel passes control to the next instruction (ÁÒ ÜØ CHAPTER 8. EXCEPTIONAL CONTROL FLOW ) in the logical control flow of Ô. However, if the set is nonempty, then the kernel chooses some signal in the set (typically the smallest ) and forces Ô to receive signal . The receipt of the signal triggers some action by the process. Once the process completes the action, then control passes back to the next instruction (ÁÒ ÜØ ) in the logical control flow of Ô. Each signal type has a predefined default action, which is one of the following: ¯ ¯ ¯ ¯ The process terminates. The process terminates and dumps core. The process stops until restarted by a SIGCONT signal. The process ignores the signal. Figure 8.23 shows the default actions associated with each type of signal. For example, the default action for the receipt of a SIGKILL is to terminate the receiving process. On the other hand, the default action for the receipt of a SIGCHLD is to ignore the signal. A process can modify the default action associated with a signal by using the signal function. The only exceptions are SIGSTOP and SIGKILL, whose default actions cannot be changed. #include <signal.h> typedef void handler t(int) handler t *signal(int signum, handler t *handler) returns: ptr to previous handler if OK, SIG ERR on error (does not set errno) The signal function can change the action associated with a signal signum in one of three ways: ¯ ¯ ¯ If handler is SIG IGN, then signals of type signum are ignored. If handler is SIG DFL, then the action for signals of type signum reverts to the default action. Otherwise, handler is the address of a user-defined function, called a signal handler, that will be called whenever the process receives a signal of type signum. Changing the default action by passing the address of a handler to the signal function is known as installing the handler. The invocation of the handler is called catching the signal. The execution of the handler is referred to as handling the signal. When a process catches a signal of type , the handler installed for signal is invoked with a single integer argument set to . This argument allows the same handler function to catch different types of signals. When the handler executes its return statement, control (usually) passes back to the instruction in the control flow where the process was interrupted by the receipt of the signal. We say “usually” because in some systems, interrupted system calls return immediately with an error. More on this in the next section. 8.5. SIGNALS 429 Figure 8.27 shows a program that catches the SIGINT signal sent by the shell whenever the user types ctrl-c at the keyboard. The default action for SIGINT is to immediately terminate the process. In this example, we modify the default behavior to catch the signal, print a message, and then terminate the process. code/ecf/sigint1.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include "csapp.h" void handler(int sig) /* SIGINT handler */ { printf("Caught SIGINT\n"); exit(0); } int main() { /* Install the SIGINT handler */ if (signal(SIGINT, handler) == SIG_ERR) unix_error("signal error"); pause(); /* wait for the receipt of a signal */ exit(0); } code/ecf/sigint1.c Figure 8.27: A program that catches a SIGINT signal. The handler function is defined in lines 3–7. The main routine installs the handler in lines 12–13, and then goes to sleep until a signal is received (line 15). When the SIGINT signal is received, the handler runs, prints a message (line 5) and then terminates the process (line 6). Practice Problem 8.7: Write a program, called snooze, that takes a single command line argument, calls the snooze function from Problem 8.5 with this argument, and then terminates. Write your program so that the user can interrupt the snooze function by typing ctrl-c at the keyboard. For example: unix> ./snooze 5 Slept for 3 of 5 secs. unix> User hits crtl-c after 3 seconds 8.5.4 Signal Handling Issues Signal handling is straightforward for programs that catch a single signal and then terminate. However, subtle issues arise when a program catches multiple signals. 430 CHAPTER 8. EXCEPTIONAL CONTROL FLOW ¯ ¯ Pending signals can be blocked. Unix signal handlers typically block pending signals of the type currently being processed by the handler. For example, suppose a process has caught a SIGINT signal and is currently running its SIGINT handler. If another SIGINT signal is sent to the process, then the SIGINT will become pending, but will not be received until after the handler returns. Pending signals are not queued. There can be at most one pending signal of any particular type. Thus, if two signals of type are sent to a destination process while signal is blocked because the destination process is currently executing a handler for signal , then the second signal is simply discarded; it is not queued. The key idea is that the existence of a pending signal merely indicates that at least one signal has arrived. System calls can be interrupted. System calls such as read, wait, and accept that can potentially block the process for a long period of time are called slow system calls. On some systems, slow system calls that are interrupted when a handler catches a signal do not resume when the signal handler returns, but instead return immediately to the user with an error condition and errno set to EINTR. ¯ Let’s look more closely at the subtleties of signal handling, using a simple application that is similar in nature to real programs such as shells and Web servers. The basic structure is that a parent process creates some children that run independently for a while and then terminate. The parent must reap the children to avoid leaving zombies in the system. But we also want the parent to be free to do other work while the children are running. So we decide to reap the children with a SIGCHLD handler, instead of explicitly waiting for the children the terminate. (Recall that the kernel sends a SIGCHLD signal to the parent whenever one of its children terminates or stops.) Figure 8.28 shows our first attempt. The parent installs a SIGCHLD handler, and then creates three children, each of which runs for 1 second and then terminates. In the meantime, the parent waits for a line of input from the terminal and then processes it. This processing is modeled by an infinite loop. When each child terminates, the kernel notifies the parent by sending it a SIGCHLD signal. The parent catches the SIGCHLD, reaps one child, does some additional cleanup work (modeled by the sleep(2) statement), and then returns. The signal1 program in Figure 8.28 seems fairly straightforward. But when we run it on our Linux system, we get the following output: linux> ./signal1 Hello from child 10320 Hello from child 10321 Hello from child 10322 Handler reaped child 10320 Handler reaped child 10322 <cr> Parent processing input From the output, we see that even though three SIGCHLD signals were sent to the parent, only two of these signals were received, and thus the parent only reaped two children. If we suspend the parent process, we see that indeed child process 10321 was never reaped and remains a zombie: 8.5. SIGNALS 431 code/ecf/signal1.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #include "csapp.h" void handler1(int sig) { pid_t pid; if ((pid = waitpid(-1, NULL, 0)) < 0) unix_error("waitpid error"); printf("Handler reaped child %d\n", (int)pid); Sleep(2); return; } int main() { int i, n; char buf[MAXBUF]; if (signal(SIGCHLD, handler1) == SIG_ERR) unix_error("signal error"); /* parent creates children */ for (i = 0; i < 3; i++) { if (Fork() == 0) { printf("Hello from child %d\n", (int)getpid()); Sleep(1); exit(0); } } /* parent waits for terminal input and then processes it */ if ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0) unix_error("read"); printf("Parent processing input\n"); while (1) ; exit(0); } code/ecf/signal1.c Figure 8.28: signal1: This program is flawed because it fails to deal with the facts that signals can block, signals are not queued, and system calls can be interrupted. 432 <ctrl-z> Suspended linux> ps PID TTY STAT TIME COMMAND ... 10319 p5 T 0:03 signal1 10321 p5 Z 0:00 (signal1 <zombie>) 10323 p5 R 0:00 ps CHAPTER 8. EXCEPTIONAL CONTROL FLOW What went wrong? The problem is that our code failed to account for the facts that signals can block and that signals are not queued. Here’s what happened: The first signal is received and caught by the parent. While the handler is still processing the first signal, the second signal is delivered and added to the set of pending signals. However, since SIGCHLD signals are blocked by the SIGCHLD handler, the second signal is not received. Shortly thereafter, while the handler is still processing the first signal, the third signal arrives. Since there is already a pending SIGCHLD, this third SIGCHLD signal is discarded. Sometime later, after the handler has returned, the kernel notices that there is a pending SIGCHLD signal and forces the parent to receive the signal. The parent catches the signal and executes the handler a second time. After the handler finishes processing the second signal, there are no more pending SIGCHLD signals, and there never will be, because all knowledge of the third SIGCHLD has been lost. The crucial lesson is that signals cannot be used to count the occurrence of events in other processes. To fix the problem, we must recall that the existence of a pending signal only implies that at least one signal has been delivered since the last time the process received a signal of that type. So we must modify the SIGCHLD handler to reap as many zombie children as possible each time it is invoked. Figure 8.29 shows the modified SIGCHLD handler. When we run signal2 on our Linux system, it now correctly reaps all of the zombie children: linux> ./signal2 Hello from child 10378 Hello from child 10379 Hello from child 10380 Handler reaped child 10379 Handler reaped child 10378 Handler reaped child 10380 <cr> Parent processing input However, we are not done yet. If we run the signal2 program on a Solaris system, it correctly reaps all of the zombie children. However, now the blocked read system call returns prematurely with an error, before we are able to type in our input on the keyboard: solaris> ./signal2 Hello from child 18906 Hello from child 18907 Hello from child 18908 Handler reaped child 18906 Handler reaped child 18908 8.5. SIGNALS 433 code/ecf/signal2.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 #include "csapp.h" void handler2(int sig) { pid_t pid; while ((pid = waitpid(-1, NULL, 0)) > 0) printf("Handler reaped child %d\n", (int)pid); if (errno != ECHILD) unix_error("waitpid error"); Sleep(2); return; } int main() { int i, n; char buf[MAXBUF]; if (signal(SIGCHLD, handler2) == SIG_ERR) unix_error("signal error"); /* parent creates children */ for (i = 0; i < 3; i++) { if (Fork() == 0) { printf("Hello from child %d\n", (int)getpid()); Sleep(1); exit(0); } } /* parent waits for terminal input and then processes it */ if ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0) unix_error("read error"); printf("Parent processing input\n"); while (1) ; exit(0); } code/ecf/signal2.c Figure 8.29: signal2: An improved version of Figure 8.28 that correctly accounts for the facts that signals can block and are not queued. However it does not allow for the possibility that system calls can be interrupted. 434 Handler reaped child 18907 read: Interrupted system call CHAPTER 8. EXCEPTIONAL CONTROL FLOW What went wrong? The problem arises because on this particular Solaris system, slow system calls such as read are not restarted automatically after they are interrupted by the delivery of a signal. Instead they return prematurely to the calling application with an error condition, unlike Linux systems, which restart interrupted system calls automatically. In order to write portable signal handling code, we must allow for the possibility that system calls will return prematurely and then restart them manually when this occurs. Figure 8.30 shows the modification to signal1 that manually restarts aborted read calls. The EINTR return code in errno indicates that the read system call returned prematurely after it was interrupted. When we run our new signal3 program on a Solaris system, the program runs correctly: solaris> ./signal3 Hello from child 19571 Hello from child 19572 Hello from child 19573 Handler reaped child 19571 Handler reaped child 19572 Handler reaped child 19573 <cr> Parent processing input 8.5.5 Portable Signal Handling The differences in signal handling semantics from system to system — such as whether or not an interrupted slow system call is restarted or aborted prematurely — is an ugly aspect of Unix signal handling. To deal with this problem, the Posix standard defines the sigaction function, which allows users on Posixcompliant systems such as Linux and Solaris to clearly specify the signal-handling semantics they want. #include <signal.h> int sigaction(int signum, struct sigaction *act, struct sigaction *oldact); returns: 0 if OK, -1 on error The sigaction function is unwieldy because it requires the user to set the entries of a structure. A cleaner approach, originally proposed by Stevens [77], is to define a wrapper function, called Signal, that calls sigaction for us. Figure 8.31 shows the definition of Signal, which is invoked in the same way as the signal function. The Signal wrapper installs a signal handler with the following signal-handling semantics: ¯ ¯ Only signals of the type currently being processed by the handler are blocked. As with all signal implementations, signals are not queued. 8.5. SIGNALS 435 code/ecf/signal3.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #include "csapp.h" void handler2(int sig) { pid_t pid; while ((pid = waitpid(-1, NULL, 0)) > 0) printf("Handler reaped child %d\n", (int)pid); if (errno != ECHILD) unix_error("waitpid error"); Sleep(2); return; } int main() { int i, n; char buf[MAXBUF]; pid_t pid; if (signal(SIGCHLD, handler2) == SIG_ERR) unix_error("signal error"); /* parent creates children */ for (i = 0; i < 3; i++) { pid = Fork(); if (pid == 0) { printf("Hello from child %d\n", (int)getpid()); Sleep(1); exit(0); } } /* Manually restart the read call if it is interrupted */ while ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0) if (errno != EINTR) unix_error("read error"); printf("Parent processing input\n"); while (1) ; exit(0); } code/ecf/signal3.c Figure 8.30: signal3: An improved version of Figure 8.29 that correctly accounts for the fact that system calls can be interrupted. 436 CHAPTER 8. EXCEPTIONAL CONTROL FLOW code/src/csapp.c 1 2 3 4 5 6 7 8 9 10 11 12 handler_t *Signal(int signum, handler_t *handler) { struct sigaction action, old_action; action.sa_handler = handler; sigemptyset(&action.sa_mask); /* block sigs of type being handled */ action.sa_flags = SA_RESTART; /* restart syscalls if possible */ if (sigaction(signum, &action, &old_action) < 0) unix_error("Signal error"); return (old_action.sa_handler); } code/src/csapp.c Figure 8.31: Signal: A wrapper for sigaction that provides portable signal handling on Posixcompliant systems. ¯ ¯ Interrupted system calls are automatically restarted whenever possible. Once the signal handler is installed, it remains installed until Signal is called with a handler argument of either SIG IGN or SIG DFL. (Some older Unix systems restore the signal action to its default action after a signal has been processed by a handler.) Figure 8.32 shows a version of the signal2 program from Figure 8.29 that uses our Signal wrapper to get predictable signal handling semantics on different computer systems. The only difference is that we have installed the handler with a call to Signal rather than a call to signal. The program now runs correctly on both our Solaris and Linux systems, and we no longer need to manually restart interrupted read system calls. 8.6 Nonlocal Jumps C provides a form of user-level exceptional control flow, called a nonlocal jump, that transfers control directly from one function to another currently executing function, without having to go through the normal call-and-return sequence. Nonlocal jumps are provided by the setjmp and longjmp functions. #include <setjmp.h> int setjmp(jmp buf env); int sigsetjmp(sigjmp buf env, int savesigs); returns: 0 from setjmp, nonzero from longjmps) The setjmp function saves the current stack context in the env buffer, for later use by longjmp, and 8.6. NONLOCAL JUMPS 437 code/ecf/signal4.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 #include "csapp.h" void handler2(int sig) { pid_t pid; while ((pid = waitpid(-1, NULL, 0)) > 0) printf("Handler reaped child %d\n", (int)pid); if (errno != ECHILD) unix_error("waitpid error"); Sleep(2); return; } int main() { int i, n; char buf[MAXBUF]; pid_t pid; Signal(SIGCHLD, handler2); /* sigaction error-handling wrapper */ /* parent creates children */ for (i = 0; i < 3; i++) { pid = Fork(); if (pid == 0) { printf("Hello from child %d\n", (int)getpid()); Sleep(1); exit(0); } } /* parent waits for terminal input and then processes it */ if ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0) unix_error("read error"); printf("Parent processing input\n"); while (1) ; exit(0); } code/ecf/signal4.c Figure 8.32: signal4: A version of Figure 8.29 that uses our Signal wrapper to get portable signalhandling semantics. 438 returns a 0. #include <setjmp.h> CHAPTER 8. EXCEPTIONAL CONTROL FLOW void longjmp(jmp buf env, int retval); void siglongjmp(sigjmp buf env, int retval); never returns) The longjmp function restores the stack context from the env buffer and then triggers a return from the most recent setjmp call that initialized env. The setjmp then returns with the nonzero return value retval. The interactions between setjmp and longjmp can be confusing at first glance. The setjmp function is called once but returns multiple times: once when the setjmp is first called and the stack context is stored in the env buffer, and once for each corresponding longjmp call. On the other hand, the longjmp function is called once but never returns. An important application of nonlocal jumps is to permit an immediate return from a deeply nested function call, usually as a result of detecting some error condition. If an error condition is detected deep in a nested function call, we can use a nonlocal jump to return directly to a common localized error handler instead of laboriously unwinding the call stack. Figure 8.33 shows an example of how this might work. The main routine first calls setjmp to save the current stack context, and then calls function foo, which in turn calls function bar. If foo or bar encounter an error, they return immediately from the setjmp via a longjmp call. The nonzero return value of the setjmp indicates the error type, which can then be decoded and handled in one place in the code. Another important application of nonlocal jumps is to branch out of a signal handler to a specific code location, rather than returning to the instruction that was interrupted by the arrival of the signal. For example, if a Web server attempts to send data to a browser that has unilaterally aborted the network connection between the client and the server, (e.g., as a result of the browser’s user clicking the STOP button), the kernel will send a SIGPIPE signal to the server. The default action for the SIGPIPE signal is to terminate the process, which is clearly not a good thing for a server that is supposed to run forever. Thus, a robust Web server will install a SIGPIPE handler to catch these signals. After cleaning up, the SIGPIPE handler should jump to the code that waits for the next request from a browser, rather than returning to the instruction that was interrupted by the receipt of the SIGPIPE signal. Nonlocal jumps are the only way to handle this kind of error recovery. Figure 8.34 shows a simple program that illustrates this basic technique. The program uses signals and nonlocal jumps to do a soft restart whenever the user types ctrl-c at the keyboard. The sigsetjmp and siglongjmp functions are versions of setjmp and longjmp that can be used by signal handlers. The initial call to the sigsetjmp function saves the stack and signal context when the program first starts. The main routine then enters an infinite processing loop. When the user types ctrl-c, the shell sends a SIGINT signal to the process, which catches it. Instead of returning from the signal handler, which would pass back control back to the interrupted processing loop, the handler performs a nonlocal jump back to the 8.6. NONLOCAL JUMPS 439 code/ecf/setjmp.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #include "csapp.h" jmp_buf buf; int error1 = 0; int error2 = 1; void foo(void), bar(void); int main() { int rc; rc = setjmp(buf); if (rc == 0) foo(); else if (rc == 1) printf("Detected an error1 condition in foo\n"); else if (rc == 2) printf("Detected an error2 condition in foo\n"); else printf("Unknown error condition in foo\n"); exit(0); } /* deeply nested function foo */ void foo(void) { if (error1) longjmp(buf, 1); bar(); } void bar(void) { if (error2) longjmp(buf, 2); } code/ecf/setjmp.c Figure 8.33: Nonlocal jump example. This example shows the framework for using nonlocal jumps to recover from error conditions in deeply nested functions without having to unwind the entire stack. 440 CHAPTER 8. EXCEPTIONAL CONTROL FLOW code/ecf/restart.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #include "csapp.h" sigjmp_buf buf; void handler(int sig) { siglongjmp(buf, 1); } int main() { Signal(SIGINT, handler); if (!sigsetjmp(buf, 1)) printf("starting\n"); else printf("restarting\n"); while(1) { Sleep(1); printf("processing...\n"); } exit(0); } code/ecf/restart.c Figure 8.34: A program that uses nonlocal jumps to restart itself when the user types ctrl-c. 8.7. TOOLS FOR MANIPULATING PROCESSES beginning of the main program. When we ran the program on our system, we got the following output: unix> ./restart starting processing... processing... restarting processing... restarting processing... 441 user hits ctrl-c User hits ctrl-c 8.7 Tools for Manipulating Processes Unix systems provide a number of useful tools for monitoring and manipulating processes. STRACE: Prints a trace of each system call invoked by a program and its children. A fascinating tool for the curious student. Compile your program with -static to get a cleaner trace without a lot of output related to shared libraries. PS: Lists processes (including zombies) currently in the system. Prints information about the resource usage of current processes. Sends a signal to a process. Useful for debugging programs with signal handlers and cleaning up wayward processes. TOP: KILL: /proc (Linux and Solaris) : A virtual filesystem that exports the contents of numerous kernel data structures in an ASCII text form that can be read by user programs. For example, type “cat /proc/loadavg” to see the current load average on your Linux system. 8.8 Summary Exceptional control flow occurs at all levels of a computer system. At the hardware level, exceptions are abrupt changes in the control flow that are triggered by events in the processor. At the operating system level, the kernel triggers abrupt changes in the control flows between different processes when it performs context switches. At the interface between the operating system and applications, applications can create child processes, wait for their child processes to stop or terminate, run new programs, and catch signals from other processes. The semantics of signal handling is subtle and can vary from system to system. However, mechanisms exist on Posix-compliant systems that allow programs to clearly specify the expected signalhandling semantics. Finally, at the application level, C programs can use nonlocal jumps to bypass the normal call/return stack discipline and branch directly from one function to another. 442 CHAPTER 8. EXCEPTIONAL CONTROL FLOW Bibliographic Notes The Intel macro-architecture specification contains a detailed discussion of exceptions and interrupts on Intel processors [17]. Operating systems texts [66, 71, 79] contain additional information on exceptions, processes, and signals. The classic work by Stevens [72], while somewhat outdated, remains a valuable and highly readable description of how to work with processes and signals from application programs. Bovet and Cesati give a wonderfully clear description of the Linux kernel, including details of the process and signal implementations. Homework Problems Homework Problem 8.8 [Category 1]: In this chapter, we have introduced some functions with unusual call and return behaviors: setjmp, longjmp, execve, and fork. Match each function with one of the following behaviors: A. Called once, returns twice. B. Called once, never returns. C. Called once, returns one or more times. Homework Problem 8.9 [Category 1]: What is one possible output of the following program? code/ecf/forkprob3.c 1 2 3 4 5 6 7 8 9 10 11 12 #include "csapp.h" int main() { int x = 3; if (Fork() != 0) printf("x=%d\n", ++x); printf("x=%d\n", --x); exit(0); } code/ecf/forkprob3.c Homework Problem 8.10 [Category 1]: How many “hello” output lines does this program print? code/ecf/forkprob5.c 8.8. SUMMARY 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 443 #include "csapp.h" void doit() { if (Fork() == 0) { Fork(); printf("hello\n"); exit(0); } return; } int main() { doit(); printf("hello\n"); exit(0); } code/ecf/forkprob5.c Homework Problem 8.11 [Category 1]: How many “hello” output lines does this program print? code/ecf/forkprob6.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include "csapp.h" void doit() { if (Fork() == 0) { Fork(); printf("hello\n"); return; } return; } int main() { doit(); printf("hello\n"); exit(0); } code/ecf/forkprob6.c Homework Problem 8.12 [Category 1]: What is the output of the following program? code/ecf/forkprob7.c 444 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 CHAPTER 8. EXCEPTIONAL CONTROL FLOW #include "csapp.h" int counter = 1; int main() { if (fork() == 0) { counter--; exit(0); } else { Wait(NULL); printf("counter = %d\n", ++counter); } exit(0); } code/ecf/forkprob7.c Homework Problem 8.13 [Category 1]: Enumerate all of the possible outputs of the program in Problem 8.4. Homework Problem 8.14 [Category 2]: Consider the following program: code/ecf/forkprob2.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include "csapp.h" void end(void) { printf("2"); } int main() { if (Fork() == 0) atexit(end); if (Fork() == 0) printf("0"); else printf("1"); exit(0); } code/ecf/forkprob2.c Determine which of the following outputs are possible. Note: The atexit function takes a pointer to a function and adds it to a list of functions (initially empty) that will be called when the exit function is called. A. 112002 8.8. SUMMARY B. 211020 C. 102120 D. 122001 E. 100212 445 Homework Problem 8.15 [Category 2]: Use execve to write a program, called myls, whose behavior is identical to the /bin/ls program. Your program should accept the same command line arguments, interpret the identical environment variables, and produce the identical output. The ls program gets the width of the screen from the COLUMNS environment variable. If COLUMNS is unset, then ls assumes that the screen is 80 columns wide. Thus, you can check your handling of the environment variables by setting the COLUMNS environment to something smaller than 80: unix> setenv COLUMNS 40 unix> ./myls ...output is 40 columns wide unix> unsetenv COLUMNS unix> ./myls ...output is now 80 columns wide Homework Problem 8.16 [Category 3]: Modify the program in Figure 8.15 so that 1. Each child terminates abnormally after attempting to write to a location in the read-only text segment. 2. The parent prints output that is identical (except for the PIDs) to the following: child 12255 terminated by signal 11: Segmentation fault child 12254 terminated by signal 11: Segmentation fault Hint: Read the man pages for wait(2) and psignal(3). Homework Problem 8.17 [Category 3]: Write your own version of the Unix system function: int mysystem(char *command); The mysystem function executes command by calling “/bin/sh -c command”, and then returns after command has completed. If command exits normally (by calling the exit function or executing a return statement), then mysystem returns the command exit status. For example, if command terminates 446 CHAPTER 8. EXCEPTIONAL CONTROL FLOW by calling exit(8), then system returns the value 8. Otherwise, if command terminates abnormally, then mysystem returns the status returned by the shell. Homework Problem 8.18 [Category 1]: One of your colleagues is thinking of using signals to allow a parent process to count events that occur in a child process. The idea is to notify the parent each time an event occurs by sending it a signal, and letting the parent’s signal handler increment a global counter variable, which the parent can then inspect after the child has terminated. However, when he runs the test program in Figure 8.35 on his system, he discovers that when the parent calls printf, counter always has a value of 2, even though the child has sent five signals to the parent. Perplexed, he comes to you for help. Can you explain the bug? code/ecf/counterprob.c 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include "csapp.h" int counter = 0; void handler(int sig) { counter++; sleep(1); /* do some work in the handler */ return; } int main() { int i; Signal(SIGUSR2, handler); if (Fork() == 0) { /* child */ for (i = 0; i < 5; i++) { Kill(getppid(), SIGUSR2); printf("sent SIGUSR2 to parent\n"); } exit(0); } Wait(NULL); printf("counter=%d\n", counter); exit(0); } code/ecf/counterprob.c Figure 8.35: Counter program referenced in Problem 8.18. Homework Problem 8.19 [Category 3]: Write a version of the fgets function, called tfgets, that times out after 5 seconds. The tfgets 8.8. SUMMARY 447 function accepts the same inputs as fgets. If the user doesn’t type an input line within 5 seconds, tfgets returns NULL. Otherwise it returns a pointer to the input line. Homework Problem 8.20 [Category 4]: Using the example in Figure 8.20 as a starting point, write a shell program that supports job control. Your shell should have the following features: ¯ The command line typed by the user consists of a name and zero or more arguments, all separated by one or more spaces. If name is a built-in command, the shell handles it immediately and waits for the next command line. Otherwise, the shell assumes that name is an executable file, which it loads and runs in the context of an initial child process (job). The process group ID for the job is identical to the PID of the child. Each job is identified by either a process ID (PID) or a job ID (JID), which is a small arbitrary positive integer assigned by the shell. JIDs are denoted on the command line by the prefix ’%’. For example, “%5” denotes JID 5, and “5” denotes PID 5. If the command line ends with an ampersand, then the shell runs the job in the background. Otherwise, the shell runs the job in the foreground. Typing ctrl-c (ctrl-z) causes the shell to send a SIGINT (SIGTSTP) signal to every process in the foreground process group. The jobs built-in command lists all background jobs. The bg <job> built-in command restarts <job> by sending it a SIGCONT signal, and then runs it in the background. The <job> argument can be either a PID or a JID. The fg <job> built-in command restarts <job> by sending it a SIGCONT signal, and then runs it in the foreground. The shell reaps all of its zombie children. If any job terminates because it receives a signal that was not caught, then the shell prints a message to the terminal with the job’s PID and a description of the offending signal. ¯ ¯ ¯ ¯ ¯ ¯ ¯ Figure 8.36 shows an example shell session. 448 CHAPTER 8. EXCEPTIONAL CONTROL FLOW unix> ./shell Run your shell program > bogus bogus: Command not found. Execve can’t find executable > foo 10 Job 5035 terminated by signal: Interrupt User types ctrl-c > foo 100 & [1] 5036 foo 100 & > foo 200 & [2] 5037 foo 200 & > jobs [1] 5036 Running foo 100 & [2] 5037 Running foo 200 & > fg %1 Job [1] 5036 stopped by signal: Stopped User types ctrl-z > jobs [1] 5036 Stopped foo 100 & [2] 5037 Running foo 200 & > bg 5035 5035: No such process > bg 5036 [1] 5036 foo 100 & > /bin/kill 5036 Job 5036 terminated by signal: Terminated Wait for fg job to finish. > fg %2 > quit unix> Back to the Unix shell Figure 8.36: Sample shell session for Problem 8.20. Chapter 9 Measuring Program Execution Time One common question people ask is “How fast does Program run on Machine ?” Such a question might be raised by a programmer trying to optimize program performance, or by a customer trying to decide which machine to buy. In our earlier discussion of performance optimization (Chapter 5), we assumed this question could be answered with perfect accuracy. We were trying to establish the cycles per element (CPE) measure for programs down to two decimal places. This requires an accuracy of 0.1% for a procedure having a CPE of 10. In this chapter, we address this problem and discover that it is surprisingly complex. You might expect that making near-perfect timing measurements on a computer system would be straightforward. After all, for a particular combination of program and data, the machine will execute a fixed sequence of instructions. Instruction execution is controlled by a processor clock that is regulated by a precision oscillator. There are many factors, however, that can vary from one execution of a program to another. Computers do not simply execute one program at a time. They continually switch from one process to another, executing some code on behalf of one process before moving on to the next. The exact scheduling of processor resources for one program depends on such factors as the number of users sharing the system, the network traffic, and the timing of disk operations. The access patterns to the caches depend not just on the references made by the program we are trying to measure, but on those of other processes executing concurrently. Finally, the branch prediction logic tries to guess whether branches will be taken or not based on past history. This history can vary from one execution of a program to another. In this chapter, we describe two basic mechanisms computers use to record the passage of time—one based on a low frequency timer that periodically interrupts the processor and one based on a counter that is incremented every clock cycle. Application programmers can gain access to the first timing mechanism by calling library functions. Cycle timers can be accessed by library functions on some systems, but they require writing assembly code on others. We have deferred the discussion of program timing until now, because it requires understanding aspects of both the CPU hardware and the way the operating system manages process execution. Using the two timing mechanisms, we investigate methods to get reliable measurements of program performance. We will see that timing variations due to context switching tend to be very large and hence must be eliminated. Variations caused by other factors such as cache and branch prediction are generally managed by evaluating program operation under carefully controlled conditions. Generally, we can get accurate measurements for durations that are either very short (less than around 10 millisecond) or very long (greater than 449 450 CHAPTER 9. MEASURING PROGRAM EXECUTION TIME Time Scale (1 Ghz Machine) Microscopic Integer Add FP Multiply FP Divide 1 ns 1.E-09 Macroscopic Disk Access Screen Refresh Keystroke 1s 1.E+00 Keystroke Interrupt Handler 1 µs 1 ms 1.E-03 Time (seconds) 1.E-06 Figure 9.1: Time Scale of Computer System Events. The processor hardware works at a microscopic a time scale in which events having durations on the order of a few nanoseconds (ns). The OS must deal on a macroscopic time scale with events having durations on the order of a few milliseconds (ms). around 1 second), even on heavily loaded machines. Times between around 10 milliseconds and 1 second require special care to measure accurately. Much of the understanding of performance measurement is part of the folklore of computer systems. Different groups and individuals have developed their own techniques for measuring program performance, but there is no widely available body of literature on the subject. Companies and research groups concerned with getting highly accurate performance measurements often set up specially configured machines that minimize any sources of timing irregularity, such as by limiting access and by disabling many OS and networking services. We want methods that application programmers can use on ordinary machines, but there are no widely available tools for this. Instead, we will develop our own. In this presentation we work through the issues systematically. We describe the design and evaluation of a number of experiments that helped us arrive at methods to achieve accurate measurements on a small set of systems. It is unusual to find a detailed experimental study in a book at this level. Generally, people expect the final answers, not a description of how those answers were determined. In this case, however, we cannot provide definitive answers on how to measure program execution time for an arbitrary program on an arbitrary system. There are too many variations of timing mechanisms, operating system behaviors, and runtime environment to have one single, simple solution. Instead, we anticipate that you will need to run your own experiments and develop your own performance measurement code. We hope that our case study will help you in this task. We summarize our findings in the form of a protocol that can guide your experiments. 9.1 The Flow of Time on a Computer System Computers operate on two fundamentally different time scales. At a microscopic level, they execute instructions at a rate of one or more per clock cycle, where each clock cycle requires only around one nanosecond (abbreviated “ns”), or ½¼ seconds. On a macroscopic scale, the processor must respond to external events 9.1. THE FLOW OF TIME ON A COMPUTER SYSTEM 451 that occur on time scales measured in milliseconds (abbreviated “ms”), or ½¼ ¿ seconds. For example, during video playback, the graphics display for most computers must be refreshed every 33 ms. A worldrecord typist can only type keystrokes at a rate of around one every 50 milliseconds. Disks typically require around 10 ms to initiate a disk transfer