Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 4 (Sep 3), slide deck
04-machine-beta. Reading: CS:APP3e §3.6–3.7. Lab: L2 (bomblab) is released. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes. It reuses Lecture 3’s simulatorx86sim.pyand runs clang’s real x86-64 output (-Ogand-O1). The slides’ gcc listings, for the jump-to-middle loop and the jump table, are also run as text, so both compilers’ styles appear. Every simulated function was checked against the real x86-64 code (run under Rosetta 2 on an Apple M4 Pro) on 3,000 inputs at each optimization level: 0 disagreements. The branch-prediction timings were measured natively on that M4 Pro. Code:code/lecture04/. Reading time: ~90 minutes; ~40 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Decode a simple x86-64 instruction from its bytes (prefix, opcode, ModRM, SIB, displacement), and tell from context which register values are pointers.
- Translate
if/elseinto its goto form, and explain when a compiler uses a conditional move instead of a branch, and when it must not. - Explain why branches are expensive when mispredicted, with a number measured on a real CPU.
- Translate
do-while,whileandforloops into goto form, and recognize the jump-to-middle and guarded-do shapes in assembly. - Explain how a
switchbecomes a jump table (including fall-through, shared and missing cases, and the one-comparison bounds check), and when it becomes a decision tree instead. - Describe the x86-64 run-time stack,
push/pop, and howcall/rettransfer control and find the return address.
0.2 Prerequisites and scope
- Lecture 3: registers, operands,
mov/lea, arithmetic, and especially the condition-code table (§9.3). You will use it on every page. - In scope: the slides of Lecture 4 (a review of encoding and pointers; loops; switch; the start of procedures) and CS:APP §3.6.6–3.6.8 (conditional moves, loops, switch), plus §3.7.1–3.7.2.
- Next lecture: the rest of procedures (arguments on the stack, local variables, register-saving conventions, recursion) and arrays.
0.3 Section → code map
| Section | Idea | Demo in code/lecture04/ |
|---|---|---|
| §1 | review: encoding, AT&T/Intel, lea, pointers, condition codes | 01_instruction_encoding.py |
| §2 | if/else: branches vs cmov; branch prediction | 02_branches_and_cmov.py, 03_branch_prediction.c |
| §3 | loops: do-while, while, for | 04_loops.py |
| §4 | switch: jump tables and decision trees | 05_switch_jump_tables.py |
| §5 | the stack; call and ret | 06_stack_call_ret.py |
| — | the simulator vs real hardware | 07_crosscheck.py |
1. Review of a few tricky bits
The slides open by revisiting the parts of Lecture 3 that students find hardest. These notes do the same, with a demo for the first one.
1.1 How an instruction becomes bytes
Lecture 3 showed that movq %rax, (%rbx) is the three bytes 48 89 03. The slides then split those bytes into fields. 01_instruction_encoding.py does it bit by bit:
48 = 01001000 REX prefix 0100|W R X B: W=1 (64-bit operands) R=0 X=0 B=0
89 = 10001001 opcode: MOV r/m <- reg (8b would be reg <- r/m)
03 = 00000011 ModRM: mod=00 reg=000 r/m=011
mod=00 -> memory operand, no displacement
reg=000 -> register 0 = %rax (the source)
r/m=011 -> register 3 = %rbx, used as the ADDRESS: (%rbx)
The general layout of an x86-64 instruction is:
[prefixes] [REX] opcode [ModRM] [SIB] [displacement] [immediate]
- Prefixes: for example 0x66, which selects 16-bit operands.
- REX (0x40–0x4F): AMD’s 2003 addition for 64-bit mode. W selects 64-bit operands, and R, X, B each supply a fourth register-number bit, so 16 registers can be named where 3 bits only reach 8. That is how
%r8–%r15exist. - ModRM: names the two operands.
regis a register;mod+r/mis either a register (mod = 11) or a memory operand with no, 8-bit or 32-bit displacement. - SIB (scale-index-base): present when the memory operand needs an index. Its three fields are the
S,Ri,RbofD(Rb,Ri,S).
Register numbers follow the hardware order rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, not alphabetical order. More shapes:
48 8b 04 f7 -> movq (%rdi,%rsi,8), %rax array load a[i]: SIB byte, scale 8
4c 89 c0 -> movq %r8, %rax register to register, REX.R names %r8
89 54 b7 10 -> movl %edx, 0x10(%rdi,%rsi,4) no REX: 32-bit, disp8 = 0x10
88 14 37 -> movb %dl, (%rdi,%rsi) byte store d[y] = a
48 8b 05 10 00 00 00 -> movq 0x10(%rip), %rax RIP-relative: a global variable
How much of x86 does this tiny decoder understand? The demo runs it over every register/memory mov (opcodes 88/89/8a/8b) in the x86-64 slice of a real system program, /bin/ls. It agrees with objdump on 841 of 841 instructions. (Swapping two register numbers in the decoder drops this to 689, so the check has teeth.) You don’t need to decode bytes by hand in this course, but knowing that this is all there is takes the mystery out of objdump’s middle column.
1.2 AT&T vs Intel, once more
15-213 uses AT&T syntax: movq %rax, (%rbx) is source, destination. Intel syntax writes the same instruction as mov qword ptr [rbx], rax, destination first. Lecture 3 §10.4 has the full comparison table. If an instruction seems backwards, check which syntax you are reading.
1.3 lea does not touch memory
| Assembly | C equivalent |
|---|---|
mov 6(%rbx,%rdi,8), %ax | ax = *(rbx + rdi*8 + 6) |
add 6(%rbx,%rdi,8), %ax | ax += *(rbx + rdi*8 + 6) |
xor %ax, 6(%rbx,%rdi,8) | *(rbx + rdi*8 + 6) ^= ax |
lea 6(%rbx,%rdi,8), %rax | rax = rbx + rdi*8 + 6 |
In every other instruction a memory operand accesses memory. lea only computes the address. Its designers meant it for pointers (&rbx[rdi]); compilers also use it for arithmetic (lea (%rbx,%rbx,2) = 3·rbx) because it has three operands and does not change the condition codes.
1.4 Which numbers are pointers?
Registers carry no type labels; gdb’s info registers shows only numbers. Following the slides, you infer which ones are pointers from context:
%rspand%ripalways hold pointers (to the stack and to the code).- Values close to
%rsp(around 0x7ffff…) or to%rip(around 0x400000) are probably pointers too. - A register used as a base in a memory operand, as in
mov (%rsi), %rsi, is expected to be a pointer. If the program crashes there, that register held a bad pointer. - In
(%rsi,%rbx,2),%rsiis the pointer and%rbxis not: a scaled index counts elements. In0x400570(,%rbx,2), the constant 0x400570 is the pointer (a global array). lea (anything), %raxmay or may not produce a pointer. It is often plain arithmetic.
This inference is the daily bread of bomblab.
1.5 Condition codes, recapped
cmp b, a (computes a − b) and test b, a (computes a & b) set CF ZF SF OF and discard the result. Ordinary arithmetic sets them as a side effect too; lea never does. jcc, setcc and (new in this lecture) cmovcc read them. Signed conditions (g, ge, l, le) use SF, OF and ZF; unsigned ones (a, ae, b, be) use CF and ZF. Lecture 3 §9 has the table, verified there on all 65,536 pairs of bytes.
2. Conditionals: branches and conditional moves
2.1 The goto form of if/else
C’s if (test) then-statement else else-statement becomes, in assembly, exactly this goto program (CS:APP §3.6.5):
t = test;
if (!t) goto Else;
then-statement;
goto Done;
Else:
else-statement;
Done:
Assembly has no blocks. A conditional jump skips over the code that shouldn’t run, and an unconditional jump skips the else part after the then part. 02_branches_and_cmov.py shows clang’s version of a function with side effects in both branches:
long lt_cnt, ge_cnt;
long absdiff_se(long x, long y) {
if (x < y) { lt_cnt++; return y - x; }
else { ge_cnt++; return x - y; }
}
movq %rdi, %rax
subq %rsi, %rax # %rax = x - y, and the flags describe x - y
jge LBB1_2 # x - y >= 0 -> else part
incq _lt_cnt(%rip) # then part
movq %rsi, %rax
subq %rdi, %rax
retq
LBB1_2:
incq _ge_cnt(%rip) # else part: x - y is already in %rax
retq
Two details are worth noticing. First, the compiler reused the subq that computes x − y as the comparison: no separate cmp is needed, because sub sets the flags too. Second, incq _lt_cnt(%rip) increments a global variable directly in memory, addressed relative to the instruction pointer (the RIP-relative operand from §1.1). The trace for x = 3, y = 10:
subq %rsi, %rax %rax=-7
jge LBB1_2 (not taken)
incq _lt_cnt(%rip) M[_lt_cnt] 0->1
2.2 Why branches are expensive: pipelines and prediction
To understand the alternative, you need one fact about modern processors (CS:APP §5.7 goes deeper). A CPU does not finish one instruction before starting the next. It pipelines instructions, fetching and decoding perhaps 15–20 stages ahead of the one completing, and it executes them out of order when it can. At a conditional branch, the instructions that come next depend on a condition that hasn’t been computed yet. The CPU cannot wait: it predicts the direction, using a predictor that learns from past behavior, and executes speculatively. If the guess was right, nothing was lost. If it was wrong, all the speculative work is thrown away and the pipeline restarts from the correct target. That is a branch misprediction penalty.
How big is it? 03_branch_prediction.c sums the elements ≥ 128 of a million random values in 0..255, first in random order and then sorted. It does this three ways:
version random ns/el sorted ns/el ratio
branchy (real jump) 2.799 0.262 10.7x (sums equal: yes)
branchless (mask) 0.256 0.257 1.0x (sums equal: yes)
plain C (compiler's) 0.251 0.252 1.0x (sums equal: yes)
extra time of the branchy loop on random data, spread over ~N/2
mispredictions: about 5.1 ns per misprediction
(at a clock of 4-4.5 GHz that is roughly 20-23 cycles)
The branchy loop executes the same instructions on both inputs and computes the same sum, yet it is 10.7× slower on random data. On sorted data the branch goes “no, no, …, no, yes, yes, …” and the predictor is almost always right. On random data it is a coin flip, the guess is wrong about half the time, and each wrong guess costs about 5 ns, roughly 20 cycles. The branchless version doesn’t care about the order of the data, because there is nothing to predict. (These timings come from one run on an Apple M4 Pro, arm64. Your numbers will differ; the ratio is the lesson.) The third row is the most interesting. Given the plain C if (a[i] >= t) s += a[i];, clang chose the branchless form by itself: its assembly uses arm64’s csel (conditional select). The benchmark needs an empty asm volatile inside the branchy version just to stop the compiler from doing that.
2.3 Conditional moves
The branchless alternative is: compute both outcomes, then select one with an instruction that has no jump. On x86-64 that instruction is cmovcc S, D: copy S to D if condition cc holds, otherwise do nothing. The data flow then doesn’t depend on a guess. CS:APP’s absdiff shows it:
long absdiff(long x, long y) { return x < y ? y - x : x - y; } /* written with if/else in control.c */
movq %rdi, %rax
subq %rsi, %rax # %rax = x - y
subq %rdi, %rsi # %rsi = y - x, and the flags now describe y - x
cmovgeq %rsi, %rax # if y - x >= 0: %rax = y - x
retq
There is no jump at all. Both differences are always computed, and cmovge reads the flags of the last flag-setting instruction, subq %rdi,%rsi (y − x), so it picks y − x exactly when y − x ≥ 0. Traced for both orders:
x=3, y=10: ... cmovgeq %rsi, %rax %rax=7 (move done)
x=10, y=3: ... cmovgeq %rsi, %rax (move skipped) -> %rax = 7 already
In goto-free C, the compiler turned the code into:
long rval = x - y;
long eval = y - x;
if (y - x >= 0) rval = eval; /* one cmov, no branch */
return rval;
2.4 When the compiler must not use cmov
cmov always pays for both sides. That is wrong, or a bad idea, in three cases (CS:APP §3.6.6):
- Side effects. In
absdiff_se, computing both sides would increment both counters, which changes the program’s meaning. So: a branch (§2.1). - Possible faults. In
return p ? *p : 0;, computing the “then” value before the test would dereference NULL:
With p = NULL the load is never executed. Atestq %rdi, %rdi je LBB2_1 # p == NULL -> return 0 movq (%rdi), %rax # only reached when p != NULL retq LBB2_1: xorl %eax, %eax retqcmovversion would execute it first and crash with a segmentation fault (Lecture 1, Reality #3). - Expensive computations. If one side is a long calculation, doing it every time can cost more than the occasional misprediction, especially when the branch is predictable (the sorted case of §2.2).
The compiler weighs these cases. It can see side effects and possible faults, but it can only guess how predictable your branch is. That is why performance-critical code is sometimes rewritten by hand in a branchless form, as in the “mask” version of the benchmark.
3. Loops
3.1 There are no loops, only backward jumps
The slides ask: what distinguishes a loop’s goto from an if’s goto? The answer is its direction. A loop jumps backward, to code that already ran. A loop has four parts: initializer, test, update and body. C’s three loop statements put them in different places, and the compiler turns each into gotos.
3.2 do-while
long pcount_do(unsigned long x) { /* count the 1 bits of x */
long result = 0;
do { result += x & 0x1; x >>= 1; } while (x);
return result;
}
The goto form tests at the bottom:
long result = 0;
loop:
result += x & 0x1;
x >>= 1;
if (x) goto loop;
return result;
Clang’s code (04_loops.py):
xorl %eax, %eax # result = 0
movq %rdi, %rcx # %rcx = x (will hold x >> 1)
LBB3_1:
movl %edi, %edx
andl $1, %edx # t = x & 1
addq %rdx, %rax # result += t
shrq %rcx # %rcx = x >> 1
cmpq $1, %rdi # is the OLD x > 1 ? (unsigned)
movq %rcx, %rdi # x = x >> 1 (mov does not change the flags)
ja LBB3_1 # backward jump = the loop
...
retq
The backward ja LBB3_1 is the loop. Clang plays a small trick: instead of testing the new x against 0, it tests whether the old x is above 1, which is the same thing, since x >> 1 ≠ 0 exactly when x > 1 for unsigned x. It slips the movq between the cmp and the ja, because mov never changes the flags. The trace for x = 0b1011 shows four iterations of 7 instructions each, one per bit position up to the highest 1 bit, accumulating %rax = 1, 2, 2, 3.
3.3 while: jump to the middle, or guard and do
A while loop tests before the first iteration: while (x) { body } must run zero times when x = 0. There are two standard translations (CS:APP §3.6.7).
Jump to middle (gcc -Og, which the slides use): jump straight to the test, then continue as a do-while.
goto test;
loop:
body;
test:
if (x) goto loop;
Guarded do (gcc -O1, and clang at both levels): test once up front; if the loop runs at all, run it as a do-while.
if (!x) goto done;
loop:
body;
if (x) goto loop;
done:
Clang’s pcount_while is the do-while of §3.2 with a guard added in front (testq %rdi,%rdi; je LBB4_3). Since clang never emits jump-to-middle, the demo feeds the slides’ gcc -Og code to the simulator as text:
pcount_while_jtm:
movl $0, %eax
jmp .L2 # jump to the test first
.L3: movq %rdi, %rdx # loop body
andl $1, %edx
addq %rdx, %rax
shrq %rdi
.L2: testq %rdi, %rdi # test
jne .L3
ret
Why would an optimizing compiler prefer the guarded form? Inside a guarded do-while the compiler knows the body runs at least once and that the test was true on entry. That knowledge enables other optimizations, such as hoisting computations out of the loop (Lecture 15). Jump-to-middle has the smallest code, which is why gcc uses it at -Og.
3.4 for
A for (init; test; update) body loop is a while loop in disguise:
init;
while (test) {
body;
update;
}
Then it is translated like any while. If the compiler can prove that the test is true the first time, the guard disappears:
#define WSIZE (8*sizeof(long))
long pcount_for(unsigned long x) {
long result = 0;
for (unsigned long i = 0; i < WSIZE; i++) result += (x >> i) & 0x1;
return result;
}
clang -Og: clang -O1:
xorl %eax, %eax xorl %eax, %eax
xorl %ecx, %ecx # i = 0 xorl %ecx, %ecx
LBB5_1: LBB5_1:
xorl %edx, %edx btq %rcx, %rdi # CF = bit i of x
btq %rcx, %rdi adcq $0, %rax # result += 0 + CF
setb %dl incq %rcx
addq %rdx, %rax cmpq $64, %rcx
incq %rcx jne LBB5_1
cmpq $64, %rcx retq
jne LBB5_1
There is no guard, because 0 < 64 is obviously true. And there are two instructions you haven’t met. bt (bit test) copies one bit of a register into CF, which is exactly (x >> i) & 1. adc (add with carry) adds CF as well, so adcq $0, %rax means result += CF. When you meet an unfamiliar instruction in a disassembly, look it up; the C meaning doesn’t change. (The simulator gained bt, adc and sbb for this lecture.)
3.5 How much work is a loop? Counting instructions
The simulator counts instructions executed per call:
x do while while-JTM for -Og for -O1
0x0 11 5 5 452 323 popcount=0
0x1 11 13 11 452 323 popcount=1
0xb 32 34 29 452 323 popcount=3
0xff 60 62 53 452 323 popcount=8
0x8000000000000000 452 454 389 452 323 popcount=1
0xffffffffffffffff 452 454 389 452 323 popcount=64
All five versions return the same popcount. Reading the table:
- x = 0: the do-while still runs its body once (11 instructions), while both
whileversions skip it (5). That is the semantic difference between the two loops, visible in instruction counts. - x ≠ 0: clang’s
whilecosts exactly 2 more than its do-while (the guard’stestq/je). gcc’s jump-to-middle loop is 6 instructions per iteration against clang’s 7. - The
do/whileversions loop once per bit position up to the highest 1 bit, so their cost depends on x. Theforversion always loops 64 times: 7 instructions per iteration at-Og, 5 at-O1.
Instruction count is only a first approximation of time, as Lecture 1 showed (Reality #4) and §2.2 measured. A mispredicted loop exit costs more than an instruction.
4. switch statements
4.1 The idea: an array of code addresses
A chain of if/else if tests takes longer the further down the matching case is. A switch over a dense range of integer constants can do better: put the address of each case’s code in an array (the jump table), index it with the switch value, and jump indirectly to the address found there. Every case then costs the same: one bounds check, one load, one indirect jump.
switch (x) { jtab: Targ0 ──▶ code block 0
case val_0: Block 0 Targ1 ──▶ code block 1
case val_1: Block 1 Targ2 ──▶ code block 2
... ...
case val_n-1: Block n-1 Targn-1 ──▶ code block n-1
}
translation (extended C): goto *JTab[x];
This is also why C only allows integer constants as case labels: the compiler must lay the table out at compile time.
4.2 The example and the slides’ gcc version
long switch_eg(long x, long y, long z) {
long w = 1;
switch (x) {
case 1: w = y * z; break;
case 2: w = y / z; /* Fall Through */
case 3: w += z; break;
case 5:
case 6: w -= z; break;
default: w = 2;
}
return w;
}
It has every awkward feature: several labels sharing code (5 and 6), fall-through (2 into 3), a missing case (4), and a default. Here is the slides’ gcc code, which 05_switch_jump_tables.py runs as text in the simulator:
switch_eg:
movq %rdx, %rcx # save z: cqto/idivq will overwrite %rdx
cmpq $6, %rdi # x : 6
ja .L8 # unsigned: x > 6 OR x < 0 -> default
jmp *.L4(,%rdi,8) # goto *JTab[x]
.L3: movq %rsi, %rax ; imulq %rdx, %rax ; ret # case 1
.L5: movq %rsi, %rax ; cqto ; idivq %rcx ; jmp .L6 # case 2, then "fall through"
.L9: movl $1, %eax # case 3: w = 1
.L6: addq %rcx, %rax ; ret # merge: w += z
.L7: movl $1, %eax ; subq %rdx, %rax ; ret # case 5, 6
.L8: movl $2, %eax ; ret # default
.section .rodata
.align 8
.L4: .quad .L8, .L3, .L5, .L9, .L8, .L7, .L7 # x = 0 .. 6
Read the pieces:
- One comparison, two bounds.
cmpq $6, %rdi; ja .L8uses the unsigned conditionja. A negative x, viewed as unsigned, is huge (Lecture 2), so it is “above 6” too. One test rejects both x < 0 and x > 6. - The indirect jump.
jmp *.L4(,%rdi,8)reads the 8-byte entry at address .L4 + 8·x and jumps there. The*marks an indirect jump; the scale 8 is the size of an address. - The table sits in read-only data. The missing cases 0 and 4 point to the default
.L8, and the shared cases 5 and 6 point to the same block.L7. - Fall-through is code placement. Case 2 computes y/z and jumps to
.L6, the second half of case 3. Case 3 itself starts at.L9(w = 1) and falls into.L6. - Why save z in
%rcx? Division usescqto(sign-extend%raxinto%rdx:%rax) andidivq(divide%rdx:%rax; quotient →%rax, remainder →%rdx). Both destroy%rdx, which held z.
4.3 Clang’s version: relative offsets
Clang’s table is different, which makes a good exercise in reading:
movl $2, %eax # w = 2 (the default), in advance
leaq -1(%rdi), %rcx # index = x - 1: cases 1..6 -> 0..5
cmpq $5, %rcx
ja LBB6_3 # unsigned x-1 > 5 -> default (just 'ret')
leaq LJTI6_0(%rip), %r8 # address of the table
movslq (%r8,%rcx,4), %rcx # load a 4-byte SIGNED offset
addq %r8, %rcx # target = table + offset
jmpq *%rcx # indirect jump
Its table holds 4-byte offsets relative to the table, not 8-byte addresses. That is half the size, and position-independent: it works wherever the program is loaded (Lecture 7). The demo reads the six entries straight out of simulated memory:
the table at LJTI6_0 (0x400190), read from memory:
entry 0 (x = 1): offset -40 -> 0x400168 = LBB6_5
entry 1 (x = 2): offset -28 -> 0x400174 = LBB6_6
entry 2 (x = 3): offset -52 -> 0x40015c = LBB6_4
entry 3 (x = 4): offset -56 -> 0x400158 = LBB6_3 (default: just 'ret', %eax is 2)
entry 4 (x = 5): offset -64 -> 0x400150 = LBB6_2
entry 5 (x = 6): offset -64 -> 0x400150 = LBB6_2
(The addresses are the simulator’s made-up ones.) Clang subtracted 1 from x because the cases start at 1, which saves a table entry, and it applies the same unsigned trick: x = 0 gives x − 1 = −1 = 0xff…ff, “above” 5. The slides mention this “alternate version” of jump tables: “rip + jump table address + offset”. The demo then runs x = −2 … 8 through clang’s code, gcc’s code and the real binary:
x C says clang-sim gcc-sim hardware path in gcc's code
-2 2 2 2 2 .L8
1 85 85 85 85 .L3
2 8 8 8 8 .L5 -> .L6
3 6 6 6 6 .L9 -> .L6
4 2 2 2 2 .L8
5 -4 -4 -4 -4 .L7
8 2 2 2 2 .L8
(Rows −1, 0, 6 and 7 are in the demo output and agree too.)
4.4 Finding a jump table in a binary
In bomblab you have no .s file, only objdump output. A jump table is recognizable by an indirect jump, jmp *0x4007f0(,%rdi,8) in gcc’s style or jmpq *%rcx after a movslq/add in clang’s. Its entries live in data, which you inspect in gdb. The slides’ example is x/8xg 0x4007f0, “examine 8 giant (8-byte) words in hex”. Each entry is a code address inside the function, and matching them to the code blocks recovers the switch.
4.5 Sparse cases: a decision tree
When the case values are far apart, a table would be mostly default entries. For cases 0, 100, 200, 1000 and 10000 a table would need 10,001 entries. So the compiler compares instead, and organizes the comparisons as a binary search:
cmpq $199, %rdi
jle LBB7_1 # x <= 199: check 0 and 100
cmpq $200, %rdi # x > 199: check 200, 1000, 10000
je LBB7_8
...
x = 0 -> returns 10 after 2 comparisons
x = 100 -> returns 11 after 3 comparisons
x = 10000 -> returns 14 after 4 comparisons
x = 5000 -> returns -1 after 4 comparisons
Each lookup takes about log₂(number of cases) comparisons. That is not constant time like a table, but much better than a chain of ifs for many cases. The compiler picks the strategy from the density of the cases.
5. Procedures, part 1: the stack, call and ret
5.1 What a procedure call needs
The slides list three mechanisms that every procedure call (function, method, subroutine) must provide:
- Passing control: jump to the beginning of the procedure’s code, and later come back to the point after the call;
- Passing data: procedure arguments in, a return value out;
- Memory management: allocate the procedure’s local variables while it runs, and deallocate them when it returns.
All three are implemented with ordinary machine instructions. The particular choices (which registers hold arguments, who saves what) are a convention called the ABI (Application Binary Interface). It must be agreed upon so that code from different compilers and libraries can call each other. This lecture covers mechanism 1; Lecture 5 covers the rest.
5.2 The x86-64 stack
The stack is a region of ordinary memory used with a last-in, first-out discipline. On x86-64 it grows toward lower addresses, and %rsp holds the address of the top element (the lowest address in use).
pushq Src: fetch the operand, decrement%rspby 8, then write the operand at the new%rsp.popq Dest: read the value at%rsp, increment%rspby 8, then store the value inDest.
06_stack_call_ret.py, PART A (stack addresses shown by their low 16 bits):
pushq $0x11 %rsp=...dff0 stack: [0xdff0]=0x11 [0xdff8]=RET-TO-CALLER
pushq $0x22 %rsp=...dfe8 stack: [0xdfe8]=0x22 [0xdff0]=0x11 [0xdff8]=RET-TO-CALLER
popq %rax %rsp=...dff0 stack: [0xdff0]=0x11 [0xdff8]=RET-TO-CALLER %rax=0x22
popq %rbx %rsp=...dff8 stack: [0xdff8]=RET-TO-CALLER %rbx=0x11
Last in, first out: 0x22 comes back first. And a popped value is still in memory below %rsp. Popping only moves the pointer; the old data stays until it is overwritten. That fact matters for security (Lecture 6) and for debugging, because “stale” stack data looks valid.
5.3 call and ret
call label: push the return address, which is the address of the instruction right after thecall, then jump tolabel.ret: pop an address from the stack and jump to it.
That is the entire mechanism that connects a function to its caller. PART B of the demo traces the slides’ example:
long mult2(long a, long b) { long s = a * b; return s; }
void multstore(long x, long y, long *dest) { long t = mult2(x, y); *dest = t; }
instruction %rip after %rsp %rbx stack (top first)
(entry) 0x400220 ...dff8 0xbbbb [0xdff8]=RET-TO-CALLER
pushq %rbx 0x400224 ...dff0 0xbbbb [0xdff0]=0xbbbb [0xdff8]=RET-TO-CALLER
movq %rdx, %rbx 0x400228 ...dff0 0x8000 [0xdff0]=0xbbbb ...
callq _mult2 0x400210 ...dfe8 0x8000 [0xdfe8]=0x40022c [0xdff0]=0xbbbb ... <- pushed the return address 0x40022c
movq %rsi, %rax 0x400214 ...dfe8 0x8000 ...
imulq %rdi, %rax 0x400218 ...dfe8 0x8000 ...
retq 0x40022c ...dff0 0x8000 [0xdff0]=0xbbbb ... <- popped it into %rip
movq %rax, (%rbx) 0x400230 ...dff0 0x8000 ...
popq %rbx 0x400234 ...dff8 0xbbbb [0xdff8]=RET-TO-CALLER
retq (done) ...e000 0xbbbb (empty)
(Instruction addresses are the simulator’s made-up ones, 4 apart. The real callq is 5 bytes long, and in the slides’ listing the return address is 0x400549 for a call at 0x400544.) Follow %rip and %rsp together. callq both moves %rsp down by 8, storing 0x40022c, the address of the instruction after the call, and changes %rip to mult2’s first instruction. mult2’s retq moves %rsp back up and puts 0x40022c into %rip, so execution continues in multstore exactly after the call. Why a stack? Calls nest: multstore is itself called by someone, and recursion can nest a function inside itself thousands of times. The most recently made call is always the first to return, which is exactly last-in, first-out.
5.4 A first look at register conventions
Why does multstore start with pushq %rbx and end with popq %rbx? It must keep dest (which arrives in %rdx) across the call to mult2. But the convention allows mult2 to overwrite %rdx (a caller-saved register). So multstore parks dest in %rbx, a callee-saved register that mult2 must preserve. Since multstore is itself a callee, it must preserve its caller’s %rbx: it saves the old value on the stack and restores it before returning. The trace shows %rbx = 0xbbbb (the caller’s value) restored at the end. Lecture 5 completes the convention: which registers are which, where arguments 7 and up go, and how local variables live in a stack frame.
6. Is the simulator right?
All traces in this lecture come from x86sim.py. 07_crosscheck.py compares it with the real x86-64 machine code for every function in control.c. The inputs cover conditional moves, global variables, loops with bt/adc, both jump-table styles’ paths and call/ret, over 3,000 test inputs. It runs the simulator twice, on clang’s -Og code and on its different -O1 code. 0 disagreements in both, and the native arm64 build agrees too.
The checks earned their keep while this lecture was being written. They exposed two simulator bugs (details in the code README). Clang’s tab-separated .long directives were silently skipped, so the jump table read as zeros. And once alignment directives worked, falling through ran into alignment padding. The hardware column was right all along; the simulator was fixed until it agreed. When a tool and reality disagree, believe reality and fix the tool.
Summary
- Encoding: an instruction is [prefixes][REX] opcode [ModRM][SIB][displacement][immediate]. REX.W selects 64-bit operands, and REX.R/X/B reach
%r8–%r15. A ~100-line decoder handled all 841movs in/bin/ls. Infer pointers from use:%rsp/%ripalways, base registers usually, scaled indexes never. if/else= test plus conditional goto plus goto. A conditional move computes both sides and selects one, so there is nothing to predict. That is attractive because a misprediction costs ~20 cycles (measured: 10.7× slowdown on random data). It is illegal when a side has side effects or may fault, and unwise when a side is expensive.- Loops are backward jumps. do-while tests at the bottom.
whileadds either a jump to the test (jump to middle, gcc-Og) or an up-front test (guarded do, gcc-O1and clang).for=init; while (test) { body; update; }. A guard vanishes when the first test is provably true. switchover dense cases becomes a jump table: one unsigned bounds check (which also rejects negatives), one table load, one indirect jump. Fall-through is code placement; shared cases share an entry; missing cases point at default. gcc stores 8-byte addresses, clang 4-byte relative offsets. Sparse cases become a decision tree.- The stack grows down;
%rsppoints at the top.push=%rsp -= 8then store;pop= load then%rsp += 8.callpushes the return address (the next instruction) and jumps;retpops it into%rip. Callee-saved registers like%rbxmust be preserved, hence push/pop pairs.
Common pitfalls
- Reading the wrong flags for
cmov/jcc. They use the most recent flag-setting instruction, which may be an arithmetic instruction, not thecmpyou were looking for (as inabsdiff). - Assuming
cmovis always faster. On predictable data a branch is nearly free andcmovpays for both sides. - Expecting gcc’s loop shape from clang (or vice versa). Learn to recognize the backward jump and the guard, whatever their arrangement.
- Treating the jump table’s bounds check as signed.
jaaftercmp $6also sends negative x to default, and that is the point. - Forgetting that
idivuses%rdx:%rax.cqtoandidivoverwrite%rdx, so anything that lived there (often the 3rd argument) must be saved first. - Thinking
poperases. The data stays in memory below%rsp. - Mixing up which address
callpushes. It pushes the address after thecallinstruction, not the address of thecall.
Exercises
-
Goto form. Write the guarded-do goto version of
long fact_while(long n) { long r = 1; while (n > 1) { r *= n; n--; } return r; }.Answer
```c long fact_while_gd(long n) { long r = 1; if (n <= 1) goto done; loop: r *= n; n--; if (n > 1) goto loop; done: return r; } ``` The guard tests the negation of the loop condition once. Inside, the test moves to the bottom. -
Branch or
cmov? Which of these can a compiler implement with a conditional move? (a)return x > 0 ? x : -x;(b)return p ? p->val : -1;(c)if (x < y) count++;wherecountis a global (d)return a < b ? slow_function(a) : 0;Answer
(a) Yes: both sides are cheap, safe, register-only. (b) No: `p->val` with p = NULL would fault. (c) Yes in principle, as `count += (x < y)` with a `set`*cc*, or a load, conditional add and store. But it always performs the store, so compilers may prefer a branch. Either way the visible effect is the same. (d) No: calling a function has side effects and may be expensive, so it must only happen when the condition holds. -
Read a loop. Write C for:
f: movl $0, %eax jmp .L2 .L3: addq %rdi, %rax subq $1, %rdi .L2: testq %rdi, %rdi jg .L3 retAnswer
`long f(long n) { long s = 0; while (n > 0) { s += n; n--; } return s; }`. This is a jump-to-middle `while`: the first `jmp` goes to the test. `jg` after `testq %rdi,%rdi` means n > 0, signed. It computes 1 + 2 + … + n. -
Jump-table bounds. A switch compiles to
cmpq $7, %rdi; ja .Ldef; jmp *.L4(,%rdi,8). Which values of x go to.Ldef? Why onejaand not two compares?Answer
All x < 0 and all x > 7. As unsigned numbers, negative values are ≥ 263, so they are "above 7" too. One unsigned comparison covers both ends of the range [0, 7]. -
Misprediction arithmetic. A loop over 108 elements takes 0.3 s on sorted data and 1.5 s on random data, with a branch that goes each way half the time on random data. Estimate the misprediction penalty, at 3 GHz.
Answer
Extra time 1.2 s, spread over about 0.5 × 108 mispredictions = 24 ns each, or about 72 cycles at 3 GHz. That is much larger than typical (15–25 cycles), which suggests something else (such as cache misses) is also involved. Exactly the kind of sanity check §2.2 does with its own numbers: 5.1 ns ≈ 20–23 cycles. -
Stack bookkeeping.
%rsp= 0x1000 and%rax= 1,%rbx= 2. Afterpushq %rax; pushq %rbx; popq %rcx; pushq $5, what is%rsp, what is%rcx, and what is stored at 0xff8 and 0xff0?Answer
push %rax: %rsp = 0xff8, M[0xff8] = 1. push %rbx: %rsp = 0xff0, M[0xff0] = 2. pop %rcx: %rcx = 2, %rsp = 0xff8. push $5: %rsp = 0xff0, M[0xff0] = 5 (the 2 is overwritten). Final: %rsp = 0xff0, %rcx = 2, M[0xff8] = 1, M[0xff0] = 5. -
Return addresses. In the slides’ listing,
400544: call 400550 <mult2>is followed by400549: mov %rax,(%rbx). What does thecallpush, and what does mult2’sretdo?Answer
The `call` is 5 bytes (opcode e8 + 4-byte displacement), so it pushes 0x400549, the address of the next instruction, decrementing %rsp by 8. Then %rip = 0x400550. mult2's `ret` pops 0x400549 into %rip (incrementing %rsp by 8), so execution resumes at the `mov`. -
Decode. What instruction is
48 8b 07?Answer
REX = 0x48 (W = 1: 64-bit); opcode 8b = MOV reg ← r/m; ModRM 0x07 = 00 000 111: mod = 00 (memory, no displacement), reg = 000 (%rax), r/m = 111 (%rdi). So `movq (%rdi), %rax`, the first instruction of `swap` in Lecture 3's disassembly.
The related lab: L2 (bomblab, released today)
This lecture is the core of bomblab. A typical phase reads your input with a function such as sscanf or read_six_numbers, then loops over it, compares it with values it computes, and calls the explode function on any mismatch. One classic phase is a switch compiled to a jump table. Recognize the indirect jmp *…(,%reg,8), dump the table in gdb with x/8xg, and match its entries to the code blocks. Practical habits: set a breakpoint on the explode function first, so a wrong guess stops in the debugger instead of exploding; read each phase’s code backwards from the explode call to find the condition that must hold; and translate every loop into its goto form before guessing what it computes. These notes contain no bomb solutions (each bomb is unique); Recitations 2 and 3 cover the gdb workflow.
Further reading
- CS:APP3e §3.6.5–3.6.8 (conditional branches and moves, loops, switch) and §3.7.1–3.7.2 (the stack, control transfer); practice problems 3.18–3.31.
- CS:APP3e §5.7 and §5.11 for the processor model behind §2.2: pipelines, out-of-order execution, branch prediction.
- The slides’ optional “activities” for machine control (with solutions) on the course schedule page.
- Compiler Explorer (godbolt.org): compare gcc and clang on
switch_egand thepcountloops at-Og,-O1,-O2.
Preview of Lecture 5: Machine-level programming III, procedures
Today’s procedure call moved control and nothing else. Lecture 5 completes the picture. Arguments go in six registers and the rest on the stack; the return value goes in %rax; and each call gets a stack frame for its local variables, saved registers and outgoing arguments. The caller-saved vs callee-saved division explains §5.4’s push/pop pair. Recursion then works with no extra machinery. After that come arrays: one- and multi-dimensional, the address arithmetic behind a[i][j], and how the D(Rb,Ri,S) operands of Lecture 3 index them.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| instruction encoding | 指令编码 |
| opcode | 操作码 |
| prefix / REX prefix | 前缀 / REX 前缀 |
| ModRM byte / SIB byte | ModRM 字节 / SIB(比例-变址-基址)字节 |
| RIP-relative addressing | RIP 相对寻址 |
| global variable | 全局变量 |
| control flow | 控制流 |
| conditional branch / jump | 条件分支 / 跳转 |
| goto form (of a C construct) | goto 形式 |
| conditional move (cmov) | 条件传送 |
| conditional select (csel, arm64) | 条件选择 |
| side effect | 副作用 |
| pipeline / pipelining | 流水线 |
| out-of-order execution | 乱序执行 |
| speculative execution | 推测执行 |
| branch prediction / branch predictor | 分支预测 / 分支预测器 |
| branch misprediction penalty | 分支预测错误惩罚 |
| loop body / loop test / initializer / update | 循环体 / 循环条件 / 初始化 / 更新 |
| do-while / while / for loop | do-while / while / for 循环 |
| jump to middle | 跳转到中间 |
| guarded do | 带保护的 do(先判断再进入 do-while) |
| bit test (bt) / add with carry (adc) | 位测试 / 带进位加法 |
| switch statement | switch 语句 |
| jump table | 跳转表 |
| indirect jump | 间接跳转 |
| fall-through | 贯穿(穿透到下一个 case) |
| decision tree / binary search | 决策树 / 二分查找 |
| procedure / function call | 过程 / 函数调用 |
| run-time stack | 运行时栈 |
| stack top / push / pop | 栈顶 / 压栈 / 弹栈 |
| last in, first out (LIFO) | 后进先出 |
| return address | 返回地址 |
| call / return (call, ret) | 调用 / 返回 |
| application binary interface (ABI) | 应用程序二进制接口 |
| caller-saved / callee-saved register | 调用者保存 / 被调用者保存寄存器 |
| stack frame | 栈帧 |
| recursion | 递归 |
| position-independent code | 位置无关代码 |