处理器中的几种hazard
什么是hazard?
- Instructions interact with each other in pipeline ;
Structural Hazard
原因:
- An instruction in the pipeline may need a resource being used by another instruction in the pipeline ;
- Structural hazard occurs when two instructions need same hardware resource at same time
- 因缺乏硬件支持而导致指令不能在预定的时钟周期内执行的情况。
实例:
例子1:存储器发生结构冒险(存、取冲突)
- 假设图4-27 的流水线结构只有一个存储器而不是两个存储器,那么如果有第四条指令的话,第一条指令在访问存储器的同时第四条指令将会在同一存储器中预取指令,流水线就会发生结构冒险。
- 这种解决方式,是stall older instruction;
例子2:寄存器发生结构冒险(读、写冲突)
- 如图所示,读寄存器和写寄存器同时发生,产生结构冒险。
如何解决:
- Can resolve in hardware by stalling newer instruction till older instruction finished with resource
- A structural hazard can always be avoided by adding more hardware to design;
- E.g., if two instructions both need a port to memory at same time, could avoid hazard by adding second port to memory;
- 感觉还有另外一种,是通过编译器解决的,就是编译器通过分析,将调整顺序不影响执行结果的指令,如果存在结构冒险,则通过调整顺序的方式,将这种结构冒险给消除掉;
Data Hazard
原因:
- An instruction may depend on something produced by an earlier instruction;
- Dependence for a data value;
- 发生在由于一条指令必须等待另一条指令的完成而造成流水线暂停的情况下。
- 这种hazard总结起来,就是说:无法提供指令所需数据;
- 即一条指令的执行需要等待另一条指令执行完成后所产生的数据。
实例:
- 上例中解决方式一:bubbles
- 上例中解决方式二:bypass
如何解决:
- Interlock
- Wait for hazard to clear by holding dependent instruction in issue stage;
- Bypass
- Resolve hazard earlier by bypassing value as soon as available;
- Speculate
- Guess on value, correct if wrong;
- So far, only effective in certain limited cases:
- Branch prediction
- Stack pointer updates
- Memory address disambiguation
Control Hazard
原因:
- An instruction may depend on something produced by an earlier instruction;
- Dependence may be for the next instruction’s address(branches, exceptions);
- 决策依赖于一条指令的结果,而其他指令正在执行中。比如说分支跳转指令,必须等ALU给出结果后才知道该跳转到哪一条语句。
- 因为取到的指令并不是所需要的(或者说指令地址的变化并不是流水线所预期的)而导致指令不能在预定的时钟周期内执行。
实例一:
实例二:What do we need to calculate next PC?
- 对于Unconditional Jumps类型的指令
- Opcode, PC, and offset
- 对于For Jump Register类型的指令
- Opcode, Register value, and offset
- 对于Conditional Branches类型的指令
- Opcode, Register (for condition), PC and offset
- 对于all other instructions
- Opcode and PC ( and have to know it’s not one of above )
如何解决:
- 加入delay slot;
- 分支预测