int foo(int i, int j) { int res = -( i / j); int res2 = -i / j; return res + res2; }
Currently, we get:
define dso_local i32 @foo(i32, i32) local_unnamed_addr #0 { %3 = sdiv i32 %0, %1 %4 = sub nsw i32 0, %0 %5 = sdiv i32 %4, %1 %6 = sub i32 %5, %3 ret i32 %6 }
With this fold we will get
define dso_local i32 @foo(i32, i32) local_unnamed_addr #0 { %3 = sdiv i32 %0, %1 %4 = sdiv i32 %0, %1 %5 = sub nsw i32 0, %4 %6 = sub i32 %5, %3 ret i32 %6 }
Which will then get folded into
define dso_local i32 @foo(i32, i32) local_unnamed_addr #0 { %3 = sdiv i32 %0, %1 %factor = mul i32 %3, -2 ret i32 %factor }
So we end with just one division:
https://godbolt.org/z/gSCKQ1
It's not commutative like that.
(You could use https://rise4fun.com/Alive, but it appears down for the moment?)