5.2.10Processor Datapath & Pipelining

Hazard detection units

3,153 words14 min readdifficulty · medium1 backlinks

What Problem Does It Solve?

In a pipelined processor, multiple instructions execute simultaneously across different stages (IF, ID, EX, MEM WB). But what if instruction2 needs the result of instruction 1 before instruction 1 writes it back? Or what if a branch changes the PC while the pipeline already fetched wrong instructions?

The hazard detection unit is dedicated combinational logic that:

  1. Monitors pipeline registers for dependencies
  2. Generates control signals (stall, flush, forward)
  3. Coordinates with the forwarding unit to resolve hazards

Why combinational? Decisions must happen within a single clock cycle—before the next clock edge commits wrong values.

Types of Hazards Detected

Architecture: Data Hazard Detection Logic

The Detection Combinational Circuit

The hazard detection unit sits in the ID stage and examines:

  • ID/EX register: The instruction currently in EX
  • EX/MEM register: The instruction currently in MEM
  • MEM/WB register: The instruction currently in WB
  • IF/ID register: The instruction currently in ID

Why ID stage? This is where we decode the instruction and know which registers it reads. We can detect dependencies before EX tries to use stale data.

Why this matters: Other data hazards can be resolved by forwarding (the forwarding unit handles those). The hazard detection unit only stalls when forwarding is impossible.

Stall Signal Generation

