Computer Organization : Understanding Read After Write (RAW) Hazards and Hazard Handling in Computer Organization

Read After Write (RAW) hazard with an example:

Consider the following sequence of instructions:

  1. ADD R1, R2, R3 ; R1 = R2 + R3
  2. SUB R4, R1, R5 ; R4 = R1 – R5
  3. MUL R6, R1, R7 ; R6 = R1 * R7

In this example, the first instruction (ADD) calculates the sum of R2 and R3 and stores the result in R1. The second instruction (SUB) then tries to use the value in R1 to perform a subtraction with R5 and stores the result in R4. Finally, the third instruction (MUL) multiplies the value in R1 with R7 and stores the result in R6.

The hazard arises from the fact that the third instruction (MUL) depends on the result of the first instruction (ADD). Specifically, the value of R1, which is computed by the ADD instruction, is needed as an input to the MUL instruction. However, the ADD instruction has not yet completed its execution, and the value of R1 has not been updated in the register file.

As a result, the processor faces a hazard, as the MUL instruction is trying to read from R1 before the value has been written back from the ADD instruction. This is a Read After Write (RAW) hazard, and it can lead to incorrect results if not handled properly.

To resolve the RAW hazard, the processor must ensure that the value of R1 is available and ready to be read by the MUL instruction. There are several techniques to handle hazards, including:

Stalling the Pipeline: The processor can insert a “bubble” or “NOP” (no-operation) into the pipeline, effectively stalling the execution of the MUL instruction until the ADD instruction completes and updates the value in R1.

Forwarding (Data Hazard Forwarding): Instead of stalling, the processor can use forwarding paths to directly provide the updated value of R1 from the output of the ADD instruction to the input of the MUL instruction. This avoids stalling and allows the MUL instruction to proceed without waiting for the data to be written to R1 in the register file.

Out-of-Order Execution: Modern processors may use techniques like out-of-order execution to dynamically rearrange the instruction order to avoid hazards, including RAW hazards. This allows the processor to continue executing other independent instructions while handling the hazard in a more flexible manner.

Author: user

Leave a Reply