MIR Optimization: Constant Folding & Propagation
C-enhancementC-perfE-mediumA-codegen
## Summary
Implement constant folding and propagation on MIR to evaluate constant expressions at compile time.
**Parent issue:** #687
## Context
Constant folding evaluates operations with constant operands at compile time:
- `add(5, 3)` → `8`
- `mul(x, 0)` → `0` (even if x is not constant)
- `and(x, 0xFF)` where x is `uint8` → `x` (no-op)
This reduces bytecode size and gas costs, and enables further optimizations.
## Tasks
### Basic constant folding
- [ ] For arithmetic ops with constant operands, compute result
- [ ] Handle 256-bit arithmetic correctly (wrapping, overflow)
- [ ] Support all arithmetic ops: add, sub, mul, div, mod, exp
- [ ] Support all bitwise ops: and, or, xor, not, shl, shr, sar
### Algebraic simplifications
- [ ] `add(x, 0)` → `x`
- [ ] `mul(x, 1)` → `x`
- [ ] `mul(x, 0)` → `0`
- [ ] `div(x, 1)` → `x`
- [ ] `and(x, 0)` → `0`
- [ ] `or(x, 0)` → `x`
- [ ] `xor(x, 0)` → `x`
- [ ] `shl(x, 0)` → `x`
- [ ] `sub(x, x)` → `0`
- [ ] `xor(x, x)` → `0`
### Comparison folding
- [ ] `eq(5, 5)` → `true`
- [ ] `lt(3, 5)` → `true`
- [ ] `iszero(0)` → `true`
- [ ] Propagate through branches (see SCCP issue)
### Integration with lowering
- [ ] Fold during HIR→MIR lowering where possible
- [ ] Avoid generating constant operations in the first place
## Example
```
; Before constant folding
v0 = const 10
v1 = const 5
v2 = add(v0, v1) ; → const 15
v3 = mul(v2, 2) ; → const 30
v4 = arg(0)
v5 = add(v4, 0) ; → v4
return v5
; After constant folding
v4 = arg(0)
return v4
```
## Acceptance Criteria
- [ ] All 256-bit arithmetic handled correctly
- [ ] Algebraic identities applied
- [ ] Tests verify no incorrect simplifications
- [ ] Measurable reduction in instruction counts
## Estimated Complexity
**Small-Medium** - Straightforward but many cases to handle
## Dependencies
- MIR structure (done)
3 条评论