[InstCombine] Fold abs(X, false) --> abs(X, true) If X != INT_MIN
Summary
The second argument of the llvm.abs intrinsic determines the behaviour when X == INT_MIN. If false, llvm.abs will return INT_MIN. If true, the return would be a poison. Therefore, the flag can be changed to true if it is known that X != INT_MIN.
Alive2 proof: https://alive2.llvm.org/ce/z/NorBAu
PR: #219527
Reasoning
This fold represents a narrowing of the range of possible return values and allows the following optimisations to return simpler forms:
abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
For example, in this scenario using eq, the fold causes the optimisation to use the simpler X > -1 form which allows the further optimisation of the or instruction being deleted:
define i1 @abs_no_poison_ne_int_min_eq_fold(i32 %x) {
%x1 = or i32 %x, 1
%abs = call i32 @llvm.abs.i32(i32 %x1, i1 false)
%cmp = icmp eq i32 %abs, %x1
ret i1 %cmp
}
Result without llvm.abs fold:
define i1 @abs_no_poison_ne_int_min_eq_fold(i32 %x) {
%x1 = or i32 %x, 1
%cmp = icmp ult i32 %x1, -2147483647
ret i1 %cmp
}
Result with llvm.abs fold:
define i1 @abs_no_poison_ne_int_min_eq_fold(i32 %x) {
%cmp = icmp sgt i32 %x, -1
ret i1 %cmp
}
The two intrinsics ctlz and cttz have a similar flag for X == 0 values being poison. They already have a fold for false flags:
// If the input to cttz/ctlz is known to be non-zero,
// then change the 'ZeroIsPoison' parameter to 'true'
// because we know the zero behavior can't affect the result.
if (!Known.One.isZero() ||
isKnownNonZero(Op0, IC.getSimplifyQuery().getWithInstruction(&II))) {
if (!match(II.getArgOperand(1), m_One()))
return CallInst::Create(II.getCalledFunction(),
{Op0, IC.Builder.getTrue()});
}
@tadeuszjt: Could you please elaborate?
@tadeuszjt: Could you please elaborate?
I don't have a real-world use case to back this up, the InstCombine guide seems to be against this sort of thing. https://llvm.org/docs/InstCombineContributorGuide.html