When the condition above is true, the hazard unit asserts:

  • PCWrite = 0: Freeze the PC (don't fetch next instruction)
  • IF/ID_Write = 0: Freeze IF/ID register (keep current instruction in ID)
  • Control_Mux = 0: Insert a NOP (bubble) into ID/EX by zeroing all control signals

Why these three signals?

  1. PCWrite=0: If we fetch the next instruction, we'd lose it when we finally advance
  2. IF/ID_Write=0: Hold the dependent instruction in ID so it retries next cycle with correct data
  3. Control_Mux=0: The instruction that was going to move from ID→EX must become a bubble (no operation) so it doesn't corrupt the pipeline

Architecture: Control Hazard Detection

Branch Resolution and Flushing

For branches, the hazard detection unit must:

  1. Detect the branch early (ideally in ID by comparing registers)
  2. Flush wrong-path instructions if branch is taken
  3. Optionally predict (simple version: assume not-taken)

Optimization: Early branch resolution in ID

  • Add comparison hardware in ID stage (instead of waiting for ALU in EX)
  • Compute branch target in ID using an adder
  • Reduces branch penalty from 3 cycles to 1 cycle

Interaction with Forwarding Unit

The hazard detection unit and forwarding unit are separate but coordinated:

| Unit | Purpose Placement | Action | |------|---------|--------|-----| | Forwarding Unit | Resolve hazards bypassing register file | EX stage | Muxes data from EX/MEM or MEM/WB directly into ALU inputs | | Hazard Detection Unit | Detect unsolvable hazards (load-use) | ID stage | Stalls pipeline when forwarding can't help |

Why separate?

  • Forwarding is about data routing (mux selection)
  • Hazard detection is about control flow (stall/flush signals)

Implementation Details

Simplified Verilog Sketch

module hazard_detection_unit(
    input [4:0] IF_ID_Rs, IF_ID_Rt,
    input [4:0] ID_EX_Rd,
    input ID_EX_MemRead,
    output reg Stall
);
    always @(*) begin
        // Load-use detection
        if (ID_EX_MemRead && 
            ((ID_EX_Rd == IF_ID_Rs) || (ID_EX_Rd == IF_ID_Rt))) begin
            Stall = 1;  // Assert stall signals
        end else begin
            Stall = 0;
        end
    end
endmodule

Why this works:

  • Combinational (always @(*)) so output updates immediately
  • Checks the one-cycle delay case where load is in EX and dependent instruction is in ID
  • Real implementations also check for Rd != 0 (register 0 is hardwired to zero in MIPS)
Recall Explain to a 12-Year-Old

Imagine you're working on a group project with 5 friends, and you're all building a big Lego castle. Each friend works on one part (fetching pieces, gluing, painting, adding details, putting it on display). You're all working on different parts of different towers at the same time—like a factory assembly line!

But sometimes there's a problem: Sarah needs to paint a tower that Ahmed is still gluing. The paint jar (data) isn't ready yet! If Sarah just grabs whatever's there, she'll paint the wrong thing and mess up the whole castle.

The hazard detection unit is like a smart supervisor who watches everyone. When they see Sarah about to paint something that's not ready, they say "Wait one minute, Sarah!" (stall). Or if Ahmed finishes gluing and can hand the tower directly to Sarah without putting it on the table first (forwarding), the supervisor lets that happen to save time.

Some mistakes can be fixed by passing things directly (forwarding). Some need you to actually wait (stall). The supervisor knows which is which!

Advanced: Handling Multiple Hazards

What if multiple hazards exist in the same cycle?

Priority rules:

  1. Load-use hazard (stall) takes priority—must resolve first
  2. Branch hazard (flush) applied after stall completes
  3. Forwarding happens after stall, using the now-available data

Connections

  • 5.2.8-Pipeline-registers: Hold the instruction and control signals between stages
  • 5.2.9-Forwarding-unit: Resolves most data hazards without stalling
  • 5.2.11-Branch-prediction: Reduces control hazard penalties (advanced topic)
  • 5.2.7-Pipeline-control-signals: The signals (RegWrite, MemRead, etc.) that hazard detection examines
  • 5.1.3-Control-unit: Generates the original control signals; hazard unit can override them (mux to NOP)

#flashcards/hardware

What does a hazard detection unit do in a pipelined processor? :: It monitors pipeline registers for data/control dependencies and generates stall or flush signals to prevent hazards from corrupting results. It coordinates with the forwarding unit to resolve hazards when possible.

Why must hazard detection logic be combinational?
Because hazard decisions must complete within a single clock cycle—before the next clock edge commits pipeline register updates. Sequential logic would introduce an extra cycle of delay, allowing wrong values to propagate.
What is a load-use hazard?
A data hazard where an instruction immediately follows a load and needs the loaded data. Forwarding can't help because the load's data isn't available until the end of MEM stage, but the dependent instruction needs it at the start of EX. Requires a1-cycle stall.
What three control signals does the hazard detection unit assert to stall the pipeline?
PCWrite=0 (freeze program counter), IF/ID_Write=0 (freeze IF/ID register), and insert a NOP into ID/EX (by zeroing control signals via mux). This holds the dependent instruction in ID and creates a bubble in EX.
Why can't forwarding resolve a load-use hazard?
Because forwarding routes data from EX/MEM or MEM/WB to the ALU inputs. A load's data doesn't reach MEM/WB until the cycle after the dependent instruction would execute in EX. There's a 1-cycle timing gap that forwarding can't bridge without time travel.
What is a control hazard?
A hazard where the pipeline doesn't know which instruction to fetch next because a branch condition hasn't been evaluated yet. Already-fetched instructions might be from the wrong path and must be flushed if the branch is taken.
How does early branch resolution in ID reduce penalty?
By adding comparison logic and branch target adder in ID, the branch decision happens1 cycle earlier (instead of waiting for the ALU in EX). This reduces the number of wrong-path instructions fetched from 2 to 1, cutting the penalty from 2 cycles to 1 cycle.
Why are the hazard detection unit and forwarding unit separate?
Hazard detection (ID stage) handles control decisions—when to stall or flush. Forwarding (EX stage) handles data routing—which pipeline register to mux into the ALU. Separating them simplifies design: stall only when forwarding can't help, forward whenever possible.
What happens when a branch is resolved as taken in ID?
The hazard detection unit asserts a flush signal that converts the IF/ID register (containing the wrongly-fetched next instruction) into a NOP. The PC is updated to the branch target, and the pipeline continues from the correct path.
In the load-use detection formula, why do we check ID/EX.MemRead == 1?
Because only load instructions read from memory. IfMemRead=0, the instruction in EX is not a load, so its result will be available forwarding without a stall. MemRead=1 identifies the specific case where data won't be ready in time.

Concept Map

implemented as

monitors

monitors

monitors

special case

requires

resolved by

resolved by

coordinates with

prevents

prevents

Hazard Detection Unit

Combinational Logic in ID stage

Data Hazard

Control Hazard

Structural Hazard

Stall Pipeline

Flush Pipeline

Forwarding Unit

Load-Use Hazard

Wrong Results

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, pipeline mein hazard detection unit ek bahut smart traffic cop ki tarah kaam karta hai. Jaise highway pe carsek ke bad ek chalti hain aur lanes change karti hain, waise hi CPU ke andar instructions pipeline ke alag-alag stages (IF, ID, EX, MEM, WB) mein simultaneously execute ho rahi hotiain. Lekin problem tab ati hai jab ek instruction ko dosri instruction ka result chahiye, par wo result abhi ready nahi hai—jaise tumhe ek book padhni hai jo tumhara dost abhi likh hi raha hai!

Hazard detection unit teen tarah ke problems detect karta hai. Pehla hai data hazard: jab instruction 2 ko instruction 1 ka result chahiye lekin wo abhi pipeline mein hi hai, write-back tak nahi pahuncha. Dosra hai control hazard: branch instruction ke baad pata nahi chalta ki next instruction konsi fetch karo, toh galat instruction utha leti hai pipeline. Tesra hai structural hazard: hardware resource (jaise memory port) ek sath sabko nahi mil sakta.

Ab yeh unit bas monitor nahi karta, action bhi leta hai! Agar forwarding unit data directly bhej sakta hai (jaise ALU se EX/MEM register se), toh HDU kuch nahi karta—forwarding handle kar legi. Lekin agar load instruction hai aur next instruction turant us loaded data ko use karna chahti hai (load-use hazard), toh forwarding help nahi kar sakti kyunki data memory se abhi aya hi nahi. Tab HDU stall signal generate karta hai: PC ko freeze kar do (PCWrite=0), IF/ID register ko rok do (IF/ID_Write=0), aur pipeline mein ek "bubble" (NOP instruction) daal do. Yeh 1 cycle ka wait time deta hai taki load complete ho aur phir forwarding kaam kar sake.

Control hazards ke liye agar branch taken hai toh HDU flush signal deta hai—galat fetched instructions ko NOP bana do aur sahi path se continue karo. Modern processors branch ko ID stage mein hi resolve karlete hain (comparison hardware add karke), toh penalty sirf 1 cycle ki hoti hai instead of 2-3 cycles. Yeh sab coordination HDU aur forwarding unit ke bech hota hai—ek control decisions leta hai (kab stall, kab flush), dosra data routing handle karta hai (konsa data kahan se forward karo).Iss tarah CPU correct results deta hai bina data corruption ke, aur jitna possible ho sake speed bhi maintain karta hai. Samajh mein aya? Yeh hardware kaek solid real-time problem-solving example hai!

Go deeper — visual, from zero

Test yourself — Processor Datapath & Pipelining

Connections