Chapter 2 Instructions Language of the Computer n

  • Slides: 92
Download presentation
Chapter 2 Instructions: Language of the Computer

Chapter 2 Instructions: Language of the Computer

n n The repertoire of instructions of a computer Different computers have different instruction

n n The repertoire of instructions of a computer Different computers have different instruction sets n n But with many aspects in common Early computers had very simple instruction sets n n § 2. 1 Introduction Instruction Set Simplified implementation Many modern computers also have simple instruction sets Chapter 2 — Instructions: Language of the Computer — 2

The MIPS Instruction Set n n n Used as the example throughout the book

The MIPS Instruction Set n n n Used as the example throughout the book Stanford MIPS commercialized by MIPS Technologies (www. mips. com) Large share of embedded core market n n Applications in consumer electronics, network/storage equipment, cameras, printers, … Typical of many modern ISAs n See MIPS Reference Data tear-out card, and Appendixes B and E Chapter 2 — Instructions: Language of the Computer — 3

n Add and subtract, three operands n n n Two sources and one destination

n Add and subtract, three operands n n n Two sources and one destination add a, b, c # a gets b + c All arithmetic operations have this form Design Principle 1: Simplicity favours regularity n n § 2. 2 Operations of the Computer Hardware Arithmetic Operations Regularity makes implementation simpler Simplicity enables higher performance at lower cost Chapter 2 — Instructions: Language of the Computer — 4

Arithmetic Example n C code: f = (g + h) - (i + j);

Arithmetic Example n C code: f = (g + h) - (i + j); n Compiled MIPS code: add t 0, g, h add t 1, i, j sub f, t 0, t 1 # temp t 0 = g + h # temp t 1 = i + j # f = t 0 - t 1 Chapter 2 — Instructions: Language of the Computer — 5

n n Arithmetic instructions use register operands MIPS has a 32 × 32 -bit

n n Arithmetic instructions use register operands MIPS has a 32 × 32 -bit register file n n Assembler names n n n Use for frequently accessed data Numbered 0 to 31 32 -bit data called a “word” $t 0, $t 1, …, $t 9 for temporary values $s 0, $s 1, …, $s 7 for saved variables § 2. 3 Operands of the Computer Hardware Register Operands Design Principle 2: Smaller is faster n c. f. main memory: millions of locations Chapter 2 — Instructions: Language of the Computer — 6

