What is this all about?
While theoretically, CPU instructions follow each other back-to-back, one per clock cycle, in
reality varying instructions tend take a varying amount of time to complete.
Consider this code:
ADD.D F3;F1;F2 ; F3 = F1+F2
ADD.D F4;F1;F3 ; F4 = F1+F3
The second instruction uses the result of the first instruction (F3
) as one if
its operands. To be able to do so, the first ADD.D
instruction must have finished
writing it's result into register F3
. If the second instruction is executed
before the first finished, it may use an old value of F3
, resulting in a wrong
result.
This kind of dependency is called RAW (Read After Write). If not considered, it can
become a Data Hazard. To avoid that, CPUs employ Scoreboarding or
Tomasulos Algorithm.
ADD.D F3;F1;F2 ; F3 = F1+F2
ADD.D F2;F5;F6 ; F2 = F5+F6
In this example, the second instruction writes to F2
, which is an operand for the
first instruction. If executed without care, this write might happen before the first
instruction had time to read it first, again resulting in incorrect calculation. A
WAR (Write After Read) hazard occured.
MUL.D F3;F1;F2 ; F3 = F1+F2
ADD.D F3;F5;F6 ; F3 = F5+F6
The last data hazard to mention is WAW (Write After Write). If instructions are
executed out of order, instruction two may write to F3
before the first one. As a
result, the first instructions writes its result last, leaving the final output wrong.