Sub topic 3
Control Hazards: Branches and Jumps
This chapter assumes you know the five-stage pipeline (IF, ID, EX, MEM, WB), pipeline registers, clock period, CPI (cycles per instruction), and data hazards with forwarding.
Control hazards
A control hazard occurs when the pipeline cannot yet tell which instruction comes next. A conditional branch decides its direction in EX, but IF has already fetched the sequential instructions behind it. If the branch is taken, those fetched instructions are on the wrong path.
Handling branches: flush, predict-not-taken, delayed branch
The simplest fix is to flush: discard the wrong-path instructions and restart fetch at the target. When a branch resolves in EX, a taken branch usually costs 2 cycles in a five-stage pipeline.
Predict-not-taken keeps fetching sequentially. The penalty applies only when the branch is actually taken.
A delayed branch places one or more independent instructions after the branch. The pipeline always executes them, so no flush is needed when the slot holds useful work.
Effective CPI and speedup with stalls
Effective CPI equals the ideal CPI plus the branch frequency times the penalty per branch.
def effective_cpi(base_cpi, branch_freq, penalty):
return base_cpi + branch_freq * penalty
cpi = effective_cpi(1, 0.20, 2) # 20% branches, 2-cycle penalty
print(cpi) # 1.4
print(round(5 / cpi, 2)) # speedup over a 5-cycle unpipelined CPI: 3.57Static and dynamic branch prediction
Static prediction uses a fixed rule, such as predict-not-taken, or backward-taken and forward-not-taken. Dynamic prediction records recent outcomes in a branch history table (BHT). A common design uses 2-bit saturating counters indexed by low address bits. Two consecutive wrong outcomes are needed to flip the prediction, which suits loop branches.
Solving GATE-style pipelining problems
Apply the same steps to every question:
- Find the stage where each branch is resolved.
- Count the wrong-path instructions flushed. That count is the penalty.
- Take the branch frequency and misprediction rate from the question.
- Compute CPI, then speedup as old time divided by new time.
Beyond the basic pipeline: superscalar and out-of-order execution
A superscalar processor issues several instructions per cycle, so one mispredicted branch wastes more issue slots. An out-of-order processor executes independent instructions while a branch is pending, then discards wrong-path results at commit. GATE questions usually assume the scalar five-stage pipeline, so check the question before applying these ideas.
Exercise
A program has 25% branches. Each taken branch costs 2 cycles, and the pipeline predicts not taken. Assume every branch is taken. What is the effective CPI?
Show answer
CPI = 1 + 0.25 × 2 = 1.5.