Why clang generate 'nsw add' for this sum function (original) (raw)

source code is

int sum(int a, int b, int c, int d) {
return a+b+c+d;
}

after run clang -S -emit-llvm -O3, i got

define dso_local i32 @sum(i32 noundef %0, i32 noundef %1, i32 noundef %2, i32 noundef %3) local_unnamed_addr #0 {
%5 = add nsw i32 %1, %0
%6 = add nsw i32 %5, %2
%7 = add nsw i32 %6, %3
ret i32 %7
}`

What I can’t understand is: why is there no signed wrap?

I really appreciate anyone who’s taken time to read or help with this - your input means a lot!

C has decided that signed overflow is UB because they want to make your life in particular worse.

niu2x June 2, 2025, 9:56am 3

That makes perfect sense.