本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
11The Processor: Datapath, Control and Pipelining
A laundry has a washer, a dryer and a folding table, each taking half an hour. Done one at a time, four loads take six hours. But as soon as the first load leaves the washer, the second can go in: with the three machines busy at once, the four loads are done in three hours, and each extra load adds only half an hour. A processor does the same with instructions. Here are five instructions going through a five-step processor, one row per instruction and one column per clock cycle:
$ python timing_diagram.py independent.S
1 2 3 4 5 6 7 8 9
addi t0, zero, 1 F D X M W
addi t1, zero, 2 F D X M W
addi t2, zero, 3 F D X M W
addi a0, zero, 0 F D X M W
jalr zero, 0(ra) F D X M W
5 instructions, 9 cycles, 0 stall cycles
No instruction finishes sooner than before; more of them finish per second. This chapter builds the processor that runs the instructions of Chapter 10, first as one large circuit that does a whole instruction in one clock cycle, then cut into five stages that work at once, and measures, on real programs run by rv, what the overlap costs when instructions depend on one another.
You already know
Book 3: a multiplexer selects one of its inputs by a control value; a decoder turns a number into one active line; an ALU computes an arithmetic or logic function chosen by its control inputs; every gate has a propagation delay. A register holds its value until the clock edge; a clock paces a synchronous circuit; a finite-state machine changes state on each edge. A processor is a datapath, which moves and transforms data, and a control unit, which drives it. Chapter 10: the RV32I formats, the immediates, and branch offsets.
11.1 A single-cycle datapath
Definition 11.1 (Single-cycle processor)
A single-cycle processor executes each instruction completely in one clock cycle: in that cycle the instruction is fetched, its registers read, the ALU used, memory accessed and the result written back, and the next clock edge stores the new program counter and the result.
Its datapath, for a subset of RV32I (the register and immediate arithmetic, lw, sw and the six conditional branches), needs these parts:
- the program counter (PC), a 32-bit register, and an instruction memory read at the PC;
- the register file, with two read ports (
rs1,rs2) and one write port (rd); - the immediate generator, which gathers the scattered immediate bits of the I, S and B formats and sign-extends them;
- the ALU, and a data memory read or written at the address the ALU computes;
- two adders for the next PC, and ;
- multiplexers wherever two sources compete for one input.
datapath.py. Data flows left to right; the write-back and the next PC return to the left. The three multiplexers choose the ALU’s second input (register or immediate), the value written back (ALU result or loaded word) and the next PC ( or the branch target). The control signals, in colour, come from the control unit; a comparator beside the ALU (not drawn) decides taken.The model datapath.py computes, for one instruction word and the current state of an rv machine, what this circuit does in one clock cycle, without changing the machine; the caller then lets rv execute the instruction and compares the two.
def cycle(m, pc, word):
"""One clock cycle of the datapath, reading machine m without changing it."""
c = CONTROL.get(word & 0x7F)
if c is None or (c.name in ("lw", "sw") and word >> 12 & 7 != 2):
return None # outside the subset: lb, sh, ...
if c.name == "R-type" and word >> 25 == 1:
return None # mul, div: the M extension
rd, rs1, rs2 = word >> 7 & 31, word >> 15 & 31, word >> 20 & 31
a, b_reg = m.x[rs1], m.x[rs2] # the register file: two reads
imm = imm_gen(word)
b = imm & MASK if c.alu_src else b_reg # the ALUSrc multiplexer
if c.branch:
taken = BRANCH[word >> 12 & 7](a, b_reg)
return Effect(None, None, None, None, (pc + imm) & MASK if taken else pc + 4)
result = ALU[alu_control(c, word)](a, b) & MASK
mem_value = m.load(result, 4) if c.mem_read else (b_reg if c.mem_write else None)
value = mem_value if c.mem_to_reg else result # the MemtoReg multiplexer
write = c.reg_write and rd != 0
return Effect(rd if write else None, value if write else None,
result if c.mem_read or c.mem_write else None, mem_value, pc + 4)
def imm_gen(word):
"""The immediate generator: gather the scattered bits, then sign-extend."""
op = word & 0x7F
if op in (0b0010011, 0b0000011): # I
return sext(word >> 20, 12)
if op == 0b0100011: # S
return sext((word >> 25) << 5 | (word >> 7) & 0x1F, 12)
if op == 0b1100011: # B
return sext((word >> 31) << 12 | (word >> 7 & 1) << 11
| (word >> 25 & 0x3F) << 5 | (word >> 8 & 0xF) << 1, 13)
return 0
Each line of cycle is a wire or a box of the figure. Tracing four instructions is a matter of following the values: add t2, t0, t1 reads two registers, the ALU adds, the multiplexer passes the ALU result to the write port. sw t2, 12(sp) reads sp and t2, the ALU adds 12 to sp as an address, and the data memory stores t2 there; nothing is written to a register. lw t3, 12(sp) computes the same address, reads memory, and writes the loaded word, through the second multiplexer, to t3. beq t2, t3, same compares the two registers; when they are equal, the PC multiplexer takes .
11.2 Control
Definition 11.2 (Control signal)
A control signal is a wire from the control unit that selects a multiplexer’s input, enables a write, or chooses an ALU operation. In a single-cycle processor the control unit is a combinational circuit whose input is the instruction’s opcode (with funct3 and funct7 for the ALU).
Method 11.3 (Deriving the control table)
For each class of instruction, follow the path its data must take through the datapath, then set each signal:
- RegWrite is 1 when the instruction has a destination register, else 0 (stores, branches);
- ALUSrc is 1 when the ALU’s second operand is the immediate (I-type, loads, stores), 0 for a register;
- MemRead and MemWrite are 1 only for loads and stores respectively;
- MemtoReg is 1 when the written value comes from memory (loads); when RegWrite is 0 it does not matter;
- Branch is 1 for the conditional branches; the PC multiplexer takes the target when Branch is 1 and the comparison holds;
- the ALU operation is “add” for addresses, “compare” for branches, and read from the funct fields otherwise.
A signal that does not matter for an instruction may be set either way; setting it to 0 makes the table simpler, never a signal that writes something.
CONTROL = { # opcode -> signals: the control table
0b0110011: Control("R-type", 0, 0, 1, 0, 0, 0, "funct"),
0b0010011: Control("I-type", 1, 0, 1, 0, 0, 0, "funct"),
0b0000011: Control("lw", 1, 1, 1, 1, 0, 0, "add"),
0b0100011: Control("sw", 1, 0, 0, 0, 1, 0, "add"),
0b1100011: Control("branch", 0, 0, 0, 0, 0, 1, "compare"),
}
alu_control then picks the operation from funct3, and funct7 separates add from sub and srl from sra; an addi has no funct7, its bit 30 being part of the immediate, which is why subi does not exist. The model’s check runs four.S and compares every instruction it covers with rv:
$ python datapath.py four.S
instruction decoded ALUSrc MemtoReg RegWrite MemRead MemWrite Branch
addi sp, sp, -16 I-type 1 0 1 0 0 0 agrees
addi t0, zero, 7 I-type 1 0 1 0 0 0 agrees
addi t1, zero, 5 I-type 1 0 1 0 0 0 agrees
add t2, t0, t1 R-type 0 0 1 0 0 0 agrees
sw t2, 12(sp) sw 1 0 0 0 1 0 agrees
lw t3, 12(sp) lw 1 1 1 1 0 0 agrees
beq t2, t3, same branch 0 0 0 0 0 1 agrees
addi a0, zero, 0 I-type 1 0 1 0 0 0 agrees
addi sp, sp, 16 I-type 1 0 1 0 0 0 agrees
jalr zero, 0(ra) outside the model's subset
9 instructions agree with rv, 1 outside the subset
rv.The chapter’s test runs the same check on every program of the chapter: the datapath and rv agree on every instruction of the subset. The ret that ends four.S is a jalr, which needs one more path, into the register file: Exercise 11.12 adds it.
The trouble with this design is its clock. The cycle must be long enough for the slowest instruction, the load, which goes through instruction memory, register file, ALU, data memory and back to the register file. Suppose those take 200, 100, 200, 200 and 100 ps: the clock period is at least 800 ps, and an add, which does not need data memory, waits for nothing while its 600 ps of work end.
11.3 The five-stage pipeline
Definition 11.4 (Instruction pipeline, pipeline stage, pipeline register)
An instruction pipeline splits the execution of an instruction into steps, the pipeline stages, each taking one clock cycle, so that several instructions are in progress at once, one per stage. Between two stages a pipeline register holds what the next stage needs: the values computed so far and the control signals of the instruction.
The classic RISC pipeline has five stages, cut where the single-cycle datapath has its large blocks: IF (fetch from instruction memory), ID (decode and read the registers), EX (the ALU), MEM (data memory) and WB (write the register). Its pipeline registers are named after the stages they separate: IF/ID, ID/EX, EX/MEM, MEM/WB. With the delays above, the clock period becomes that of the slowest stage, 200 ps.
Definition 11.5 (Latency, throughput)
The latency of an instruction is the time from its fetch to its completion. The throughput of a processor is the number of instructions it completes per unit of time, or per cycle.
The pipeline does not lower the latency: in five stages of 200 ps an instruction takes 1000 ps, more than the 800 ps of the single cycle. It raises the throughput: in the steady state, one instruction completes every cycle.
Proposition 11.6 (Ideal gain of a pipeline)
On a -stage pipeline with no hazard, instructions take cycles. With a cycle times shorter than the unpipelined one, the time of the unpipelined machine divided by that of the pipeline is
which tends to as grows.
Proof. The first instruction leaves the last stage at the end of cycle . Each later one enters the pipeline one cycle after the one before it and so leaves one cycle after it: the -th leaves at the end of cycle . The unpipelined machine takes cycles of length (in units of the short cycle), so . Dividing, . ∎
The hook’s five instructions took cycles. In practice the stages are never perfectly balanced and the pipeline registers add their own delay, so the gain stays below even before the next section’s hazards.
The chapter’s timing model pipeline.py does not simulate wires: it takes the stream of instructions that rv executed (one Step per instruction, with the registers it read and wrote) and computes the cycle in which each enters each stage, with these rules: an instruction enters ID when the one before it leaves ID, and enters EX when its operands are ready.
def schedule(steps, forwarding=True, predictor=None):
"""The cycle of every stage of every instruction, the first IF in cycle 1."""
predictor = predictor or NotTaken()
t = Timing()
ready = {} # register -> earliest EX of a reader
next_fetch, prev_ex = 1, 1
for s in steps:
f = next_fetch
d = max(f + 1, prev_ex) # ID frees when the one ahead enters EX
need = max([ready.get(r, 0) for r in s.srcs], default=0)
x = max(d + 1, need) # the hazard check, made in ID
if t.execute:
t.flushed += d - prev_ex # fetched late: a branch or a jump
t.stalls += x - (d + 1) # held in ID until operands are ready
t.fetch.append(f)
t.decode.append(d)
t.execute.append(x)
if s.rd is not None:
if not forwarding: # read in ID once WB has written it
ready[s.rd] = x + NO_FORWARD_DELAY
else:
ready[s.rd] = x + (LOAD_DELAY if s.kind == "load" else ALU_DELAY)
next_fetch = d # the next is fetched as this enters ID
11.4 Hazards
Definition 11.7 (Hazard: structural, data, control)
A hazard is a situation in which the next instruction cannot enter its next stage in the next cycle. It is structural when two instructions need the same hardware in the same cycle; a data hazard when an instruction needs a value that an earlier instruction has not yet written; a control hazard when the processor does not yet know which instruction comes next, after a branch or a jump.
Separate instruction and data memories remove the structural hazard between IF and MEM, and the register file is written in the first half of a cycle and read in the second, so WB and ID can share a cycle. Data hazards are everywhere: add t0, a1, a2 followed by sub t1, t0, a2 reads t0 in ID while add is still in EX. Without any help, sub must wait in ID until add has written t0 in WB, two cycles later.
Definition 11.8 (Stall, bubble, load-use hazard)
A stall holds an instruction in its stage for a cycle; the stage after it receives a bubble, an empty slot that does nothing. A load-use hazard is a data hazard in which an instruction uses the register that the instruction just before it loads from memory.
Definition 11.9 (Forwarding)
Forwarding (or bypassing) sends a result to the ALU’s input directly from a pipeline register, EX/MEM or MEM/WB, as soon as it has been computed, instead of waiting for it to be written to the register file and read again.
The value add computes is in EX/MEM at the end of its EX cycle, just in time for sub’s EX in the next one. The forwarding unit compares the source registers of the instruction in EX with the destinations of the two instructions ahead of it:
def forward(rs, ex_mem, mem_wb, check_x0=True):
"""ex_mem, mem_wb: (reg_write, rd) of the instructions one and two ahead."""
for source, (reg_write, rd) in (("EX/MEM", ex_mem), ("MEM/WB", mem_wb)):
if reg_write and rd == rs and (rd != 0 or not check_x0):
return source # the nearer one wins: it is the newer value
return "register file"
$ python forwarding.py forwarding.S
addi a1, zero, 7 zero <- register file
addi a2, zero, 5 zero <- register file
add t0, a1, a2 a1 <- MEM/WB, a2 <- EX/MEM
sub t1, t0, a2 t0 <- EX/MEM, a2 <- MEM/WB
and t2, t0, t1 t0 <- MEM/WB, t1 <- EX/MEM
or t3, t0, t2 t0 <- register file, t2 <- EX/MEM
jalr zero, 0(ra) ra <- register file
Forwarding cannot help a load: its value comes out of data memory at the end of MEM, one cycle later than an ALU result. The model encodes these delays in three numbers: an instruction may be in EX one cycle after an ALU producer, two after a load, and three after any producer when there is no forwarding (it reads in ID, during the producer’s WB).
Proposition 11.10 (One stall per load-use)
With forwarding from EX/MEM and MEM/WB, an instruction that uses the result of a load immediately before it is stalled exactly one cycle, and an instruction that uses it two or more instructions later is not stalled by it.
The proof is Exercise 11.8. Here are both effects on load_use.S:
$ python timing_diagram.py load_use.S
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
auipc a0, 0xfff0 F D X M W
addi a0, a0, 0 F D X M W
lw t0, 0(a0) F D X M W
add t1, t0, t0 F D * X M W
lw t2, 4(a0) F . D X M W
add t3, t1, t2 F D * X M W
sw t3, 8(a0) F . D X M W
addi a0, zero, 0 F D X M W
jalr zero, 0(ra) F D X M W
$ python timing_diagram.py load_use.S --no-forwarding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
auipc a0, 0xfff0 F D X M W
addi a0, a0, 0 F D * * X M W
lw t0, 0(a0) F . . D * * X M W
add t1, t0, t0 F . . D * * X M W
lw t2, 4(a0) F . . D X M W
add t3, t1, t2 F D * * X M W
sw t3, 8(a0) F . . D * * X M W
addi a0, zero, 0 F . . D X M W
jalr zero, 0(ra) F D X M W
9 instructions, 23 cycles, 10 stall cycles
add to the sw). Each stall slides every later instruction one column to the right.The second half of the model handles control hazards. A conditional branch is resolved in EX, so when the processor guesses wrong about it, the two instructions fetched after it are thrown away and fetching restarts after its EX: two cycles lost. A jal knows its target in ID (it is ), one cycle lost; a jalr needs a register, so EX, two cycles.
if s.kind == "branch":
guess = predictor.predict(s.pc)
predictor.update(s.pc, s.branch_taken)
if guess != s.branch_taken: # resolved in EX: fetch again after it
t.mispredicted += 1
next_fetch = x + 1
elif s.kind == "jump":
jal = s.text.split()[0] == "jal" # jal: target known in ID; jalr: EX
next_fetch = d + 1 if jal else x + 1
prev_ex = x
return t
11.5 Branch prediction
Definition 11.11 (Branch prediction, predictor, misprediction penalty)
Branch prediction lets the processor fetch past a conditional branch before it is resolved, along the direction a branch predictor guesses. When the guess is wrong, the instructions fetched since are discarded (flushed); the cycles lost are the misprediction penalty, here 2.
The simplest predictor says “not taken” for every branch, and is right whenever the branch falls through. Loops defeat it: the branch that closes a loop is taken at every turn but the last. A dynamic predictor remembers what each branch did. A one-bit predictor predicts that a branch does what it did last time; it is wrong twice per run of a loop, at the last turn and again at the first turn of the next run.
Definition 11.12 (Saturating counter)
A two-bit saturating counter is a number from 0 to 3, incremented when the branch is taken and decremented when it is not, without going past 0 or 3; it predicts “taken” when it is 2 or 3.
class TwoBit:
"""A two-bit saturating counter per branch: 0, 1 predict not taken; 2, 3 taken."""
name = "two-bit"
def __init__(self, start=1):
self.start = start
self.counter = {}
def predict(self, pc):
return self.counter.get(pc, self.start) >= 2
def update(self, pc, taken):
c = self.counter.get(pc, self.start)
self.counter[pc] = min(c + 1, 3) if taken else max(c - 1, 0)
Proposition 11.13 (Two bits for a loop)
Let the branch that closes an inner loop of turns be taken times and then not taken, at each execution of the inner loop. Once its counter has reached 3 during one execution, a two-bit counter mispredicts it exactly once per later execution of the inner loop; a one-bit predictor mispredicts it twice per execution.
The proof is Exercise 11.11. On the branch traces of three programs, the three predictors give:
$ python branches.py
program branches taken mispredicted: not taken one-bit two-bit
loop_sum.S 32 31 31 2 2
bubble_sort.S 272 176 176 86 60
collatz.S 942 186 186 315 161
On loop_sum.S the two-bit counter is wrong twice: once at the first turn, while it warms up, once at the exit. collatz.S is harder: its branch on the parity of follows the data, and there a one-bit predictor does worse than predicting “not taken” at all, because an odd is always followed by an even one: each taken outcome comes alone and costs the one-bit predictor two mistakes, the miss and the miss after it, where “not taken” misses once. Real processors keep thousands of counters, indexed by the address and by the outcomes of the last branches, and predict far better than these three; the principle is the same.
11.6 The performance equation
Definition 11.14 (Cycles per instruction, performance equation)
The cycles per instruction (CPI) of a run is its number of cycles divided by its number of instructions. The performance equation gives the time of a run:
Each factor belongs to someone. The number of instructions depends on the program, the compiler and the instruction set; the CPI on the pipeline’s handling of hazards and on how often the program triggers them; the cycle time on the circuit. A single-cycle processor has a CPI of 1 and a long cycle; the pipeline has a short cycle and a CPI above 1, which forwarding and prediction bring closer to 1. In the model, for instructions,
an identity the chapter’s test checks on every program and every configuration.
$ python cpi_table.py
program instructions no forwarding forwarding forwarding + two-bit
loop_sum.S 136 2.456 1.721 1.294
bubble_sort.S 964 1.961 1.512 1.272
collatz.S 3342 1.790 1.338 1.323
collatz.S, whose branches follow the data.
In practice — Pipelines today
Processors in desktops and phones have much longer pipelines than five stages, issue several instructions per cycle, and execute them out of order when their operands are ready; the hazards of this chapter remain, handled by more forwarding paths, deeper buffers and better predictors. The performance equation still decides: a longer pipeline shortens the cycle but raises the misprediction penalty. When code is slow on a modern machine, the usual suspects are mispredicted branches on unpredictable data and loads that miss in the caches, the subject of Chapter 12.
11.7 Exercises
Exercise 11.1 ★
How many cycles does the five-stage pipeline take for 8 independent instructions? For ? What fraction of the stage slots are used in the first case?
Solution
Solution of Exercise 11.1.
By Proposition 11.6, cycles: 12 for 8 instructions. The pipeline has stage slots in those cycles and the instructions use : two thirds. The empty slots are the filling at the start and the draining at the end, which matter less as grows.
Exercise 11.2 ★
A designer copies the row of lw for sw and only clears MemRead and MemtoReg, leaving RegWrite at 1. What does sw t2, 12(sp) then do besides storing? (Look at what bits 11 to 7 of an S-type word hold.)
Solution
Solution of Exercise 11.2.
In an S-type word, bits 11 to 7 are the low five bits of the immediate, not a register. For sw t2, 12(sp) they hold 12, so the register file writes register x12, which is a2. MemtoReg is 0, so the value written is the ALU result, the address . The store itself is correct; a2 is silently overwritten, and the bug shows only when a caller later reads a2. That is why RegWrite must be 0 for every instruction without a destination, while the “don’t care” signals may be anything.
Exercise 11.3 ★
Give the control signals for lui and the change it needs in the datapath. Add it to the model and check it against rv.
Solution
Solution of Exercise 11.3.
lui rd, imm writes to rd: RegWrite 1, ALUSrc 1, MemRead 0, MemWrite 0, MemtoReg 0, Branch 0. Two changes are needed. The immediate generator learns the U format (the upper 20 bits of the word, low bits zero). And the ALU’s first input must be 0, not rs1, since bits 19 to 15 of a U-type word belong to the immediate: a new multiplexer on that input, driven by a new signal, with the ALU adding.
# New signals: a_zero (the ALU's first input is 0, not rs1), pc4 (rd gets pc + 4), jump
# ("jal": the next pc is pc + imm; "jalr": the ALU result with bit 0 cleared).
MORE = {
0b0110111: dict(name="lui", alu_src=1, reg_write=1, a_zero=1, pc4=0, jump=None),
0b1101111: dict(name="jal", alu_src=1, reg_write=1, a_zero=0, pc4=1, jump="jal"),
0b1100111: dict(name="jalr", alu_src=1, reg_write=1, a_zero=0, pc4=1, jump="jalr"),
}
lui, jal and jalr code/bachelor-2/11-processor-and-pipelining/exercises/datapath_more.pyThe chapter’s test runs a program with lui (through li) and checks the model against rv.
Exercise 11.4 ★
Compute the ratio of Proposition 11.6 for and , and , and for , . How many instructions are needed for a five-stage pipeline to reach 90 % of its limit?
Solution
Solution of Exercise 11.4.
For : for , for , for . For , : , still far from 10, as filling and draining a deep pipeline cost more. For 90 % of 5: gives , so .
Exercise 11.5 ★★
Draw the timing diagram, with forwarding, of exo_diagram.S, and give its number of cycles.
main: lw t0, 0(sp)
addi t1, t0, 1
addi t2, zero, 5
add t3, t1, t2
ret
Solution
Solution of Exercise 11.5.
$ python timing_diagram.py exo_diagram.S
1 2 3 4 5 6 7 8 9 10
lw t0, 0(sp) F D X M W
addi t1, t0, 1 F D * X M W
addi t2, zero, 5 F . D X M W
add t3, t1, t2 F D X M W
jalr zero, 0(ra) F D X M W
5 instructions, 10 cycles, 1 stall cycle
The addi t1 uses t0 just after it is loaded: one stall, by Proposition 11.10, and the next addi waits one cycle in IF. add t3 gets t1 from MEM/WB and t2 from EX/MEM. Five instructions take cycles.
Exercise 11.6 ★★
A forwarding unit tests only reg_write and rd == rs, without rd != 0. Find a short program whose result is then wrong, and say what it computes.
Solution
Solution of Exercise 11.6.
$ python forwarding.py exo_x0.S --forget-x0
addi t0, zero, 41 zero <- register file
addi zero, t0, 1 t0 <- EX/MEM
add a0, zero, zero zero <- EX/MEM, zero <- EX/MEM
jalr zero, 0(ra) ra <- register file
exo_x0.S. Some lines are left out.addi zero, t0, 1 computes 42 and, since it writes x0, the register file ignores it. But the faulty unit sees rd == 0 == rs in the next instruction and forwards 42 from EX/MEM to both inputs of add a0, zero, zero, which computes 84 instead of 0. Writes to x0 are rare in compiled code, but a nop is addi zero, zero, 0, and any instruction can be used as a no-op that way.
Exercise 11.7 ★★
Add to the model a static predictor, “backward taken, forward not taken”: a branch whose target lies before it is predicted taken. Measure it on the three programs against the two-bit counter.
Solution
Solution of Exercise 11.7.
class BackwardTaken:
"""Predict taken exactly for the branches that jump backwards: loop branches."""
name = "backward taken"
def __init__(self, steps):
self.back = {s.pc: decode(s.word).imm < 0 for s in steps if s.kind == "branch"}
def predict(self, pc):
return self.back[pc]
def update(self, pc, taken):
pass
The predictor decodes the branch’s offset; it needs no memory and no warm-up. On the three programs it mispredicts 1, 72 and 158 branches (two-bit: 2, 60 and 161), for CPIs of 1.279, 1.297 and 1.322. It wins on loop_sum.S, whose only branch closes a loop, and on collatz.S, whose backward bge closes the outer loop; it loses on the sort, where the forward branch bge t4, t3, keep is taken 55 times out of 120, which a counter follows better than a fixed rule. The test checks the case of loop_sum.S.
Exercise 11.8 ★★
Prove Proposition 11.10 from the model’s rules.
Solution
Solution of Exercise 11.8.
Let a load be in EX at cycle . In the model a consumer may be in EX at at the earliest (the word leaves data memory at the end of MEM, cycle , and reaches the ALU input through MEM/WB). Instructions enter EX in order, at most one per cycle, and without hazards each enters EX one cycle after the one before. If the consumer follows the load directly, it would be in EX at ; the rule holds it one cycle, to , and nothing else delays it by this dependence: exactly one stall. If it comes instructions later, it cannot be in EX before , since the instructions between enter EX in the cycles in between: the rule asks nothing more, no stall. (The test checks both cases with an ALU instruction, a store and a branch as the consumer.)
Exercise 11.9 ★★
Reorder the loop of loop_sum.S so that no instruction stalls with forwarding, without changing what it computes, and measure the gain in cycles in the model.
Solution
Solution of Exercise 11.9.
The addi t0, t0, 4 does not depend on the load; moving it between the load and the add puts the use two places after the load:
loop: lw t2, 0(t0)
addi t0, t0, 4 # moved up: independent of the load
add a0, a0, t2 # t2 now arrives through MEM/WB: no stall
bltu t0, t1, loop
The bltu still reads t0 one instruction after the addi, which forwarding handles. The model gives 202 cycles instead of 234, the 32 load-use stalls removed, with the same 136 instructions. Compilers do this reordering, called instruction scheduling, for exactly this reason.
Exercise 11.10 ★★★
In a program, 20 % of the instructions are conditional branches, mispredicted 10 % of the time with a penalty of 2 cycles; 25 % are loads, 40 % of which are followed at once by a user of the loaded value; there are no other hazards. Compute the CPI. Which improvement is worth more: halving the misprediction rate, or reordering so that half of the load-uses disappear?
Solution
Solution of Exercise 11.10.
Per instruction, the branches cost cycle and the load-uses cycle: . Halving the misprediction rate saves (CPI 1.12); halving the load-uses saves (CPI 1.09). Here the reordering is worth more, because load-uses are more frequent than mispredictions, even with a smaller penalty.
Exercise 11.11 ★★★
Prove Proposition 11.13. Does it hold for ?
Solution
Solution of Exercise 11.11.
Within one execution the branch is taken times, then not taken. Suppose the counter is at least 2 when an execution starts. The taken outcomes are predicted taken and push the counter to 3, where it stays; the final not-taken outcome is predicted taken, wrongly, and brings the counter down to 2. So the execution has exactly one misprediction and the next one starts at 2. Once the counter has reached 3 in one execution, that execution ends at 2, and by induction every later one starts at 2 and has one misprediction. With one bit, an execution starts after a not-taken outcome: its first outcome, taken, is mispredicted, the next are right, and the exit is wrong again: two per execution. For the branch is never taken; the counter falls to 0 and never errs again, while the hypothesis (reaching 3) is never met: the proposition does not apply, and the loop costs nothing once warm.
Exercise 11.12 ★★★
Add jal and jalr to the single-cycle datapath: the new paths, the new control signals, and the model, checked against rv on a program that calls and returns.
Solution
Solution of Exercise 11.12.
jal rd, imm writes to rd and jumps to (J format); jalr rd, imm(rs1) writes and jumps to with bit 0 cleared. The datapath needs a third input on the write-back multiplexer, from the existing adder (signal pc4_to_reg); the J format in the immediate generator, whose result goes to the existing branch adder; and a third input on the PC multiplexer, the ALU result with bit 0 cleared (signal jump, three values: none, jal, jalr).
if c is None:
return cycle(m, pc, word)
rd, rs1 = word >> 7 & 31, word >> 15 & 31
imm = imm_more(word)
a = 0 if c["a_zero"] else m.x[rs1]
result = (a + imm) & MASK # the ALU adds
if c["jump"] == "jal":
next_pc = (pc + imm) & MASK
elif c["jump"] == "jalr":
next_pc = result & ~1
else:
next_pc = pc + 4
value = pc + 4 if c["pc4"] else result
write = rd != 0
return Effect(rd if write else None, value if write else None, None, None, next_pc)
The test runs a program with a call, a ret and an indirect jalr through a register: the model agrees with rv on every instruction but the auipc of la and the final ecall, and on every program of the chapter it now covers the rets too.
11.8 Problem: Making the sort run faster
Problem 11.1
Weekend problem — Making the sort run faster
A bubble sort of 16 page counts is run through the pipeline model in its three configurations. The problem counts its instructions, then its cycles, and reads the gain of each improvement in the performance equation.
Part I — Counting instructions.
sort: # sort(a0 = array, a1 = n): a leaf
addi t0, a1, -1 # i = n - 1
outer: blez t0, done # for (; i > 0; i--)
mv t1, a0 # p = &a[0]
slli t2, t0, 2
add t2, a0, t2 # end = &a[i]
inner: lw t3, 0(t1) # for (; p < end; p++)
lw t4, 4(t1)
ble t3, t4, keep # if (p[0] > p[1]) swap them
sw t4, 0(t1)
sw t3, 4(t1)
keep: addi t1, t1, 4
bltu t1, t2, inner
addi t0, t0, -1
j outer
done: ret
- How many instructions does one turn of the inner loop execute, without and with a swap?
- How many does one turn of the outer loop execute outside the inner loop?
- Prove that
sortexecutes instructions on values, where is the number of swaps. - Prove that is the number of inversions of the array, the pairs with .
- The array has 65 inversions and
mainexecutes 141 instructions. Check the total against the model’s count of 964. - How many loads and stores does the run execute?
Part II — Without forwarding.
$ python -m rv run bubble_sort.S
12 38 65 77 87 98 133 145 189 199 251 260 300 320 412 501
- Which instructions of the inner loop depend on the instruction just before them?
- Show that without forwarding an instruction one place after its producer waits two cycles, and one two places after waits one.
- The model counts 552 stall cycles. Account for them: 120 turns of the inner loop, 16 of the printing loop, 15 outer turns, and 5 single stalls of two cycles each.
- Under “not taken”, which branches cost cycles, and how many cycles do they and the jumps lose in all?
- Compute the cycles and the CPI, and check them against Output 11.7.
- Which costs more here, the data hazards or the control hazards?
Part III — Forwarding and prediction.
- With forwarding, which dependences still stall, and how many cycles do they cost?
- Propose a change of the inner loop that removes them, and say what else it saves.
- The two-bit counters mispredict 60 branches: 41 of
bge t4, t3, keep, 16 of the inner loop’sbltu, 2 of the printing loop’s, 1 of the outer test. Explain each number. - Why is the swap test the hardest to predict?
- How many cycles do branches and jumps now lose?
- Compute the cycles and the CPI.
Part IV — The performance equation.
- With the stage delays of this chapter, the single-cycle clock is 800 ps and the pipeline’s 200 ps. Compute the time of the run on the single-cycle processor and on the pipeline in its three configurations.
- How many times faster than the single-cycle processor is the best pipeline? Why not 4?
- Which factor of the performance equation does each of the three improvements (pipelining, forwarding, prediction) act on?
- What would the CPI be with a perfect predictor?
- And with a perfect predictor and the change of question 14?
- State the result of the problem.
Solution
Solution of Problem 11.1.
1. Five without a swap (lw, lw, bge, addi, bltu); seven with one, the two stores added.
2. Six: blez, mv, slli, add, then addi and j after the inner loop.
3. The addi before the loop runs once. The outer loop runs for down to 1, and turn executes 6 instructions and inner turns of 5, plus 2 per swap: , and for the swaps. The last test blez, taken, and the ret add 2. In all ; for , the three instructions addi, blez, ret.
4. A swap exchanges two adjacent values . The relative order of every other pair is unchanged, so the number of inversions falls by exactly one. At the end the array is sorted, with no inversion; every swap removed one, so equals the initial number of inversions.
5. for sort, and , the count of Output 11.7.
6. Loads: 2 per inner turn, 240, the 16 of the printing loop and the lw ra: 257. Stores: 2 per swap, 130, and sw ra: 131.
7. bge t4, t3 uses t4, loaded just before, and t3, two before; bltu t1, t2 uses t1, set by the addi just before. The two stores use the loaded values two and three places after their loads.
8. Without forwarding the consumer reads in ID, at the earliest in the producer’s WB cycle, , so it is in EX at . Placed after, it would naturally be in EX at : it waits cycles, 2 for , 1 for , none beyond.
9. Each inner turn stalls 2 at the bge and 2 at the bltu: . The stores are not stalled, the bge having waited already. The printing loop’s bltu follows its addi: . Each outer turn’s add t2, a0, t2 follows the slli: . Five pairs occur once (the sw ra after addi sp; the two la, addi after auipc; the addi t1, t0, 64 after the second la; the first blez after addi t0): 10. Total .
10. The taken branches each lose 2: 105 of the inner bltu, 55 of the swap test, 15 of the printing loop and the last outer test, 176 in all, 352 cycles. The 16 jal (one call, 15 j) lose 1 each, and sort’s ret loses 2; main’s ret is the last instruction and loses nothing. .
11. cycles, CPI .
12. The data hazards, 552 cycles against 370.
13. Only the load-use of t4 by the bge, one cycle per inner turn: 120.
14. Move addi t1, t1, 4 up between lw t4 and the bge, and write the stores as sw t4, -4(t1) and sw t3, 0(t1): the bge is then two places after the load, and no stall remains, for the same number of instructions; 120 cycles saved. A further change saves loads too: after the compare the larger value is at p[1], so it can stay in a register as the next turn’s p[0], one load instead of two per turn.
15. The swap test depends on the data and is wrong 41 times out of 120. The inner bltu is wrong at each of the 15 exits and once at the very first turn, when its counter still says “not taken”: 16, as Proposition 11.13 predicts. The printing loop’s is wrong at its first turn and at its exit: 2. The outer blez is not taken 15 times and taken once, at the end: 1.
16. Its outcome is whether two neighbours are out of order, a property of the data, not of the loop’s structure; only as the sorted tail grows does it become regular.
17. .
18. cycles, CPI .
19. Single-cycle: ns. Pipeline: ns without forwarding, ns with it, ns with the predictor too.
20. times faster. The cycle is 4 times shorter but the CPI is 1.272 instead of 1: .
21. Pipelining acts on the cycle time (and raises the CPI from 1); forwarding and prediction act on the CPI. None changes the number of instructions.
22. Only the jumps would lose cycles, 18: .
23. With no stall either: , close to the ideal.
24. In the five-stage model, forwarding and a two-bit predictor take the CPI of the bubble sort from 1.961 to 1.272: forwarding removes 432 of the 552 stall cycles, the predictor 232 of the 370 cycles lost to branches and jumps, and the run takes 1226 cycles instead of 1890, 35 % fewer.
本章定义的术语
- Branch prediction, predictor, misprediction penalty
- Control signal
- Cycles per instruction, performance equation
- Forwarding
- Hazard: structural, data, control
- Instruction pipeline, pipeline stage, pipeline register
- Latency, throughput
- Saturating counter
- Single-cycle processor
- Stall, bubble, load-use hazard