Skip to content

Commit d59cce5

Browse files
committed
SILOptimizer: Teach constant folding about add, sub, mul variants without overflow checks
1 parent 40d0ea5 commit d59cce5

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

lib/SILOptimizer/Utils/ConstantFolding.cpp

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -588,8 +588,31 @@ static SILValue constantFoldBinary(BuiltinInst *BI,
588588
// Are there valid uses for these in stdlib?
589589
case BuiltinValueKind::Add:
590590
case BuiltinValueKind::Mul:
591-
case BuiltinValueKind::Sub:
592-
return nullptr;
591+
case BuiltinValueKind::Sub: {
592+
OperandValueArrayRef Args = BI->getArguments();
593+
auto *LHS = dyn_cast<IntegerLiteralInst>(Args[0]);
594+
auto *RHS = dyn_cast<IntegerLiteralInst>(Args[1]);
595+
if (!RHS || !LHS)
596+
return nullptr;
597+
APInt LHSI = LHS->getValue();
598+
APInt RHSI = RHS->getValue();
599+
600+
switch (ID) {
601+
default: llvm_unreachable("Not all cases are covered!");
602+
case BuiltinValueKind::Add:
603+
LHSI += RHSI;
604+
break;
605+
case BuiltinValueKind::Mul:
606+
LHSI *= RHSI;
607+
break;
608+
case BuiltinValueKind::Sub:
609+
LHSI -= RHSI;
610+
break;
611+
}
612+
613+
SILBuilderWithScope B(BI);
614+
return B.createIntegerLiteral(BI->getLoc(), BI->getType(), LHSI);
615+
}
593616

594617
case BuiltinValueKind::And:
595618
case BuiltinValueKind::AShr:

0 commit comments

Comments
 (0)