Skip to content

Commit

Permalink
[SCCP] Extend visitBinaryOperator to overflowing binary ops
Browse files Browse the repository at this point in the history
Leverage more refined ranges results when handling overflowing
binary operators.
  • Loading branch information
antoniofrighetto committed Mar 14, 2024
1 parent 589c7ab commit 6ae4fcf
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
8 changes: 7 additions & 1 deletion llvm/lib/Transforms/Utils/SCCPSolver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1486,7 +1486,13 @@ void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
// Try to simplify to a constant range.
ConstantRange A = getConstantRange(V1State, I.getType());
ConstantRange B = getConstantRange(V2State, I.getType());
ConstantRange R = A.binaryOp(cast<BinaryOperator>(&I)->getOpcode(), B);

auto *BO = cast<BinaryOperator>(&I);
ConstantRange R = ConstantRange::getEmpty(I.getType()->getScalarSizeInBits());
if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO))
R = A.overflowingBinaryOp(BO->getOpcode(), B, OBO->getNoWrapKind());
else
R = A.binaryOp(BO->getOpcode(), B);
mergeInValue(&I, ValueLatticeElement::getRange(R));

// TODO: Currently we do not exploit special values that produce something
Expand Down
29 changes: 29 additions & 0 deletions llvm/test/Transforms/SCCP/add-nuw-nsw-flags.ll
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,32 @@ then:
else:
ret i16 0
}

define i1 @test_add_nuw_sub(i32 %a) {
; CHECK-LABEL: @test_add_nuw_sub(
; CHECK-NEXT: entry:
; CHECK-NEXT: [[ADD:%.*]] = add nuw i32 [[A:%.*]], 10000
; CHECK-NEXT: [[SUB:%.*]] = add i32 [[ADD]], -5000
; CHECK-NEXT: ret i1 false
;
entry:
%add = add nuw i32 %a, 10000
%sub = add i32 %add, -5000
%cond = icmp ult i32 %sub, 5000
ret i1 %cond
}

define i1 @test_add_nsw_sub(i32 %a) {
; CHECK-LABEL: @test_add_nsw_sub(
; CHECK-NEXT: entry:
; CHECK-NEXT: [[ADD:%.*]] = add nsw i32 [[A:%.*]], 10000
; CHECK-NEXT: [[SUB:%.*]] = add nsw i32 [[ADD]], -5000
; CHECK-NEXT: [[COND:%.*]] = icmp ult i32 [[SUB]], 5000
; CHECK-NEXT: ret i1 [[COND]]
;
entry:
%add = add nsw i32 %a, 10000
%sub = add i32 %add, -5000
%cond = icmp ult i32 %sub, 5000
ret i1 %cond
}

0 comments on commit 6ae4fcf

Please sign in to comment.