Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1910,6 +1910,23 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
return Res;

// Combine adds through zext nneg:
// (zext nneg (X + C1)) + C2 --> zext X if C1 + C2 == 0
{
Value *X;
const APInt *C1, *C2;
if (match(&I, m_c_Add(m_NNegZExt(m_Add(m_Value(X), m_APInt(C1))),
m_APInt(C2)))) {
// Check if the constants cancel out (C1 + C2 == 0)
APInt Sum = C1->sext(C2->getBitWidth()) + *C2;
if (Sum.isZero()) {
// The add inside the zext and the outer add cancel out
Value *NewZExt = Builder.CreateZExt(X, I.getType());
return replaceInstUsesWith(I, NewZExt);
}
}
}

// Re-enqueue users of the induction variable of add recurrence if we infer
// new nuw/nsw flags.
if (Changed) {
Expand Down
11 changes: 11 additions & 0 deletions llvm/test/Transforms/InstCombine/zext.ll
Original file line number Diff line number Diff line change
Expand Up @@ -976,3 +976,14 @@ entry:
%res = zext nneg i2 %x to i32
ret i32 %res
}

define i32 @zext_nneg_add_cancel(i8 %arg) {
; CHECK-LABEL: @zext_nneg_add_cancel(
; CHECK-NEXT: [[ADD2:%.*]] = zext i8 [[ARG:%.*]] to i32
; CHECK-NEXT: ret i32 [[ADD2]]
;
%add = add i8 %arg, -2
%zext = zext nneg i8 %add to i32
%add2 = add i32 %zext, 2
ret i32 %add2
}