A rebuild of 6.191 Lectures 10 to 15 from zero: RISC-V assembly and the calling convention, the single-cycle processor, the memory hierarchy, caches, and pipelining. The aim is that you can explain each idea in one sentence and then work an exam problem on it by a fixed method. Every section has a picture you can step through, a recipe for the problem type, and worked questions.
If you remember only this section, you can rebuild most of the rest.
There is no magic in machine code. A fixed group of bits says what to do, and other fixed groups say which registers and which constant. Decoding is just slicing.
The two source registers and the destination are in the same bit positions in every format that has them. That is deliberate: the register file can start reading before the processor knows what kind of instruction it is.
Caller and callee are written separately, so they agree in advance on who may overwrite what. Everything about stack frames follows from that agreement.
a0 to a7.ra.t and a registers to survive the call.a0.s registers and sp hold the same values on return as on entry.sp it was given.All state is the PC, 32 registers and memory. Each instruction reads some of that state and writes a little of it. Every processor design is a different way to schedule this same loop.
Programs reuse the same addresses and their neighbours. Keep a small fast copy of recent lines and most accesses never reach slow memory. The bet's payoff is one formula.
average access time = hit time + miss rate × miss penalty
Even a 5% miss rate makes misses the larger share of the time. Cache design is mostly about the miss term.
Overlapping instructions shortens the clock. It works perfectly until one instruction needs something an earlier one has not finished. Then you wait, forward, or guess.
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|
| i1 | IF | DEC | EXE | MEM | WB | ||
| i2 | IF | DEC | EXE | MEM | WB | ||
| i3 | IF | DEC | EXE | MEM | WB |
Read a column to see what every stage is doing in one cycle. Read a row to see one instruction's life. Every pipeline exam question is about filling in this grid correctly.
Six formats cover all of RV32I. The opcode picks the format. The format tells you where the immediate bits are.
| Format | Used by | Why it has this shape | Immediate means |
|---|---|---|---|
| R | add sub and or xor sll srl sra slt sltu | Two source registers and a destination, no constant | none |
| I | addi andi …, loads, jalr | One source, a destination, a 12-bit constant | sign-extended 12 bits, −2048 to 2047 |
| S | sw sh sb | Two sources and no destination, so the constant takes over the rd slot | sign-extended 12-bit offset |
| B | beq bne blt bge bltu bgeu | Same as S, but the offset is in units of 2 bytes | signed offset from this instruction's PC, bit 0 is always 0 |
| U | lui auipc | A destination and a 20-bit constant | the upper 20 bits, lower 12 are zero |
| J | jal | A destination and a long jump offset | signed 21-bit offset from this PC, bit 0 is always 0 |
Two rules explain the odd bit orders in B and J. Bit 31 is always the sign bit of the immediate, so sign extension never needs a mux. And as many immediate bits as possible stay in the same instruction positions across formats.
Your Lab 4 decoder builds every immediate with one concatenation and one extension. This is the hardware meaning of the format table.
rd, rs1, rs2 as plain 5-bit numbers. Use funct3 and, for R, funct7 to pick the operation.Recall
0x00C58533.Binary: 0000000 01100 01011 000 01010 0110011. Opcode 0110011 is R-type. funct7 = 0, rs2 = 12, rs1 = 11, funct3 = 000, rd = 10. That is add x10, x11, x12, or add a0, a1, a2.
sw x5, 8(x2).S-type, opcode 0100011, funct3 010. imm = 8 = 000000001000. imm[11:5] = 0000000, imm[4:0] = 01000. rs2 = 5 = 00101, rs1 = 2 = 00010. Bits: 0000000 00101 00010 010 01000 0100011 = 0x00512423.
beq at address 0x40 must jump to 0x38. What are the immediate bits?Offset = 0x38 − 0x40 = −8. In 13 bits: 1 1111 1111 1000. imm[12] = 1, imm[11] = 1, imm[10:5] = 111111, imm[4:1] = 1100. The instruction stores 1 111111 in bits 31:25 and 1100 1 in bits 11:7. Bit 0 is not stored.
addi can add, and how do you load 0x12345678?2047, because the 12-bit immediate is signed. Use two instructions: lui x5, 0x12345 sets the upper 20 bits, then addi x5, x5, 0x678. If the low 12 bits are 0x800 or more, addi will subtract, so add 1 to the lui value to compensate.
An address needs 32 bits and there are only 12 or 20 to spare. Branch targets are almost always nearby, so a small signed offset from the PC reaches them. It also makes code position-independent.
beq reach? A jal?beq: a 13-bit signed offset, −4096 to +4094 bytes. jal: a 21-bit signed offset, about ±1 MB.
A compiler does three mechanical things: it puts variables in registers, turns each expression into a few instructions, and turns every control structure into labels and branches.
| C | Assembly shape | The trick |
|---|---|---|
| if (a < b) { T } | bge a, b, skip T skip: | Branch on the opposite condition to jump over the body |
| if (c) { T } else { E } | b!c else T j end else: E end: | The j end after T is the line people forget |
| while (c) { B } | loop: b!c done B j loop done: | Test at the top, jump back at the bottom |
| for (i=0; i<n; i++) { B } | li i, 0 loop: bge i, n, done B addi i, i, 1 j loop done: | A for is a while with an init and a step |
| a[i] (int array) | slli t, i, 2 add t, a, t lw v, 0(t) | Address = base + 4 × index, because an int is 4 bytes |
| *p, p->f | lw v, off(p) | A pointer is an address in a register. A field is a fixed offset |
The flow below runs a small loop one instruction at a time. Note how the three lines for a[i] turn an index into an address.
In that loop s0 and s1 are pointers that step through the input and output arrays, and s2 counts down. They are in s registers because they must survive the call to gcd. That choice is the calling convention at work, which is the next section.
goto: one label per loop top, loop exit and else.Recall
if (x == 0) y = 1; else y = 2; with x in a0, y in a1.bnez a0, else · li a1, 1 · j end · else: li a1, 2 · end:. The branch tests the opposite condition and the j end keeps the then-branch from falling into the else.
a is an int array at address in a0, i is in a1. Write a[i] = a[i] + 1.slli t0, a1, 2 · add t0, a0, t0 · lw t1, 0(t0) · addi t1, t1, 1 · sw t1, 0(t0).
for (i=0;i<3;i++) s += i; written as init, test at top, body, step, jump?Init: 1. Each of 3 iterations: test, body, step, jump = 4, total 12. Final failing test: 1. Total 14.
lw t0, 0(a0) and mv t0, a0?mv copies the register, so t0 holds the address. lw goes to memory at that address and brings back the word stored there. It is the difference between p and *p.
li called a pseudo-instruction?The hardware has no li. The assembler expands it to addi rd, x0, imm for small constants or lui plus addi for large ones. mv, j, ret, beqz and nop are also pseudo-instructions.
Before a call, save what you still need and the callee may destroy. Inside a function, restore what you changed and promised to keep. The stack is where both kinds of saving happen.
| Registers | Role | Who must save it if they care | Survives a call? |
|---|---|---|---|
| a0 – a7 | Arguments. a0 (and a1) carry the return value | Caller | No |
| t0 – t6 | Temporaries | Caller | No |
| ra | Return address, written by jal | Caller. In practice a function that makes a call saves ra in its own prologue | No |
| s0 – s11 | Saved values | Callee, if it writes them | Yes |
| sp | Stack pointer. The stack grows toward lower addresses | Callee restores it | Yes |
A function that calls nothing and uses only a and t registers needs no stack frame at all. A function that makes a call must save ra, because its own jal will overwrite it. The flow shows exactly that moment.
ra goes on the stack.s register and add that s register to the save list. The alternative is to keep it in a t or a register and save it around each call.sp by 4 × the number of saved words, then one sw per word.lw per word, increment sp by the same amount, ret.ret restores the frame, including early returns.Recall
t0, calls g, then reads t0. What is the bug?t0 is caller-saved, so g may overwrite it. Either save t0 on the stack around the call or keep the value in an s register that the function saves in its prologue.
s0 and s1.Prologue: addi sp, sp, -12 · sw ra, 8(sp) · sw s0, 4(sp) · sw s1, 0(sp). Epilogue: lw s1, 0(sp) · lw s0, 4(sp) · lw ra, 8(sp) · addi sp, sp, 12 · ret.
fact(n) saves ra and s0. How much stack does fact(5) use at its deepest, if the base case n == 0 also builds a frame?Calls are active for n = 5, 4, 3, 2, 1, 0: six frames of 8 bytes each, 48 bytes.
jal ra, f and ret actually do?jal ra, f writes PC + 4 into ra and sets PC to f. ret is jalr x0, 0(ra): set PC to ra and discard the link value.
ra?Nothing inside it executes a jal, so ra still holds the caller's return address when it reaches ret.
a0, t3, s2, sp, ra can the caller rely on?a0 holds the return value. s2 and sp are unchanged. t3 and ra may hold anything.
One clock cycle does the whole loop for one instruction. The datapath contains every component any instruction needs, and control signals pick which parts matter this cycle.
One instruction of each kind follows. The highlighted boxes are the ones whose output is actually used.
Control is a table lookup on the instruction type. This table is worth being able to reproduce from memory.
| Type | Example | ALU second input | Writes a register? | Value written | Data memory | Next PC |
|---|---|---|---|---|---|---|
| OP | add | rs2 value | yes | ALU result | unused | pc + 4 |
| OPIMM | addi | immediate | yes | ALU result | unused | pc + 4 |
| LOAD | lw | immediate (address = rs1 + imm) | yes | memory data | read | pc + 4 |
| STORE | sw | immediate (address = rs1 + imm) | no | none | write rs2 value | pc + 4 |
| BRANCH | beq | rs2 value, compared | no | none | unused | taken ? pc + imm : pc + 4 |
| JAL | jal | unused | yes | pc + 4 | unused | pc + imm |
| JALR | jalr | immediate | yes | pc + 4 | unused | (rs1 + imm) & ~1 |
| LUI | lui | unused | yes | immediate | unused | pc + 4 |
Your Lab 4 processor is this loop written as one rule. Each line is one box of the datapath.
The clock period must fit the slowest instruction. A load uses every component in series, so it sets the clock for everything. The delays below are made-up round numbers to show the shape.
An add could finish in 60% of the cycle but waits for the clock anyway. That wasted time is what pipelining recovers.
Recall
The load path uses everything: 200 + 100 + 150 + 250 + 50 = 750 ps. An add needs 200 + 100 + 150 + 50 = 500 ps but the clock must be 750 ps.
The ones that should not write: stores and branches. They would write some value into the register named by bits 11:7, which for those formats are immediate bits. If those bits are 0 it is harmless, since x0 ignores writes.
lw x5, 8(x6) with x6 = 0x100, what does each component produce?Register file reads x6 = 0x100. ALU adds the immediate: 0x108. Data memory reads the word at 0x108. That word is written to x5. Next PC is PC + 4.
Reads are combinational and see the old contents. The write takes effect at the clock edge that ends the cycle. So addi x1, x1, 1 reads the old x1 and writes the new one.
OPIMM, LOAD, STORE and JALR. They all compute rs1 + imm or rs1 op imm.
The PC, the 32 registers (with x0 fixed at 0), and memory. Everything else in the single-cycle datapath is combinational.
No single memory technology is fast, large and cheap. Stack several, smallest and fastest nearest the processor, and rely on locality to make the stack behave like the fast one with the capacity of the big one.
| Technology | Speed | Capacity per cost | Keeps data without power? | Used as |
|---|---|---|---|---|
| Flip-flops | fastest | worst | no | Registers |
| SRAM | about 1 ns | poor | no | Caches |
| DRAM | about 100 ns | good | no, and needs refresh | Main memory |
| Flash | about 100 µs | very good | yes | Storage |
| Hard disk | about 10 ms | best | yes | Bulk storage |
If an address was used recently, it will probably be used again soon. Loop counters, the instructions of a loop body and the top of the stack are examples. This is why keeping recent data pays.
If an address was used, nearby addresses will probably be used soon. Arrays and straight-line code are examples. This is why a cache fetches a whole line, not one word.
The line is straight because every extra percent of misses costs the same: one hundredth of the penalty. The marked point is the current slider setting.
AMAT = hit time + miss rate × miss penalty before touching numbers.AMAT = t1 + m1 × (t2 + m2 × penalty2).Recall
2 + 0.04 × 50 = 4 cycles.
L2's AMAT = 8 + 0.2 × 100 = 28. Overall = 1 + 0.1 × 28 = 3.8 cycles.
A: 1 + 0.06 × 40 = 3.4. B: 2 + 0.02 × 40 = 2.8. B wins even though every hit is twice as slow.
1 + m × 50 ≤ 3, so m ≤ 0.04. At most 4%.
Line size exploits spatial locality. Keeping recent lines, and evicting the least recently used one, exploits temporal locality.
The address itself says where to look. The low bits pick a byte within a line, the middle bits pick a set, and the remaining high bits are a tag stored with the line to prove it is the right one.
| Organisation | Sets | Lines a given address may live in | Comparators | Weakness |
|---|---|---|---|---|
| Direct-mapped | number of lines | 1 | 1 | Two hot lines with the same index evict each other |
| N-way set-associative | lines ÷ N | N | N | Slower hit, needs a replacement policy |
| Fully associative | 1 | any | one per line | Expensive, only practical when small |
Follow a short trace on a tiny direct-mapped cache with 4 sets and 8-byte lines.
The first access ever to that line. No cache of any size avoids it. Longer lines reduce it, because one miss brings in neighbours.
The program uses more lines than the cache holds, so even a fully associative cache of the same size would have dropped this line. Fix: a larger cache.
The cache had room overall, but too many lines map to this set. A fully associative cache of the same size would have hit. Fix: more ways.
The simulator below classifies each miss by that definition. Change the geometry and watch conflict misses appear and disappear.
| Decision | Options | What your Lab 5 cache does |
|---|---|---|
| Write hit | Write-through: update memory now. Write-back: mark the line dirty, update memory on eviction | Write-back with a dirty status |
| Write miss | Allocate: fetch the line, then write it in the cache. No-allocate: write memory only | Allocate |
| Which line to evict | Least recently used, first in first out, random | LRU, one bit per set for two ways |
The Lab 6 page has a trace of your own cache's state machine doing a dirty eviction, and the helper functions that slice the address.
Recall
Lines = 4096 ÷ 16 = 256, so 8 index bits. Offset = log2(16) = 4. Tag = 32 − 8 − 4 = 20.
Sets = 256 ÷ 4 = 64, so 6 index bits. Offset stays 4. Tag grows to 22 bits. Capacity is unchanged.
Per line: 128 data + 20 tag + 2 status = 150 bits. Times 256 lines = 38,400 bits. The data alone is 32,768 bits.
0x0, 0x4, 0x10, 0x0, 0x10.Index = address bits [3:2], tag = bits above. 0x0: set 0 tag 0, miss. 0x4: set 1 tag 0, miss. 0x10: set 0 tag 1, miss, evicts tag 0. 0x0: set 0 tag 0, miss, evicts tag 1. 0x10: miss again. Zero hits. The last two are conflict misses because three other sets had room.
Index = bit 2. 0x0: set 0 tag 0, miss. 0x4: set 1, miss. 0x10: set 0 tag 2, miss, goes in the second way. 0x0: hit. 0x10: hit. Two hits out of five. Associativity removed the conflicts.
int array once, in order, through a cache with 16-byte lines. What is the miss rate?Each line holds 4 ints. The first access to each line misses and the next three hit. Miss rate 25%, all compulsory.
At power-up the tag bits are arbitrary and could match a real address by chance. The valid bit says the tag and data mean something.
Compulsory misses fall for sequential access, since each miss brings in more neighbours. There are half as many lines, so conflict and capacity misses can rise. The miss penalty also grows.
Pipelining shortens the clock by splitting the work into stages. It is correct only if each instruction sees the same register and memory values it would have seen running alone. Hazards are the cases where it would not, and each has a fixed fix.
| Stage | Work | State it writes |
|---|---|---|
| IF | Read the instruction at the PC, choose the next PC | PC |
| DEC | Decode, read the register file | nothing permanent |
| EXE | ALU, branch decision, memory address | nothing permanent |
| MEM | Read or write data memory | memory, for stores |
| WB | Write the result to the register file | a register |
An instruction in DEC needs a register that an earlier instruction, still in the pipeline, has not written yet.
Fix: stall in DEC until it is written, or bypass the value from the stage where it already exists.
IF must choose the next PC before the branch ahead of it has been decided.
Fix: guess PC + 4, and annul the wrongly fetched instructions when a branch turns out taken.
Each stall and each annulled instruction is one cycle with no instruction finishing.
CPI = 1 + average stall cycles per instruction + average annulled instructions per instruction.
The generator builds the diagram for a few sequences under the rules you choose. Change one setting at a time and predict the grid before you look.
The consumer is in DEC. The table gives the stall count for a five-stage pipeline where register values are needed in DEC, by how far ahead the producer is.
| Producer | Rule | 1 instruction ahead | 2 ahead | 3 ahead |
|---|---|---|---|---|
| Any, no bypassing | Wait until the producer has finished WB | 3 | 2 | 1 |
| ALU result, full bypassing | Value exists once the producer is in EXE | 0 | 0 | 0 |
| Load, full bypassing, data from MEM | Value exists once the load is in MEM | 1 | 0 | 0 |
| Load, full bypassing, data from WB | Value exists once the load is in WB | 2 | 1 | 0 |
A taken branch costs one annulled instruction per stage between IF and the stage that resolves it: 2 if resolved in EXE, 1 if resolved in DEC. Your Lab 6 processor has four stages, bypasses into decode, and loses 1 cycle on load-use and 1 on a taken branch. The Lab 6 page shows why from the code.
Recall
addi x1,x0,5 then add x2,x1,x1, five stages, no bypassing. In which cycle does the add finish WB?addi: IF 1, DEC 2, EXE 3, MEM 4, WB 5. add: IF 2, DEC 3. It must wait until addi has written, so it stays in DEC for cycles 3, 4, 5 and leaves DEC in cycle 6. EXE 7, MEM 8, WB 9. Three stall cycles.
When add is in DEC in cycle 3, addi is in EXE and its ALU output is bypassed. No stall. add finishes WB in cycle 6.
lw x1,0(x2) then add x3,x1,x1, full bypassing, load data available from MEM.lw: IF 1, DEC 2, EXE 3, MEM 4, WB 5. add is in DEC in cycle 3 while the load is in EXE: no data yet, stall. In cycle 4 the load is in MEM and its data is bypassed. One stall. add: IF 2, DEC 3, DEC 4, EXE 5, MEM 6, WB 7.
1 + 0.20 × 0.5 × 1 + 0.15 × 2 = 1 + 0.10 + 0.30 = 1.40.
Single-cycle time per instruction: 800 ps. Pipelined: 1.4 × 200 = 280 ps. Speed-up 800 ÷ 280 ≈ 2.86, not 5.
They are still in IF and DEC, which write no registers and no memory. Replacing them with bubbles leaves no trace.
x5. Which value does the bypass logic pick?The one from the nearer stage, because that instruction is younger and its write is the one the program expects to be visible.
The slowest stage plus register overhead: 300 + 20 = 320 ps. Unbalanced stages waste time in the short ones.
No. Latency is stages × clock period, which is at least the single-cycle time. Pipelining raises throughput: more instructions finish per second.
The comparison must now fit in DEC after the register read and the bypass muxes, which can lengthen the clock. A branch that depends on the instruction just ahead may also need a stall it did not need before.
if, while, for and an array access into assembly.