Overflow Detections

$(¬(sign_A⊕sign_B))∧(sign_A⊕new_{sign})$
Dealing with Overflow
Some languages (比如C) ignore overflow: Let compilers or programmers decide what to do
Other language (e.g., Ada, Fortran) require an exception to be raised. If the hardware detects overflow/underflow, it raises an exception and invokes the exception handler.
Internal overflow (instruction overflow): handle immediately
External overflow:
- Save PC in exception program counter (mepc) register 保存现场→出事位置
- Save status in the CSR registers (e.g. mcause) 保存现场→记录原因
- Jump to a predefined handler address 跳转到预先写好的异常处理程序
- Return after corrective action (by jalr instruction) 修复完问题后返回原先代码位置继续执行
- This requires precise exceptions, making out-of-order execution hard to implement
- 精确异常要求:异常发生时,必须保证所有之前的指令都执行完,之后的指令都没执行。
- 但乱序执行(比如CPU同时处理多条指令)会打乱指令顺序,导致难以确定“到底哪条指令触发了异常”。
- 这需要复杂的硬件设计(比如用重排序缓冲ROB),因此支持异常的语言(如Ada)会让硬件设计更复杂。
Why not HW traps on Overflow
- Performance Impact (check overflow, traps are expensive to handle, rare)
- Exception handling increases the complexity of high performance implementations (pipelining, out-of-order execution).
- Flexibility: some applications want the warp around behavior of the unsigned integers
The potential performance impact and added complexity of hardware traps have led to alternative approaches that rely on software or compiler support for overflow detection and handling.
由于检查每次运算是否溢出会带来明显的性能下降和系统复杂度增加,并且大部分情况下并不需要处理溢出问题,所以硬件层面通常不采用对溢出触发陷阱的方式,而是依赖软件或编译器在需要的时候才通过特殊检测手段来处理溢出问题。这样既能保持高性能,又能在必要时提供对溢出的恰当处理。
Overflow Handling in RISC-V