Register Operand Example n C code: f = (g + h) - (i +

Register Operand Example n C code: f = (g + h) - (i + j); n f, …, j in $s 0, …, $s 4 n Compiled MIPS code: add $t 0, $s 1, $s 2 add $t 1, $s 3, $s 4 sub $s 0, $t 1 Chapter 2 — Instructions: Language of the Computer — 7

Memory Operands n Main memory used for composite data n n To apply arithmetic

Memory Operands n Main memory used for composite data n n To apply arithmetic operations n n n Each address identifies an 8 -bit byte Words are aligned in memory n n Load values from memory into registers Store result from register to memory Memory is byte addressed n n Arrays, structures, dynamic data Address must be a multiple of 4 MIPS is Big Endian n n Most-significant byte at least address of a word c. f. Little Endian: least-significant byte at least address Chapter 2 — Instructions: Language of the Computer — 8

Memory Operand Example 1 n C code: g = h + A[8]; n g

Memory Operand Example 1 n C code: g = h + A[8]; n g in $s 1, h in $s 2, base address of A in $s 3 n Compiled MIPS code: n Index 8 requires offset of 32 n 4 bytes per word lw $t 0, 32($s 3) add $s 1, $s 2, $t 0 offset # load word base register Chapter 2 — Instructions: Language of the Computer — 9

Memory Operand Example 2 n C code: A[12] = h + A[8]; n h

Memory Operand Example 2 n C code: A[12] = h + A[8]; n h in $s 2, base address of A in $s 3 n Compiled MIPS code: Index 8 requires offset of 32 lw $t 0, 32($s 3) # load word add $t 0, $s 2, $t 0 sw $t 0, 48($s 3) # store word n Chapter 2 — Instructions: Language of the Computer — 10

Registers vs. Memory n n Registers are faster to access than memory Operating on

Registers vs. Memory n n Registers are faster to access than memory Operating on memory data requires loads and stores n n More instructions to be executed Compiler must use registers for variables as much as possible n n Only spill to memory for less frequently used variables Register optimization is important! Chapter 2 — Instructions: Language of the Computer — 11

Immediate Operands n Constant data specified in an instruction addi $s 3, 4 n

Immediate Operands n Constant data specified in an instruction addi $s 3, 4 n No subtract immediate instruction n Just use a negative constant addi $s 2, $s 1, -1 n Design Principle 3: Make the common case fast n n Small constants are common Immediate operand avoids a load instruction Chapter 2 — Instructions: Language of the Computer — 12

The Constant Zero n MIPS register 0 ($zero) is the constant 0 n n

The Constant Zero n MIPS register 0 ($zero) is the constant 0 n n Cannot be overwritten Useful for common operations n E. g. , move between registers add $t 2, $s 1, $zero Chapter 2 — Instructions: Language of the Computer — 13

n n n Given an n-bit number Range: 0 to +2 n – 1

n n n Given an n-bit number Range: 0 to +2 n – 1 Example n n § 2. 4 Signed and Unsigned Numbers Unsigned Binary Integers 0000 0000 10112 = 0 + … + 1× 23 + 0× 22 +1× 21 +1× 20 = 0 + … + 8 + 0 + 2 + 1 = 1110 Using 32 bits n 0 to +4, 294, 967, 295 Chapter 2 — Instructions: Language of the Computer — 14

2 s-Complement Signed Integers n n n Given an n-bit number Range: – 2

2 s-Complement Signed Integers n n n Given an n-bit number Range: – 2 n – 1 to +2 n – 1 Example n n 1111 1111 11002 = – 1× 231 + 1× 230 + … + 1× 22 +0× 21 +0× 20 = – 2, 147, 483, 648 + 2, 147, 483, 644 = – 410 Using 32 bits n – 2, 147, 483, 648 to +2, 147, 483, 647 Chapter 2 — Instructions: Language of the Computer — 15

2 s-Complement Signed Integers n Bit 31 is sign bit n n n 1

2 s-Complement Signed Integers n Bit 31 is sign bit n n n 1 for negative numbers 0 for non-negative numbers –(– 2 n – 1) can’t be represented Non-negative numbers have the same unsigned and 2 s-complement representation Some specific numbers n n 0: 0000 … 0000 – 1: 1111 … 1111 Most-negative: 1000 0000 … 0000 Most-positive: 0111 1111 … 1111 Chapter 2 — Instructions: Language of the Computer — 16

Signed Negation n Complement and add 1 n n Complement means 1 → 0,

Signed Negation n Complement and add 1 n n Complement means 1 → 0, 0 → 1 Example: negate +2 n n +2 = 0000 … 00102 – 2 = 1111 … 11012 + 1 = 1111 … 11102 Chapter 2 — Instructions: Language of the Computer — 17

Sign Extension n Representing a number using more bits n n In MIPS instruction

Sign Extension n Representing a number using more bits n n In MIPS instruction set n n addi: extend immediate value lb, lh: extend loaded byte/halfword beq, bne: extend the displacement Replicate the sign bit to the left n n Preserve the numeric value c. f. unsigned values: extend with 0 s Examples: 8 -bit to 16 -bit n n +2: 0000 0010 => 0000 0010 – 2: 1111 1110 => 1111 1110 Chapter 2 — Instructions: Language of the Computer — 18

n Instructions are encoded in binary n n MIPS instructions n n Called machine

n Instructions are encoded in binary n n MIPS instructions n n Called machine code Encoded as 32 -bit instruction words Small number of formats encoding operation code (opcode), register numbers, … Regularity! Register numbers n n n $t 0 – $t 7 are reg’s 8 – 15 $t 8 – $t 9 are reg’s 24 – 25 $s 0 – $s 7 are reg’s 16 – 23 § 2. 5 Representing Instructions in the Computer Representing Instructions Chapter 2 — Instructions: Language of the Computer — 19

MIPS R-format Instructions n op rs rt rd shamt funct 6 bits 5 bits

MIPS R-format Instructions n op rs rt rd shamt funct 6 bits 5 bits 6 bits Instruction fields n n n op: operation code (opcode) rs: first source register number rt: second source register number rd: destination register number shamt: shift amount (00000 for now) funct: function code (extends opcode) Chapter 2 — Instructions: Language of the Computer — 20

R-format Example op rs rt rd shamt funct 6 bits 5 bits 6 bits

R-format Example op rs rt rd shamt funct 6 bits 5 bits 6 bits add $t 0, $s 1, $s 2 special $s 1 $s 2 $t 0 0 add 0 17 18 8 0 32 000000 10001 10010 01000 00000 10000001100100100001000002 = 0232402016 Chapter 2 — Instructions: Language of the Computer — 21

Hexadecimal n Base 16 n n 0 1 2 3 n Compact representation of

Hexadecimal n Base 16 n n 0 1 2 3 n Compact representation of bit strings 4 bits per hex digit 0000 0001 0010 0011 4 5 6 7 0100 0101 0110 0111 8 9 a b 1000 1001 1010 1011 c d e f 1100 1101 1110 1111 Example: eca 8 6420 n 1110 1100 1010 1000 0110 0100 0010 0000 Chapter 2 — Instructions: Language of the Computer — 22

MIPS I-format Instructions n rs rt constant or address 6 bits 5 bits 16

MIPS I-format Instructions n rs rt constant or address 6 bits 5 bits 16 bits Immediate arithmetic and load/store instructions n n op rt: destination or source register number Constant: – 215 to +215 – 1 Address: offset added to base address in rs Design Principle 4: Good design demands good compromises n n Different formats complicate decoding, but allow 32 -bit instructions uniformly Keep formats as similar as possible Chapter 2 — Instructions: Language of the Computer — 23

Stored Program Computers The BIG Picture n n n Instructions represented in binary, just

Stored Program Computers The BIG Picture n n n Instructions represented in binary, just like data Instructions and data stored in memory Programs can operate on programs n n e. g. , compilers, linkers, … Binary compatibility allows compiled programs to work on different computers n Standardized ISAs Chapter 2 — Instructions: Language of the Computer — 24

n n Instructions for bitwise manipulation Operation C Java MIPS Shift left << <<

n n Instructions for bitwise manipulation Operation C Java MIPS Shift left << << sll Shift right >> >>> srl Bitwise AND & & and, andi Bitwise OR | | or, ori Bitwise NOT ~ ~ nor § 2. 6 Logical Operations Useful for extracting and inserting groups of bits in a word Chapter 2 — Instructions: Language of the Computer — 25

Shift Operations n n rs rt rd shamt funct 6 bits 5 bits 6

Shift Operations n n rs rt rd shamt funct 6 bits 5 bits 6 bits shamt: how many positions to shift Shift left logical n n n op Shift left and fill with 0 bits sll by i bits multiplies by 2 i Shift right logical n n Shift right and fill with 0 bits srl by i bits divides by 2 i (unsigned only) Chapter 2 — Instructions: Language of the Computer — 26

AND Operations n Useful to mask bits in a word n Select some bits,

AND Operations n Useful to mask bits in a word n Select some bits, clear others to 0 and $t 0, $t 1, $t 2 0000 0000 1101 1100 0000 $t 1 0000 0011 1100 0000 $t 0 0000 0000 1100 0000 Chapter 2 — Instructions: Language of the Computer — 27

OR Operations n Useful to include bits in a word n Set some bits

OR Operations n Useful to include bits in a word n Set some bits to 1, leave others unchanged or $t 0, $t 1, $t 2 0000 0000 1101 1100 0000 $t 1 0000 0011 1100 0000 $t 0 0000 0011 1100 0000 Chapter 2 — Instructions: Language of the Computer — 28

NOT Operations n Useful to invert bits in a word n n Change 0

NOT Operations n Useful to invert bits in a word n n Change 0 to 1, and 1 to 0 MIPS has NOR 3 -operand instruction n a NOR b == NOT ( a OR b ) nor $t 0, $t 1, $zero Register 0: always read as zero $t 1 0000 0011 1100 0000 $t 0 1111 1100 0011 1111 Chapter 2 — Instructions: Language of the Computer — 29

n Branch to a labeled instruction if a condition is true n n beq

n Branch to a labeled instruction if a condition is true n n beq rs, rt, L 1 n n if (rs == rt) branch to instruction labeled L 1; bne rs, rt, L 1 n n Otherwise, continue sequentially § 2. 7 Instructions for Making Decisions Conditional Operations if (rs != rt) branch to instruction labeled L 1; j L 1 n unconditional jump to instruction labeled L 1 Chapter 2 — Instructions: Language of the Computer — 30

Compiling If Statements n C code: if (i==j) f = g+h; else f =

Compiling If Statements n C code: if (i==j) f = g+h; else f = g-h; n n f, g, … in $s 0, $s 1, … Compiled MIPS code: bne add j Else: sub Exit: … $s 3, $s 4, Else $s 0, $s 1, $s 2 Exit $s 0, $s 1, $s 2 Assembler calculates addresses Chapter 2 — Instructions: Language of the Computer — 31

Compiling Loop Statements n C code: while (save[i] == k) i += 1; n

Compiling Loop Statements n C code: while (save[i] == k) i += 1; n n i in $s 3, k in $s 5, address of save in $s 6 Compiled MIPS code: Loop: sll add lw bne addi j Exit: … $t 1, $t 0, $s 3, Loop $s 3, 2 $t 1, $s 6 0($t 1) $s 5, Exit $s 3, 1 Chapter 2 — Instructions: Language of the Computer — 32

Basic Blocks n A basic block is a sequence of instructions with n n

Basic Blocks n A basic block is a sequence of instructions with n n No embedded branches (except at end) No branch targets (except at beginning) n n A compiler identifies basic blocks for optimization An advanced processor can accelerate execution of basic blocks Chapter 2 — Instructions: Language of the Computer — 33

More Conditional Operations n Set result to 1 if a condition is true n

More Conditional Operations n Set result to 1 if a condition is true n n slt rd, rs, rt n n if (rs < rt) rd = 1; else rd = 0; slti rt, rs, constant n n Otherwise, set to 0 if (rs < constant) rt = 1; else rt = 0; Use in combination with beq, bne slt $t 0, $s 1, $s 2 bne $t 0, $zero, L # if ($s 1 < $s 2) # branch to L Chapter 2 — Instructions: Language of the Computer — 34

Branch Instruction Design n n Why not blt, bge, etc? Hardware for <, ≥,

Branch Instruction Design n n Why not blt, bge, etc? Hardware for <, ≥, … slower than =, ≠ n n Combining with branch involves more work per instruction, requiring a slower clock All instructions penalized! beq and bne are the common case This is a good design compromise Chapter 2 — Instructions: Language of the Computer — 35

Signed vs. Unsigned n n n Signed comparison: slt, slti Unsigned comparison: sltu, sltui

Signed vs. Unsigned n n n Signed comparison: slt, slti Unsigned comparison: sltu, sltui Example n n n $s 0 = 1111 1111 $s 1 = 0000 0000 0001 slt $t 0, $s 1 # signed n n – 1 < +1 $t 0 = 1 sltu $t 0, $s 1 n # unsigned +4, 294, 967, 295 > +1 $t 0 = 0 Chapter 2 — Instructions: Language of the Computer — 36

n Steps required 1. 2. 3. 4. 5. 6. Place parameters in registers Transfer

n Steps required 1. 2. 3. 4. 5. 6. Place parameters in registers Transfer control to procedure Acquire storage for procedure Perform procedure’s operations Place result in register for caller Return to place of call § 2. 8 Supporting Procedures in Computer Hardware Procedure Calling Chapter 2 — Instructions: Language of the Computer — 37

Register Usage n n n $a 0 – $a 3: arguments (reg’s 4 –

Register Usage n n n $a 0 – $a 3: arguments (reg’s 4 – 7) $v 0, $v 1: result values (reg’s 2 and 3) $t 0 – $t 9: temporaries n n $s 0 – $s 7: saved n n n Can be overwritten by callee Must be saved/restored by callee $gp: global pointer for static data (reg 28) $sp: stack pointer (reg 29) $fp: frame pointer (reg 30) $ra: return address (reg 31) Chapter 2 — Instructions: Language of the Computer — 38

Procedure Call Instructions n Procedure call: jump and link jal Procedure. Label n Address

Procedure Call Instructions n Procedure call: jump and link jal Procedure. Label n Address of following instruction put in $ra n Jumps to target address n Procedure return: jump register jr $ra n Copies $ra to program counter n Can also be used for computed jumps n e. g. , for case/switch statements Chapter 2 — Instructions: Language of the Computer — 39

Leaf Procedure Example n C code: int leaf_example (int g, h, i, j) {

Leaf Procedure Example n C code: int leaf_example (int g, h, i, j) { int f; f = (g + h) - (i + j); return f; } n Arguments g, …, j in $a 0, …, $a 3 n f in $s 0 (hence, need to save $s 0 on stack) n Result in $v 0 Chapter 2 — Instructions: Language of the Computer — 40

Leaf Procedure Example n MIPS code: leaf_example: addi $sp, -4 sw $s 0, 0($sp)

Leaf Procedure Example n MIPS code: leaf_example: addi $sp, -4 sw $s 0, 0($sp) add $t 0, $a 1 add $t 1, $a 2, $a 3 sub $s 0, $t 1 add $v 0, $s 0, $zero lw $s 0, 0($sp) addi $sp, 4 jr $ra Save $s 0 on stack Procedure body Result Restore $s 0 Return Chapter 2 — Instructions: Language of the Computer — 41

Non-Leaf Procedures n n Procedures that call other procedures For nested call, caller needs

Non-Leaf Procedures n n Procedures that call other procedures For nested call, caller needs to save on the stack: n n n Its return address Any arguments and temporaries needed after the call Restore from the stack after the call Chapter 2 — Instructions: Language of the Computer — 42

Non-Leaf Procedure Example n C code: int fact (int n) { if (n <

Non-Leaf Procedure Example n C code: int fact (int n) { if (n < 1) return f; else return n * fact(n - 1); } n Argument n in $a 0 n Result in $v 0 Chapter 2 — Instructions: Language of the Computer — 43

Non-Leaf Procedure Example n MIPS code: fact: addi sw sw slti beq addi jr

Non-Leaf Procedure Example n MIPS code: fact: addi sw sw slti beq addi jr L 1: addi jal lw lw addi mul jr $sp, $ra, $a 0, $t 0, $v 0, $sp, $ra $a 0, fact $a 0, $ra, $sp, $v 0, $ra $sp, -8 4($sp) 0($sp) $a 0, 1 $zero, L 1 $zero, 1 $sp, 8 $a 0, -1 0($sp) 4($sp) $sp, 8 $a 0, $v 0 # # adjust stack for 2 items save return address save argument test for n < 1 # # # # # if so, result is 1 pop 2 items from stack and return else decrement n recursive call restore original n and return address pop 2 items from stack multiply to get result and return Chapter 2 — Instructions: Language of the Computer — 44

Local Data on the Stack n Local data allocated by callee n n e.

Local Data on the Stack n Local data allocated by callee n n e. g. , C automatic variables Procedure frame (activation record) n Used by some compilers to manage stack storage Chapter 2 — Instructions: Language of the Computer — 45

Memory Layout n n Text: program code Static data: global variables n n n

Memory Layout n n Text: program code Static data: global variables n n n Dynamic data: heap n n e. g. , static variables in C, constant arrays and strings $gp initialized to address allowing ±offsets into this segment E. g. , malloc in C, new in Java Stack: automatic storage Chapter 2 — Instructions: Language of the Computer — 46

n Byte-encoded character sets n ASCII: 128 characters n n Latin-1: 256 characters n

n Byte-encoded character sets n ASCII: 128 characters n n Latin-1: 256 characters n n 95 graphic, 33 control ASCII, +96 more graphic characters § 2. 9 Communicating with People Character Data Unicode: 32 -bit character set n n n Used in Java, C++ wide characters, … Most of the world’s alphabets, plus symbols UTF-8, UTF-16: variable-length encodings Chapter 2 — Instructions: Language of the Computer — 47

Byte/Halfword Operations n n Could use bitwise operations MIPS byte/halfword load/store n String processing

Byte/Halfword Operations n n Could use bitwise operations MIPS byte/halfword load/store n String processing is a common case lb rt, offset(rs) n Sign extend to 32 bits in rt lbu rt, offset(rs) n lhu rt, offset(rs) Zero extend to 32 bits in rt sb rt, offset(rs) n lh rt, offset(rs) sh rt, offset(rs) Store just rightmost byte/halfword Chapter 2 — Instructions: Language of the Computer — 48

String Copy Example n C code (naïve): Null-terminated string void strcpy (char x[], char

String Copy Example n C code (naïve): Null-terminated string void strcpy (char x[], char y[]) { int i; i = 0; while ((x[i]=y[i])!='') i += 1; } n Addresses of x, y in $a 0, $a 1 n i in $s 0 n Chapter 2 — Instructions: Language of the Computer — 49

String Copy Example n MIPS code: strcpy: addi sw add L 1: add lbu

String Copy Example n MIPS code: strcpy: addi sw add L 1: add lbu add sb beq addi j L 2: lw addi jr $sp, $s 0, $t 1, $t 2, $t 3, $t 2, $s 0, L 1 $s 0, $sp, $ra $sp, -4 0($sp) $zero, $zero $s 0, $a 1 0($t 1) $s 0, $a 0 0($t 3) $zero, L 2 $s 0, 1 0($sp) $sp, 4 # # # # adjust stack for 1 item save $s 0 i = 0 addr of y[i] in $t 1 $t 2 = y[i] addr of x[i] in $t 3 x[i] = y[i] exit loop if y[i] == 0 i = i + 1 next iteration of loop restore saved $s 0 pop 1 item from stack and return Chapter 2 — Instructions: Language of the Computer — 50

n Most constants are small n n 16 -bit immediate is sufficient For the

n Most constants are small n n 16 -bit immediate is sufficient For the occasional 32 -bit constant lui rt, constant n n Copies 16 -bit constant to left 16 bits of rt Clears right 16 bits of rt to 0 lhi $s 0, 61 0000 0111 1101 0000 ori $s 0, 2304 0000 0111 1101 0000 1001 0000 § 2. 10 MIPS Addressing for 32 -Bit Immediates and Addresses 32 -bit Constants Chapter 2 — Instructions: Language of the Computer — 51

Branch Addressing n Branch instructions specify n n Opcode, two registers, target address Most

Branch Addressing n Branch instructions specify n n Opcode, two registers, target address Most branch targets are near branch n n Forward or backward op rs rt constant or address 6 bits 5 bits 16 bits PC-relative addressing n n Target address = PC + offset × 4 PC already incremented by 4 by this time Chapter 2 — Instructions: Language of the Computer — 52

Jump Addressing n Jump (j and jal) targets could be anywhere in text segment

Jump Addressing n Jump (j and jal) targets could be anywhere in text segment n n Encode full address in instruction op address 6 bits 26 bits (Pseudo)Direct jump addressing n Target address = PC 31… 28 : (address × 4) Chapter 2 — Instructions: Language of the Computer — 53

Target Addressing Example n Loop code from earlier example n Assume Loop at location

Target Addressing Example n Loop code from earlier example n Assume Loop at location 80000 $t 1, $s 3, 2 80000 0 0 19 9 4 0 add $t 1, $s 6 80004 0 9 22 9 0 32 lw $t 0, 0($t 1) 80008 35 9 8 0 bne $t 0, $s 5, Exit 80012 5 8 21 2 addi $s 3, 1 80016 8 19 19 1 j 80020 2 Loop: sll Exit: … Loop 20000 80024 Chapter 2 — Instructions: Language of the Computer — 54

Branching Far Away n n If branch target is too far to encode with

Branching Far Away n n If branch target is too far to encode with 16 -bit offset, assembler rewrites the code Example beq $s 0, $s 1, L 1 ↓ bne $s 0, $s 1, L 2 j L 1 L 2: … Chapter 2 — Instructions: Language of the Computer — 55

Addressing Mode Summary Chapter 2 — Instructions: Language of the Computer — 56

Addressing Mode Summary Chapter 2 — Instructions: Language of the Computer — 56

n Two processors sharing an area of memory n n P 1 writes, then

n Two processors sharing an area of memory n n P 1 writes, then P 2 reads Data race if P 1 and P 2 don’t synchronize n n Hardware support required n n n Result depends of order of accesses Atomic read/write memory operation No other access to the location allowed between the read and write Could be a single instruction n n E. g. , atomic swap of register ↔ memory Or an atomic pair of instructions § 2. 11 Parallelism and Instructions: Synchronization Chapter 2 — Instructions: Language of the Computer — 57

Synchronization in MIPS n n Load linked: ll rt, offset(rs) Store conditional: sc rt,

Synchronization in MIPS n n Load linked: ll rt, offset(rs) Store conditional: sc rt, offset(rs) n Succeeds if location not changed since the ll n n Fails if location is changed n n Returns 1 in rt Returns 0 in rt Example: atomic swap (to test/set lock variable) try: add ll sc beq add $t 0, $zero, $s 4 $t 1, 0($s 1) $t 0, $zero, try $s 4, $zero, $t 1 ; copy exchange value ; load linked ; store conditional ; branch store fails ; put load value in $s 4 Chapter 2 — Instructions: Language of the Computer — 58

Many compilers produce object modules directly Static linking § 2. 12 Translating and Starting

Many compilers produce object modules directly Static linking § 2. 12 Translating and Starting a Program Translation and Startup Chapter 2 — Instructions: Language of the Computer — 59

Assembler Pseudoinstructions n n Most assembler instructions represent machine instructions one-to-one Pseudoinstructions: figments of

Assembler Pseudoinstructions n n Most assembler instructions represent machine instructions one-to-one Pseudoinstructions: figments of the assembler’s imagination → add $t 0, $zero, $t 1 blt $t 0, $t 1, L → slt $at, $t 0, $t 1 move $t 0, $t 1 bne $at, $zero, L n $at (register 1): assembler temporary Chapter 2 — Instructions: Language of the Computer — 60

Producing an Object Module n n Assembler (or compiler) translates program into machine instructions

Producing an Object Module n n Assembler (or compiler) translates program into machine instructions Provides information for building a complete program from the pieces n n n Header: described contents of object module Text segment: translated instructions Static data segment: data allocated for the life of the program Relocation info: for contents that depend on absolute location of loaded program Symbol table: global definitions and external refs Debug info: for associating with source code Chapter 2 — Instructions: Language of the Computer — 61

Linking Object Modules n Produces an executable image 1. Merges segments 2. Resolve labels

Linking Object Modules n Produces an executable image 1. Merges segments 2. Resolve labels (determine their addresses) 3. Patch location-dependent and external refs n Could leave location dependencies for fixing by a relocating loader n n But with virtual memory, no need to do this Program can be loaded into absolute location in virtual memory space Chapter 2 — Instructions: Language of the Computer — 62

Loading a Program n Load from image file on disk into memory 1. Read

Loading a Program n Load from image file on disk into memory 1. Read header to determine segment sizes 2. Create virtual address space 3. Copy text and initialized data into memory n Or set page table entries so they can be faulted in 4. Set up arguments on stack 5. Initialize registers (including $sp, $fp, $gp) 6. Jump to startup routine n n Copies arguments to $a 0, … and calls main When main returns, do exit syscall Chapter 2 — Instructions: Language of the Computer — 63

Dynamic Linking n Only link/load library procedure when it is called n n n

Dynamic Linking n Only link/load library procedure when it is called n n n Requires procedure code to be relocatable Avoids image bloat caused by static linking of all (transitively) referenced libraries Automatically picks up new library versions Chapter 2 — Instructions: Language of the Computer — 64

Lazy Linkage Indirection table Stub: Loads routine ID, Jump to linker/loader Linker/loader code Dynamically

Lazy Linkage Indirection table Stub: Loads routine ID, Jump to linker/loader Linker/loader code Dynamically mapped code Chapter 2 — Instructions: Language of the Computer — 65

Starting Java Applications Simple portable instruction set for the JVM Compiles bytecodes of “hot”

Starting Java Applications Simple portable instruction set for the JVM Compiles bytecodes of “hot” methods into native code for host machine Interprets bytecodes Chapter 2 — Instructions: Language of the Computer — 66

n n Illustrates use of assembly instructions for a C bubble sort function Swap

n n Illustrates use of assembly instructions for a C bubble sort function Swap procedure (leaf) n void swap(int v[], int k) { int temp; temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; } v in $a 0, k in $a 1, temp in $t 0 § 2. 13 A C Sort Example to Put It All Together C Sort Example Chapter 2 — Instructions: Language of the Computer — 67

The Procedure Swap swap: sll $t 1, $a 1, 2 # $t 1 =

The Procedure Swap swap: sll $t 1, $a 1, 2 # $t 1 = k * 4 add $t 1, $a 0, $t 1 # $t 1 = v+(k*4) # (address of v[k]) lw $t 0, 0($t 1) # $t 0 (temp) = v[k] lw $t 2, 4($t 1) # $t 2 = v[k+1] sw $t 2, 0($t 1) # v[k] = $t 2 (v[k+1]) sw $t 0, 4($t 1) # v[k+1] = $t 0 (temp) jr $ra # return to calling routine Chapter 2 — Instructions: Language of the Computer — 68

The Sort Procedure in C n Non-leaf (calls swap) n void sort (int v[],

The Sort Procedure in C n Non-leaf (calls swap) n void sort (int v[], int n) { int i, j; for (i = 0; i < n; i += 1) { for (j = i – 1; j >= 0 && v[j] > v[j + 1]; j -= 1) { swap(v, j); } } } v in $a 0, k in $a 1, i in $s 0, j in $s 1 Chapter 2 — Instructions: Language of the Computer — 69

The Procedure Body move for 1 tst: slt beq addi for 2 tst: slti

The Procedure Body move for 1 tst: slt beq addi for 2 tst: slti bne sll add lw lw slt beq move jal addi j exit 2: addi j $s 2, $a 0 $s 3, $a 1 $s 0, $zero $t 0, $s 3 $t 0, $zero, exit 1 $s 1, $s 0, – 1 $t 0, $s 1, 0 $t 0, $zero, exit 2 $t 1, $s 1, 2 $t 2, $s 2, $t 1 $t 3, 0($t 2) $t 4, 4($t 2) $t 0, $t 4, $t 3 $t 0, $zero, exit 2 $a 0, $s 2 $a 1, $s 1 swap $s 1, – 1 for 2 tst $s 0, 1 for 1 tst # # # # # # save $a 0 into $s 2 save $a 1 into $s 3 i = 0 $t 0 = 0 if $s 0 ≥ $s 3 (i ≥ n) go to exit 1 if $s 0 ≥ $s 3 (i ≥ n) j = i – 1 $t 0 = 1 if $s 1 < 0 (j < 0) go to exit 2 if $s 1 < 0 (j < 0) $t 1 = j * 4 $t 2 = v + (j * 4) $t 3 = v[j] $t 4 = v[j + 1] $t 0 = 0 if $t 4 ≥ $t 3 go to exit 2 if $t 4 ≥ $t 3 1 st param of swap is v (old $a 0) 2 nd param of swap is j call swap procedure j –= 1 jump to test of inner loop i += 1 jump to test of outer loop Move params Outer loop Inner loop Pass params & call Inner loop Outer loop Chapter 2 — Instructions: Language of the Computer — 70

The Full Procedure sort: addi $sp, – 20 sw $ra, 16($sp) sw $s 3,

The Full Procedure sort: addi $sp, – 20 sw $ra, 16($sp) sw $s 3, 12($sp) sw $s 2, 8($sp) sw $s 1, 4($sp) sw $s 0, 0($sp) … … exit 1: lw $s 0, 0($sp) lw $s 1, 4($sp) lw $s 2, 8($sp) lw $s 3, 12($sp) lw $ra, 16($sp) addi $sp, 20 jr $ra # # # # make room on stack for 5 registers save $ra on stack save $s 3 on stack save $s 2 on stack save $s 1 on stack save $s 0 on stack procedure body # # # # restore $s 0 from stack restore $s 1 from stack restore $s 2 from stack restore $s 3 from stack restore $ra from stack restore stack pointer return to calling routine Chapter 2 — Instructions: Language of the Computer — 71

Effect of Compiler Optimization Compiled with gcc for Pentium 4 under Linux Chapter 2

Effect of Compiler Optimization Compiled with gcc for Pentium 4 under Linux Chapter 2 — Instructions: Language of the Computer — 72

Effect of Language and Algorithm Chapter 2 — Instructions: Language of the Computer —

Effect of Language and Algorithm Chapter 2 — Instructions: Language of the Computer — 73

Lessons Learnt n n n Instruction count and CPI are not good performance indicators

Lessons Learnt n n n Instruction count and CPI are not good performance indicators in isolation Compiler optimizations are sensitive to the algorithm Java/JIT compiled code is significantly faster than JVM interpreted n n Comparable to optimized C in some cases Nothing can fix a dumb algorithm! Chapter 2 — Instructions: Language of the Computer — 74

n Array indexing involves n n n Multiplying index by element size Adding to

n Array indexing involves n n n Multiplying index by element size Adding to array base address Pointers correspond directly to memory addresses n § 2. 14 Arrays versus Pointers Arrays vs. Pointers Can avoid indexing complexity Chapter 2 — Instructions: Language of the Computer — 75

Example: Clearing and Array clear 1(int array[], int size) { int i; for (i

Example: Clearing and Array clear 1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear 2(int *array, int size) { int *p; for (p = &array[0]; p < &array[size]; p = p + 1) *p = 0; } move $t 0, $zero loop 1: sll $t 1, $t 0, 2 add $t 2, $a 0, $t 1 move $t 0, $a 0 # p = & array[0] sll $t 1, $a 1, 2 # $t 1 = size * 4 add $t 2, $a 0, $t 1 # $t 2 = # &array[size] loop 2: sw $zero, 0($t 0) # Memory[p] = 0 addi $t 0, 4 # p = p + 4 slt $t 3, $t 0, $t 2 # $t 3 = #(p<&array[size]) bne $t 3, $zero, loop 2 # if (…) # goto loop 2 # i = 0 # $t 1 = i * 4 # $t 2 = # &array[i] sw $zero, 0($t 2) # array[i] = 0 addi $t 0, 1 # i = i + 1 slt $t 3, $t 0, $a 1 # $t 3 = # (i < size) bne $t 3, $zero, loop 1 # if (…) # goto loop 1 Chapter 2 — Instructions: Language of the Computer — 76

Comparison of Array vs. Ptr n n Multiply “strength reduced” to shift Array version

Comparison of Array vs. Ptr n n Multiply “strength reduced” to shift Array version requires shift to be inside loop n n n Part of index calculation for incremented i c. f. incrementing pointer Compiler can achieve same effect as manual use of pointers n n Induction variable elimination Better to make program clearer and safer Chapter 2 — Instructions: Language of the Computer — 77

n n ARM: the most popular embedded core Similar basic set of instructions to

n n ARM: the most popular embedded core Similar basic set of instructions to MIPS ARM MIPS 1985 Instruction size 32 bits Address space 32 -bit flat Data alignment Aligned 9 3 15 × 32 -bit 31 × 32 -bit Memory mapped Date announced Data addressing modes Registers Input/output § 2. 16 Real Stuff: ARM Instructions ARM & MIPS Similarities Chapter 2 — Instructions: Language of the Computer — 78

Compare and Branch in ARM n Uses condition codes for result of an arithmetic/logical

Compare and Branch in ARM n Uses condition codes for result of an arithmetic/logical instruction n Negative, zero, carry, overflow Compare instructions to set condition codes without keeping the result Each instruction can be conditional n n Top 4 bits of instruction word: condition value Can avoid branches over single instructions Chapter 2 — Instructions: Language of the Computer — 79

Instruction Encoding Chapter 2 — Instructions: Language of the Computer — 80

Instruction Encoding Chapter 2 — Instructions: Language of the Computer — 80

n Evolution with backward compatibility n 8080 (1974): 8 -bit microprocessor n n 8086

n Evolution with backward compatibility n 8080 (1974): 8 -bit microprocessor n n 8086 (1978): 16 -bit extension to 8080 n n Adds FP instructions and register stack 80286 (1982): 24 -bit addresses, MMU n n Complex instruction set (CISC) 8087 (1980): floating-point coprocessor n n Accumulator, plus 3 index-register pairs § 2. 17 Real Stuff: x 86 Instructions The Intel x 86 ISA Segmented memory mapping and protection 80386 (1985): 32 -bit extension (now IA-32) n n Additional addressing modes and operations Paged memory mapping as well as segments Chapter 2 — Instructions: Language of the Computer — 81

The Intel x 86 ISA n Further evolution… n i 486 (1989): pipelined, on-chip

The Intel x 86 ISA n Further evolution… n i 486 (1989): pipelined, on-chip caches and FPU n n Pentium (1993): superscalar, 64 -bit datapath n n n New microarchitecture (see Colwell, The Pentium Chronicles) Pentium III (1999) n n Later versions added MMX (Multi-Media e. Xtension) instructions The infamous FDIV bug Pentium Pro (1995), Pentium II (1997) n n Compatible competitors: AMD, Cyrix, … Added SSE (Streaming SIMD Extensions) and associated registers Pentium 4 (2001) n n New microarchitecture Added SSE 2 instructions Chapter 2 — Instructions: Language of the Computer — 82

The Intel x 86 ISA n And further… n n AMD 64 (2003): extended

The Intel x 86 ISA n And further… n n AMD 64 (2003): extended architecture to 64 bits EM 64 T – Extended Memory 64 Technology (2004) n n n Intel Core (2006) n n Intel declined to follow, instead… Advanced Vector Extension (announced 2008) n n Added SSE 4 instructions, virtual machine support AMD 64 (announced 2007): SSE 5 instructions n n AMD 64 adopted by Intel (with refinements) Added SSE 3 instructions Longer SSE registers, more instructions If Intel didn’t extend with compatibility, its competitors would! n Technical elegance ≠ market success Chapter 2 — Instructions: Language of the Computer — 83

Basic x 86 Registers Chapter 2 — Instructions: Language of the Computer — 84

Basic x 86 Registers Chapter 2 — Instructions: Language of the Computer — 84

Basic x 86 Addressing Modes n n Two operands per instruction Source/dest operand Second

Basic x 86 Addressing Modes n n Two operands per instruction Source/dest operand Second source operand Register Immediate Register Memory Immediate Memory addressing modes n n Address in register Address = Rbase + displacement Address = Rbase + 2 scale × Rindex (scale = 0, 1, 2, or 3) Address = Rbase + 2 scale × Rindex + displacement Chapter 2 — Instructions: Language of the Computer — 85

x 86 Instruction Encoding n Variable length encoding n n Postfix bytes specify addressing

x 86 Instruction Encoding n Variable length encoding n n Postfix bytes specify addressing mode Prefix bytes modify operation n Operand length, repetition, locking, … Chapter 2 — Instructions: Language of the Computer — 86

Implementing IA-32 n Complex instruction set makes implementation difficult n Hardware translates instructions to

Implementing IA-32 n Complex instruction set makes implementation difficult n Hardware translates instructions to simpler microoperations n n n Simple instructions: 1– 1 Complex instructions: 1–many Microengine similar to RISC Market share makes this economically viable Comparable performance to RISC n Compilers avoid complex instructions Chapter 2 — Instructions: Language of the Computer — 87

n Powerful instruction higher performance n n Fewer instructions required But complex instructions are

n Powerful instruction higher performance n n Fewer instructions required But complex instructions are hard to implement n n n May slow down all instructions, including simple ones § 2. 18 Fallacies and Pitfalls Fallacies Compilers are good at making fast code from simple instructions Use assembly code for high performance n n But modern compilers are better at dealing with modern processors More lines of code more errors and less productivity Chapter 2 — Instructions: Language of the Computer — 88

Fallacies n Backward compatibility instruction set doesn’t change n But they do accrete more

Fallacies n Backward compatibility instruction set doesn’t change n But they do accrete more instructions x 86 instruction set Chapter 2 — Instructions: Language of the Computer — 89

Pitfalls n Sequential words are not at sequential addresses n n Increment by 4,

Pitfalls n Sequential words are not at sequential addresses n n Increment by 4, not by 1! Keeping a pointer to an automatic variable after procedure returns n n e. g. , passing pointer back via an argument Pointer becomes invalid when stack popped Chapter 2 — Instructions: Language of the Computer — 90

n Design principles 1. 2. 3. 4. n Layers of software/hardware n n Simplicity

n Design principles 1. 2. 3. 4. n Layers of software/hardware n n Simplicity favors regularity Smaller is faster Make the common case fast Good design demands good compromises § 2. 19 Concluding Remarks Compiler, assembler, hardware MIPS: typical of RISC ISAs n c. f. x 86 Chapter 2 — Instructions: Language of the Computer — 91

Concluding Remarks n Measure MIPS instruction executions in benchmark programs n n Consider making

Concluding Remarks n Measure MIPS instruction executions in benchmark programs n n Consider making the common case fast Consider compromises Instruction class MIPS examples SPEC 2006 Int SPEC 2006 FP Arithmetic add, sub, addi 16% 48% Data transfer lw, sw, lbu, lhu, sb, lui 35% 36% Logical and, or, nor, andi, ori, sll, srl 12% 4% Cond. Branch beq, bne, slti, sltiu 34% 8% Jump j, jr, jal 2% 0% Chapter 2 — Instructions: Language of the Computer — 92