[TailCallElim] Accumulator recursion elimination keeps the accumulator's range attribute, causing a miscompile
TailCallElim’s accumulator transformation moves %m = call range(i8 1, 3) @llvm.umax.i8(i8 %r, i8 1) into the loop as umax(%accumulator.tr, %k), but keeps range(i8 1, 3). That range held for umax(x, 1), not for umax(acc, k). The accumulator starts at 0 (the identity value for umax), so when the recursion never runs and %k == 0, the call returns 0 and the result is poison.
Reproducer: opt -passes=tailcallelim -S Godbolt
define i8 @kind(ptr %p) {
entry:
%tag = load i8, ptr %p, align 1, !range !0
%is_wrap = icmp eq i8 %tag, 1
br i1 %is_wrap, label %wrap, label %leaf
leaf:
%kp = getelementptr inbounds i8, ptr %p, i64 1
%k = load i8, ptr %kp, align 1, !range !1
ret i8 %k
wrap:
%cp = getelementptr inbounds i8, ptr %p, i64 8
%c = load ptr, ptr %cp, align 8
%r = call i8 @kind(ptr %c)
%m = call range(i8 1, 3) i8 @llvm.umax.i8(i8 %r, i8 1)
ret i8 %m
}
declare i8 @llvm.umax.i8(i8, i8)
!0 = !{i8 0, i8 2}
!1 = !{i8 0, i8 3}
Output, still wrong on trunk:
%accumulator.tr = phi i8 [ 0, %entry ], [ %m, %wrap ]
...
%accumulator.ret.tr = tail call range(i8 1, 3) i8 @llvm.umax.i8(i8 %accumulator.tr, i8 %k)
This miscompiles safe Rust code: Rust issue Godbolt. At -O, f folds to ret i8 1 and the program prints B instead of A. We found it in production code, where a shader code generator dropped a type cast.
The likely fix is to drop poison-generating return attributes and flags when the accumulator instruction is moved into the loop.
working on this
/cherry-pick 21c1bcd7059ca56dee6bc377e60a06a3b18a1d69
/pull-request llvm/llvm-project#234221