FuelLabs / sway

🌴 Empowering everyone to build reliable and efficient smart contracts.
https://docs.fuel.network/docs/sway/
Apache License 2.0
62.76k stars 5.36k forks source link

conditional constant propagation #6498

Closed vaivaswatha closed 3 weeks ago

vaivaswatha commented 3 weeks ago

Given this Sway code

script;

pub fn main() -> u64 {
    foo(10) + foo(11)
}

fn foo(p: u64) -> u64 {
   if p == 10 {
      p + 1
   } else {
      p - 1
   }
}

This optimization (after const-folding) produces

fn foo_2(p !116: u64) -> u64, !119 {
        entry(p: u64):
        v0 = const u64 10, !120
        v1 = cmp eq p v0, !123
        v2 = const u64 11, !126
        cbr v1, block2(v2), block1(), !121

        block1():
        v3 = const u64 1, !127
        v4 = sub p, v3, !130
        br block2(v4)

        block2(v5: u64):
        ret u64 v5
    }

The p+1 has been optimized into 11.

vaivaswatha commented 3 weeks ago

Unfortunately, this optimisation has no impact on our testsuite, but considering that it's linear (and hence not expensive), I think we should still merge this.