36#define DEBUG_TYPE "indvars"
38STATISTIC(NumElimIdentity,
"Number of IV identities eliminated");
39STATISTIC(NumElimOperand,
"Number of IV operands folded into a use");
40STATISTIC(NumFoldedUser,
"Number of IV users folded into a constant");
41STATISTIC(NumElimRem ,
"Number of IV remainder operations eliminated");
44 "Number of IV signed division operations converted to unsigned division");
47 "Number of IV signed remainder operations converted to unsigned remainder");
48STATISTIC(NumElimCmp,
"Number of IV comparisons eliminated");
49STATISTIC(NumInvariantCmp,
"Number of IV comparisons made loop invariant");
50STATISTIC(NumSameSign,
"Number of IV comparisons with new samesign flags");
57 class SimplifyIndvar {
67 bool RunUnswitching =
false;
74 : L(
Loop), LI(LI), SE(SE), DT(DT),
TTI(
TTI), Rewriter(Rewriter),
76 assert(LI &&
"IV simplification requires LoopInfo");
79 bool hasChanged()
const {
return Changed; }
80 bool runUnswitching()
const {
return RunUnswitching; }
85 void simplifyUsers(PHINode *CurrIV, IVVisitor *
V =
nullptr);
87 void pushIVUsers(Instruction *Def,
88 SmallPtrSet<Instruction *, 16> &Simplified,
89 SmallVectorImpl<std::pair<Instruction *, Instruction *>>
92 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
94 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
95 bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
96 bool replaceFloatIVWithIntegerIV(Instruction *UseInst);
98 bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
99 bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
100 bool eliminateTrunc(TruncInst *TI);
101 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
102 bool makeIVComparisonInvariant(ICmpInst *ICmp, Instruction *IVOperand);
103 void eliminateIVComparison(ICmpInst *ICmp, Instruction *IVOperand);
104 void simplifyIVRemainder(BinaryOperator *Rem, Instruction *IVOperand,
106 void replaceRemWithNumerator(BinaryOperator *Rem);
107 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
108 bool replaceRemWithNumeratorOrZeroUpdateProfiles(SelectInst &SI);
109 void replaceSRemWithURem(BinaryOperator *Rem);
110 bool eliminateSDiv(BinaryOperator *SDiv);
111 bool strengthenBinaryOp(BinaryOperator *BO, Instruction *IVOperand);
112 bool strengthenOverflowingOperation(BinaryOperator *OBO,
113 Instruction *IVOperand);
114 bool strengthenRightShift(BinaryOperator *BO, Instruction *IVOperand);
124 for (
auto *Insn : Instructions)
127 assert(CommonDom &&
"Common dominator not found?");
140 Value *IVSrc =
nullptr;
141 const unsigned OperIdx = 0;
142 const SCEV *FoldedExpr =
nullptr;
143 bool MustDropExactFlag =
false;
147 case Instruction::UDiv:
148 case Instruction::LShr:
151 if (IVOperand != UseInst->
getOperand(OperIdx) ||
166 if (UseInst->
getOpcode() == Instruction::LShr) {
181 MustDropExactFlag =
true;
188 if (SE->
getSCEV(UseInst) != FoldedExpr)
191 LLVM_DEBUG(
dbgs() <<
"INDVARS: Eliminated IV operand: " << *IVOperand
192 <<
" -> " << *UseInst <<
'\n');
195 assert(SE->
getSCEV(UseInst) == FoldedExpr &&
"bad SCEV with folded oper");
197 if (MustDropExactFlag)
203 DeadInsts.emplace_back(IVOperand);
207bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
208 Instruction *IVOperand) {
212 unsigned IVOperIdx = 0;
229 ICmpInst::Predicate InvariantPredicate = LIP->Pred;
230 const SCEV *InvariantLHS = LIP->LHS;
231 const SCEV *InvariantRHS = LIP->RHS;
234 auto *PHTerm = Preheader->getTerminator();
235 if (
Rewriter.isHighCostExpansion({InvariantLHS, InvariantRHS}, L,
237 !
Rewriter.isSafeToExpandAt(InvariantLHS, PHTerm) ||
238 !
Rewriter.isSafeToExpandAt(InvariantRHS, PHTerm))
244 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified comparison: " << *ICmp <<
'\n');
247 Value *NewICmp = Builder.CreateICmp(InvariantPredicate, NewLHS, NewRHS,
"",
251 DeadInsts.emplace_back(ICmp);
252 RunUnswitching =
true;
258void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp,
259 Instruction *IVOperand) {
260 unsigned IVOperIdx = 0;
262 ICmpInst::Predicate OriginalPred =
Pred;
278 SmallVector<Instruction *, 4>
Users;
279 for (
auto *U : ICmp->
users())
285 DeadInsts.emplace_back(ICmp);
286 LLVM_DEBUG(
dbgs() <<
"INDVARS: Eliminated comparison: " << *ICmp <<
'\n');
292 if (makeIVComparisonInvariant(ICmp, IVOperand)) {
298 if ((ICmpInst::isSigned(OriginalPred) ||
299 (ICmpInst::isUnsigned(OriginalPred) && !ICmp->
hasSameSign())) &&
306 LLVM_DEBUG(
dbgs() <<
"INDVARS: Marking comparison samesign: " << *ICmp
316bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
331 UDiv->setIsExact(SDiv->
isExact());
334 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified sdiv: " << *SDiv <<
'\n');
337 DeadInsts.push_back(SDiv);
345void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
351 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified srem: " << *Rem <<
'\n');
354 DeadInsts.emplace_back(Rem);
358void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
360 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified rem: " << *Rem <<
'\n');
363 DeadInsts.emplace_back(Rem);
366bool SimplifyIndvar::replaceRemWithNumeratorOrZeroUpdateProfiles(
376 if (
L->getExitingBlock() != Latch || !DT->
dominates(
SI.getParent(), Latch))
381 if (
L->getExitingBlock() ==
nullptr ||
L->getExitingBlock() != Latch)
395void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
398 ICmpInst *ICmp =
new ICmpInst(Rem->
getIterator(), ICmpInst::ICMP_EQ,
N,
D);
404 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified rem: " << *Rem <<
'\n');
407 DeadInsts.emplace_back(Rem);
408 if (!replaceRemWithNumeratorOrZeroUpdateProfiles(*Sel))
414void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem,
415 Instruction *IVOperand,
422 bool UsedAsNumerator = IVOperand == NValue;
423 if (!UsedAsNumerator && !IsSigned)
426 const SCEV *
N = SE->
getSCEV(NValue);
435 if (!IsNumeratorNonNegative)
438 const SCEV *
D = SE->
getSCEV(DValue);
441 if (UsedAsNumerator) {
442 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
444 replaceRemWithNumerator(Rem);
451 replaceRemWithNumeratorOrZero(Rem);
461 replaceSRemWithURem(Rem);
464bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
483 for (
auto *U : WO->
users()) {
485 if (EVI->getIndices()[0] == 1)
488 assert(EVI->getIndices()[0] == 0 &&
"Only two possibilities!");
489 EVI->replaceAllUsesWith(NewResult);
496 for (
auto *EVI : ToDelete)
497 EVI->eraseFromParent();
506bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
513 SI->getBinaryOp(),
SI->getLHS(),
SI->getRHS(),
SI->getName(),
SI->getIterator());
519 SI->replaceAllUsesWith(BO);
521 DeadInsts.emplace_back(SI);
526bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
544 Type *IVTy =
IV->getType();
546 const SCEV *TISCEV = SE->
getSCEV(TI);
550 bool DoesSExtCollapse =
false;
551 bool DoesZExtCollapse =
false;
553 DoesSExtCollapse =
true;
555 DoesZExtCollapse =
true;
559 if (!DoesSExtCollapse && !DoesZExtCollapse)
565 for (
auto *U : TI->
users()) {
571 if (!ICI)
return false;
577 if (ICI->
isSigned() && !DoesSExtCollapse)
585 auto CanUseZExt = [&](ICmpInst *ICI) {
590 if (!DoesZExtCollapse)
604 for (
auto *ICI : ICmpUsers) {
605 bool IsSwapped =
L->isLoopInvariant(ICI->
getOperand(0));
608 Value *Ext =
nullptr;
616 if (IsSwapped)
Pred = ICmpInst::getSwappedPredicate(
Pred);
617 if (CanUseZExt(ICI)) {
618 assert(DoesZExtCollapse &&
"Unprofitable zext?");
619 Ext = Builder.CreateZExt(Op1, IVTy,
"zext");
622 assert(DoesSExtCollapse &&
"Unprofitable sext?");
623 Ext = Builder.CreateSExt(Op1, IVTy,
"sext");
629 auto *NewCmp = Builder.CreateICmp(
Pred,
IV, Ext);
631 DeadInsts.emplace_back(ICI);
636 DeadInsts.emplace_back(TI);
643bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
644 Instruction *IVOperand) {
646 eliminateIVComparison(ICmp, IVOperand);
650 bool IsSRem =
Bin->getOpcode() == Instruction::SRem;
651 if (IsSRem ||
Bin->getOpcode() == Instruction::URem) {
652 simplifyIVRemainder(
Bin, IVOperand, IsSRem);
656 if (
Bin->getOpcode() == Instruction::SDiv)
657 return eliminateSDiv(
Bin);
661 if (eliminateOverflowIntrinsic(WO))
665 if (eliminateSaturatingIntrinsic(SI))
669 if (eliminateTrunc(TI))
672 if (eliminateIdentitySCEV(UseInst, IVOperand))
679 if (
auto *BB = L->getLoopPreheader())
680 return BB->getTerminator();
686bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *
I) {
702 if (!
Rewriter.isSafeToExpandAt(S, IP)) {
704 <<
" with non-speculable loop invariant: " << *S <<
'\n');
708 auto *Invariant =
Rewriter.expandCodeFor(S,
I->getType(), IP);
709 bool NeedToEmitLCSSAPhis =
false;
711 NeedToEmitLCSSAPhis =
true;
713 I->replaceAllUsesWith(Invariant);
715 <<
" with loop invariant: " << *S <<
'\n');
717 if (NeedToEmitLCSSAPhis) {
722 <<
" inserting LCSSA Phis" <<
'\n');
726 DeadInsts.emplace_back(
I);
731bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) {
732 if (UseInst->
getOpcode() != CastInst::SIToFP &&
733 UseInst->
getOpcode() != CastInst::UIToFP)
740 if (UseInst->
getOpcode() == CastInst::SIToFP)
745 if (MaskBits <= DestNumSigBits) {
746 for (User *U : UseInst->
users()) {
752 CastInst::CastOps Opcode = CI->getOpcode();
753 if (Opcode != CastInst::FPToSI && Opcode != CastInst::FPToUI)
756 Value *Conv =
nullptr;
757 if (IVOperand->
getType() != CI->getType()) {
764 Conv = Builder.CreateTrunc(IVOperand, CI->getType(), Name +
".trunc");
765 }
else if (Opcode == CastInst::FPToUI ||
766 UseInst->
getOpcode() == CastInst::UIToFP) {
767 Conv = Builder.CreateZExt(IVOperand, CI->getType(), Name +
".zext");
769 Conv = Builder.CreateSExt(IVOperand, CI->getType(), Name +
".sext");
775 DeadInsts.push_back(CI);
777 <<
" with: " << *Conv <<
'\n');
788bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
789 Instruction *IVOperand) {
794 const SCEV *UseSCEV = SE->
getSCEV(UseInst);
795 if (UseSCEV != SE->
getSCEV(IVOperand))
817 if (!DT || !DT->
dominates(IVOperand, UseInst))
825 SmallVector<Instruction *> DropPoisonGeneratingInsts;
829 for (Instruction *
I : DropPoisonGeneratingInsts)
830 I->dropPoisonGeneratingAnnotations();
833 LLVM_DEBUG(
dbgs() <<
"INDVARS: Eliminated identity: " << *UseInst <<
'\n');
839 DeadInsts.emplace_back(UseInst);
843bool SimplifyIndvar::strengthenBinaryOp(BinaryOperator *BO,
844 Instruction *IVOperand) {
846 strengthenOverflowingOperation(BO, IVOperand)) ||
852bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
853 Instruction *IVOperand) {
876bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
877 Instruction *IVOperand) {
878 if (BO->
getOpcode() == Instruction::Shl) {
881 for (
auto *U : BO->
users()) {
901void SimplifyIndvar::pushIVUsers(
902 Instruction *Def, SmallPtrSet<Instruction *, 16> &Simplified,
903 SmallVectorImpl<std::pair<Instruction *, Instruction *>> &SimpleIVUsers) {
904 for (User *U :
Def->users()) {
916 if (!
L->contains(UI))
923 SimpleIVUsers.push_back(std::make_pair(UI, Def));
960void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *
V) {
973 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
975 while (!SimpleIVUsers.
empty()) {
976 std::pair<Instruction*, Instruction*> UseOper =
985 DeadInsts.emplace_back(UseInst);
990 if (UseInst == CurrIV)
continue;
994 if (replaceIVUserWithLoopInvariant(UseInst))
1000 for (Use &U : UseInst->
uses()) {
1002 if (replaceIVUserWithLoopInvariant(User))
1007 for (
unsigned N = 0; IVOperand; ++
N) {
1011 Value *NewOper = foldIVUser(UseInst, IVOperand);
1019 if (eliminateIVUser(UseInst, IVOperand)) {
1020 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
1025 if (strengthenBinaryOp(BO, IVOperand)) {
1028 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
1033 if (replaceFloatIVWithIntegerIV(UseInst)) {
1035 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
1045 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1066 SIV.simplifyUsers(CurrIV, V);
1067 return {SIV.hasChanged(), SIV.runUnswitching()};
1076#if LLVM_ENABLE_ABI_BREAKING_CHECKS
1081 const auto &[
C,
_] =
1104 ScalarEvolution *SE;
1111 bool UsePostIncrementRanges;
1114 unsigned NumElimExt = 0;
1115 unsigned NumWidened = 0;
1118 PHINode *WidePhi =
nullptr;
1120 const SCEV *WideIncExpr =
nullptr;
1121 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
1123 SmallPtrSet<Instruction *,16> Widened;
1131 DenseMap<AssertingVH<Instruction>,
ExtendKind> ExtendKindMap;
1133 using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
1139 DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
1141 std::optional<ConstantRange> getPostIncRangeInfo(
Value *Def,
1142 Instruction *UseI) {
1143 DefUserPair
Key(Def, UseI);
1144 auto It = PostIncRangeInfos.
find(
Key);
1145 return It == PostIncRangeInfos.
end()
1146 ? std::optional<ConstantRange>(std::nullopt)
1147 : std::optional<ConstantRange>(It->second);
1150 void calculatePostIncRanges(PHINode *OrigPhi);
1151 void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
1153 void updatePostIncRangeInfo(
Value *Def, Instruction *UseI, ConstantRange R) {
1154 DefUserPair
Key(Def, UseI);
1157 It->second =
R.intersectWith(It->second);
1164 struct NarrowIVDefUse {
1172 bool NeverNegative =
false;
1174 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
1176 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
1177 NeverNegative(NeverNegative) {}
1180 WidenIV(
const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1181 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1182 bool HasGuards,
bool UsePostIncrementRanges =
true);
1186 unsigned getNumElimExt() {
return NumElimExt; };
1187 unsigned getNumWidened() {
return NumWidened; };
1190 Value *createExtendInst(
Value *NarrowOper,
Type *WideType,
bool IsSigned,
1193 Instruction *cloneIVUser(NarrowIVDefUse DU,
const SCEVAddRecExpr *WideAR);
1194 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1195 const SCEVAddRecExpr *WideAR);
1196 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1200 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1202 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1204 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1206 const SCEV *getSCEVByOpCode(
const SCEV *
LHS,
const SCEV *
RHS,
1207 unsigned OpCode)
const;
1210 PHINode *OrigPhi, PHINode *WidePhi);
1211 void truncateIVUse(NarrowIVDefUse DU);
1213 bool widenLoopCompare(NarrowIVDefUse DU);
1214 bool widenWithVariantUse(NarrowIVDefUse DU);
1216 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1236 for (
unsigned i = 0, e =
PHI->getNumIncomingValues(); i != e; ++i) {
1237 if (
PHI->getIncomingValue(i) != Def)
1262 assert(DT->
dominates(DefI, InsertPt) &&
"def does not dominate all uses");
1267 for (
auto *DTN = (*DT)[InsertPt->
getParent()]; DTN; DTN = DTN->getIDom())
1269 return DTN->getBlock()->getTerminator();
1274WidenIV::WidenIV(
const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1275 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1276 bool HasGuards,
bool UsePostIncrementRanges)
1277 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
1278 L(LI->getLoopFor(OrigPhi->
getParent())), SE(SEv), DT(DTree),
1279 HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges),
1282 ExtendKindMap[OrigPhi] = WI.
IsSigned ? ExtendKind::Sign : ExtendKind::Zero;
1285Value *WidenIV::createExtendInst(
Value *NarrowOper,
Type *WideType,
1291 L &&
L->getLoopPreheader() &&
L->isLoopInvariant(NarrowOper);
1292 L =
L->getParentLoop())
1293 Builder.SetInsertPoint(
L->getLoopPreheader()->getTerminator());
1295 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1296 Builder.CreateZExt(NarrowOper, WideType);
1302Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU,
1303 const SCEVAddRecExpr *WideAR) {
1304 unsigned Opcode = DU.NarrowUse->
getOpcode();
1308 case Instruction::Add:
1309 case Instruction::Mul:
1310 case Instruction::UDiv:
1311 case Instruction::Sub:
1312 return cloneArithmeticIVUser(DU, WideAR);
1314 case Instruction::And:
1315 case Instruction::Or:
1316 case Instruction::Xor:
1317 case Instruction::Shl:
1318 case Instruction::LShr:
1319 case Instruction::AShr:
1320 return cloneBitwiseIVUser(DU);
1324Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) {
1329 LLVM_DEBUG(
dbgs() <<
"Cloning bitwise IVUser: " << *NarrowUse <<
"\n");
1335 bool IsSigned = getExtendKind(NarrowDef) == ExtendKind::Sign;
1338 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1339 IsSigned, NarrowUse);
1342 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1343 IsSigned, NarrowUse);
1349 Builder.Insert(WideBO);
1350 WideBO->copyIRFlags(NarrowBO);
1354Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,
1355 const SCEVAddRecExpr *WideAR) {
1360 LLVM_DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1362 unsigned IVOpIdx = (NarrowUse->
getOperand(0) == NarrowDef) ? 0 : 1;
1373 auto GuessNonIVOperand = [&](
bool SignExt) {
1374 const SCEV *WideLHS;
1375 const SCEV *WideRHS;
1377 auto GetExtend = [
this, SignExt](
const SCEV *S,
Type *Ty) {
1384 WideLHS = SE->
getSCEV(WideDef);
1386 WideRHS = GetExtend(NarrowRHS, WideType);
1389 WideLHS = GetExtend(NarrowLHS, WideType);
1390 WideRHS = SE->
getSCEV(WideDef);
1394 const SCEV *WideUse =
1395 getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->
getOpcode());
1397 return WideUse == WideAR;
1400 bool SignExtend = getExtendKind(NarrowDef) == ExtendKind::Sign;
1401 if (!GuessNonIVOperand(SignExtend)) {
1402 SignExtend = !SignExtend;
1403 if (!GuessNonIVOperand(SignExtend))
1409 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1410 SignExtend, NarrowUse);
1413 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1414 SignExtend, NarrowUse);
1421 Builder.Insert(WideBO);
1422 WideBO->copyIRFlags(NarrowBO);
1426WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *
I) {
1427 auto It = ExtendKindMap.
find(
I);
1428 assert(It != ExtendKindMap.
end() &&
"Instruction not yet extended!");
1432const SCEV *WidenIV::getSCEVByOpCode(
const SCEV *
LHS,
const SCEV *
RHS,
1433 unsigned OpCode)
const {
1435 case Instruction::Add:
1437 case Instruction::Sub:
1439 case Instruction::Mul:
1441 case Instruction::UDiv:
1463 IsNSW = OBO->hasNoSignedWrap();
1464 IsNUW = OBO->hasNoUnsignedWrap();
1469 bool IsNSW =
false,
bool IsNUW =
false)
1470 : Opcode(Opcode),
Operands({
LHS,
RHS}), IsNSW(IsNSW), IsNUW(IsNUW) {}
1476 switch (
Op->getOpcode()) {
1477 case Instruction::Add:
1478 case Instruction::Sub:
1479 case Instruction::Mul:
1481 case Instruction::Or: {
1484 return BinaryOp(Instruction::Add,
Op->getOperand(0),
Op->getOperand(1),
1488 case Instruction::Shl: {
1496 if (SA->getValue().ult(
BitWidth)) {
1501 bool IsNUW =
Op->hasNoUnsignedWrap();
1502 bool IsNSW =
Op->hasNoSignedWrap() &&
1503 (IsNUW || SA->getValue().ult(
BitWidth - 1));
1506 ConstantInt::get(
Op->getContext(),
1508 return BinaryOp(Instruction::Mul,
Op->getOperand(0),
X, IsNSW, IsNUW);
1516 return std::nullopt;
1524WidenIV::WidenedRecTy
1525WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) {
1528 return {
nullptr, ExtendKind::Unknown};
1530 assert((
Op->Opcode == Instruction::Add ||
Op->Opcode == Instruction::Sub ||
1531 Op->Opcode == Instruction::Mul) &&
1532 "Unexpected opcode");
1536 const unsigned ExtendOperIdx =
Op->Operands[0] == DU.NarrowDef ? 1 : 0;
1537 assert(
Op->Operands[1 - ExtendOperIdx] == DU.NarrowDef &&
"bad DU");
1539 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1540 if (!(ExtKind == ExtendKind::Sign &&
Op->IsNSW) &&
1541 !(ExtKind == ExtendKind::Zero &&
Op->IsNUW)) {
1542 ExtKind = ExtendKind::Unknown;
1548 if (DU.NeverNegative) {
1550 ExtKind = ExtendKind::Sign;
1551 }
else if (
Op->IsNUW) {
1552 ExtKind = ExtendKind::Zero;
1557 const SCEV *ExtendOperExpr = SE->
getSCEV(
Op->Operands[ExtendOperIdx]);
1558 if (ExtKind == ExtendKind::Sign)
1560 else if (ExtKind == ExtendKind::Zero)
1563 return {
nullptr, ExtendKind::Unknown};
1570 const SCEV *lhs = SE->
getSCEV(DU.WideDef);
1571 const SCEV *rhs = ExtendOperExpr;
1575 if (ExtendOperIdx == 0)
1577 const SCEVAddRecExpr *AddRec =
1580 if (!AddRec || AddRec->
getLoop() != L)
1581 return {
nullptr, ExtendKind::Unknown};
1583 return {AddRec, ExtKind};
1591WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) {
1593 return {
nullptr, ExtendKind::Unknown};
1595 const SCEV *NarrowExpr = SE->
getSCEV(DU.NarrowUse);
1600 return {
nullptr, ExtendKind::Unknown};
1603 const SCEV *WideExpr;
1605 if (DU.NeverNegative) {
1608 ExtKind = ExtendKind::Sign;
1611 ExtKind = ExtendKind::Zero;
1613 }
else if (getExtendKind(DU.NarrowDef) == ExtendKind::Sign) {
1615 ExtKind = ExtendKind::Sign;
1618 ExtKind = ExtendKind::Zero;
1621 if (!AddRec || AddRec->
getLoop() != L)
1622 return {
nullptr, ExtendKind::Unknown};
1623 return {AddRec, ExtKind};
1628void WidenIV::truncateIVUse(NarrowIVDefUse DU) {
1632 LLVM_DEBUG(
dbgs() <<
"INDVARS: Truncate IV " << *DU.WideDef <<
" for user "
1633 << *DU.NarrowUse <<
"\n");
1634 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1637 Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType(),
"",
1638 DU.NeverNegative || ExtKind == ExtendKind::Zero,
1639 DU.NeverNegative || ExtKind == ExtendKind::Sign);
1640 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef,
Trunc);
1646bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) {
1665 bool IsSigned = getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1666 bool CmpPreferredSign =
Cmp->hasSameSign() ? IsSigned :
Cmp->isSigned();
1667 if (!DU.NeverNegative && IsSigned != CmpPreferredSign)
1670 Value *
Op =
Cmp->getOperand(
Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1673 assert(CastWidth <= IVWidth &&
"Unexpected width while widening compare.");
1679 if (CastWidth < IVWidth) {
1684 CmpPreferredSign =
true;
1686 Value *ExtOp = createExtendInst(
Op, WideType, CmpPreferredSign, Cmp);
1712bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) {
1720 if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1721 OpCode != Instruction::Mul)
1730 const OverflowingBinaryOperator *OBO =
1732 ExtendKind ExtKind = getExtendKind(NarrowDef);
1733 bool CanSignExtend = ExtKind == ExtendKind::Sign && OBO->
hasNoSignedWrap();
1735 auto AnotherOpExtKind = ExtKind;
1742 SmallVector<Instruction *, 4> ExtUsers;
1745 for (Use &U : NarrowUse->
uses()) {
1747 if (User == NarrowDef)
1749 if (!
L->contains(User)) {
1753 if (LCSSAPhi->getNumOperands() != 1)
1764 if (ExtKind == ExtendKind::Zero && ICmpInst::isSigned(
Pred))
1766 if (ExtKind == ExtendKind::Sign && ICmpInst::isUnsigned(
Pred))
1771 if (ExtKind == ExtendKind::Sign)
1775 if (!User ||
User->getType() != WideType)
1779 if (ExtUsers.
empty()) {
1789 if (!CanSignExtend && !CanZeroExtend) {
1792 if (OpCode != Instruction::Add)
1794 if (ExtKind != ExtendKind::Zero)
1812 AnotherOpExtKind = ExtendKind::Sign;
1816 const SCEV *Op1 = SE->
getSCEV(WideDef);
1818 if (!AddRecOp1 || AddRecOp1->
getLoop() != L)
1821 LLVM_DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1827 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1828 AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1832 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1833 AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1839 Builder.Insert(WideBO);
1840 WideBO->copyIRFlags(NarrowBO);
1841 ExtendKindMap[NarrowUse] = ExtKind;
1843 for (Instruction *User : ExtUsers) {
1844 assert(
User->getType() == WideType &&
"Checked before!");
1845 LLVM_DEBUG(
dbgs() <<
"INDVARS: eliminating " << *User <<
" replaced by "
1846 << *WideBO <<
"\n");
1848 User->replaceAllUsesWith(WideBO);
1852 for (PHINode *User : LCSSAPhiUsers) {
1853 assert(
User->getNumOperands() == 1 &&
"Checked before!");
1854 Builder.SetInsertPoint(User);
1856 Builder.CreatePHI(WideBO->getType(), 1,
User->getName() +
".wide");
1857 BasicBlock *LoopExitingBlock =
User->getParent()->getSinglePredecessor();
1858 assert(LoopExitingBlock &&
L->contains(LoopExitingBlock) &&
1859 "Not a LCSSA Phi?");
1860 WidePN->addIncoming(WideBO, LoopExitingBlock);
1861 Builder.SetInsertPoint(
User->getParent()->getFirstInsertionPt());
1862 auto *TruncPN = Builder.CreateTrunc(WidePN,
User->getType());
1863 User->replaceAllUsesWith(TruncPN);
1867 for (ICmpInst *User : ICmpUsers) {
1868 Builder.SetInsertPoint(User);
1872 if (ExtKind == ExtendKind::Zero)
1873 return Builder.CreateZExt(
V, WideBO->getType());
1875 return Builder.CreateSExt(
V, WideBO->getType());
1878 auto *
LHS = ExtendedOp(
User->getOperand(0));
1879 auto *
RHS = ExtendedOp(
User->getOperand(1));
1882 User->replaceAllUsesWith(WideCmp);
1891Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU,
1892 SCEVExpander &
Rewriter, PHINode *OrigPhi,
1895 "Should already know the kind of extension used to widen NarrowDef");
1899 bool CanWidenBySExt =
1900 DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1901 bool CanWidenByZExt =
1902 DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Zero;
1906 if (LI->
getLoopFor(UsePhi->getParent()) != L) {
1910 if (UsePhi->getNumOperands() != 1)
1921 UsePhi->getIterator());
1922 WidePhi->
addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1926 CanWidenByZExt, CanWidenBySExt);
1927 UsePhi->replaceAllUsesWith(
Trunc);
1929 LLVM_DEBUG(
dbgs() <<
"INDVARS: Widen lcssa phi " << *UsePhi <<
" to "
1930 << *WidePhi <<
"\n");
1939 Value *NewDef = DU.WideDef;
1940 if (DU.NarrowUse->
getType() != WideType) {
1943 if (CastWidth < IVWidth) {
1946 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->
getType(),
"",
1947 CanWidenByZExt, CanWidenBySExt);
1954 <<
" not wide enough to subsume " << *DU.NarrowUse
1957 NewDef = DU.NarrowUse;
1960 if (NewDef != DU.NarrowUse) {
1962 <<
" replaced by " << *DU.WideDef <<
"\n");
1977 auto tryAddRecExpansion = [&]() -> Instruction* {
1979 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1980 if (!WideAddRec.first)
1981 WideAddRec = getWideRecurrence(DU);
1982 assert((WideAddRec.first ==
nullptr) ==
1983 (WideAddRec.second == ExtendKind::Unknown));
1984 if (!WideAddRec.first)
1987 auto CanUseWideInc = [&]() {
1994 bool NeedToRecomputeFlags =
1996 OrigPhi, WidePhi, DU.NarrowUse, WideInc) ||
1999 return WideAddRec.first == WideIncExpr &&
2000 Rewriter.hoistIVInc(WideInc, DU.NarrowUse, NeedToRecomputeFlags);
2004 if (CanUseWideInc())
2007 WideUse = cloneIVUser(DU, WideAddRec.first);
2016 if (WideAddRec.first != SE->
getSCEV(WideUse)) {
2017 LLVM_DEBUG(
dbgs() <<
"Wide use expression mismatch: " << *WideUse <<
": "
2018 << *SE->
getSCEV(WideUse) <<
" != " << *WideAddRec.first
2028 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
2033 if (
auto *
I = tryAddRecExpansion())
2038 if (widenLoopCompare(DU))
2046 if (widenWithVariantUse(DU))
2057void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
2058 const SCEV *NarrowSCEV = SE->
getSCEV(NarrowDef);
2059 bool NonNegativeDef =
2062 for (User *U : NarrowDef->
users()) {
2066 if (!Widened.
insert(NarrowUser).second)
2069 bool NonNegativeUse =
false;
2070 if (!NonNegativeDef) {
2072 if (
auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
2073 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
2076 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
2077 NonNegativeDef || NonNegativeUse);
2089PHINode *WidenIV::createWideIV(SCEVExpander &
Rewriter) {
2096 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == ExtendKind::Sign
2101 "Expect the new IV expression to preserve its type");
2105 if (!AddRec || AddRec->
getLoop() != L)
2114 "Loop header phi recurrence inputs do not dominate the loop");
2126 if (UsePostIncrementRanges)
2127 calculatePostIncRanges(OrigPhi);
2133 Instruction *InsertPt = &*
L->getHeader()->getFirstInsertionPt();
2134 Value *ExpandInst =
Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
2151 if (BasicBlock *LatchBlock =
L->getLoopLatch()) {
2155 WideIncExpr = SE->
getSCEV(WideInc);
2172 OrigInc, WideInc) &&
2176 OrigInc->hasNoUnsignedWrap());
2178 OrigInc->hasNoSignedWrap());
2187 assert(Widened.
empty() && NarrowIVUsers.empty() &&
"expect initial state" );
2190 pushNarrowIVUsers(OrigPhi, WidePhi);
2192 while (!NarrowIVUsers.empty()) {
2193 WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
2201 pushNarrowIVUsers(DU.NarrowUse, WideUse);
2216void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
2217 Instruction *NarrowUser) {
2218 Value *NarrowDefLHS;
2219 const APInt *NarrowDefRHS;
2225 auto UpdateRangeFromCondition = [&](
Value *Condition,
bool TrueDest) {
2235 auto CmpConstrainedLHSRange =
2237 auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
2240 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
2243 auto UpdateRangeFromGuards = [&](
Instruction *Ctx) {
2247 for (Instruction &
I :
make_range(Ctx->getIterator().getReverse(),
2248 Ctx->getParent()->rend())) {
2251 UpdateRangeFromCondition(
C,
true);
2255 UpdateRangeFromGuards(NarrowUser);
2263 for (
auto *DTB = (*DT)[NarrowUserBB]->getIDom();
2264 L->contains(DTB->getBlock());
2265 DTB = DTB->getIDom()) {
2266 auto *BB = DTB->getBlock();
2267 auto *TI = BB->getTerminator();
2268 UpdateRangeFromGuards(TI);
2274 auto *TrueSuccessor = BI->getSuccessor(0);
2275 auto *FalseSuccessor = BI->getSuccessor(1);
2277 if (DT->
dominates(BasicBlockEdge(BB, TrueSuccessor), NarrowUserBB))
2278 UpdateRangeFromCondition(BI->getCondition(),
true);
2280 if (DT->
dominates(BasicBlockEdge(BB, FalseSuccessor), NarrowUserBB))
2281 UpdateRangeFromCondition(BI->getCondition(),
false);
2286void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
2287 SmallPtrSet<Instruction *, 16> Visited;
2292 while (!Worklist.
empty()) {
2295 for (Use &U : NarrowDef->
uses()) {
2299 auto *NarrowUserLoop = (*LI)[NarrowUser->
getParent()];
2300 if (!NarrowUserLoop || !
L->contains(NarrowUserLoop))
2303 if (!Visited.
insert(NarrowUser).second)
2308 calculatePostIncRange(NarrowDef, NarrowUser);
2316 unsigned &NumElimExt,
unsigned &NumWidened,
2317 bool HasGuards,
bool UsePostIncrementRanges) {
2318 WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
2319 PHINode *WidePHI = Widener.createWideIV(Rewriter);
2320 NumElimExt = Widener.getNumElimExt();
2321 NumWidened = Widener.getNumWidened();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
iv Induction Variable Users
This file contains the declarations for profiling metadata utility functions.
static Instruction * GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint)
static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE)
Return true if this instruction generates a simple SCEV expression in terms of that IV.
static Instruction * findCommonDominator(ArrayRef< Instruction * > Instructions, DominatorTree &DT)
Find a point in code which dominates all given instructions.
static Instruction * getInsertPointForUses(Instruction *User, Value *Def, DominatorTree *DT, LoopInfo *LI)
Determine the insertion point for this user.
static std::optional< BinaryOp > matchBinaryOp(Instruction *Op)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
virt reg Virtual Register Rewriter
static const uint32_t IV[8]
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
LLVM_ABI bool isSigned() const
Whether the intrinsic is signed or unsigned.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Predicate getPredicate() const
Return the predicate for this instruction.
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
LLVM_ABI unsigned getActiveBits() const
Compute the maximal number of active bits needed to represent every value in this range.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
static DebugLoc getDropped()
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
bool hasSameSign() const
An icmp instruction, which can be marked as "samesign", indicating that the two operands have the sam...
void setSameSign(bool B=true)
CmpPredicate getCmpPredicate() const
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
Interface for visiting interesting IV users that are recognized but not simplified by this utility.
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Represents a single loop in the control flow graph.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This node represents a polynomial recurrence on the trip count of the specified loop.
const Loop * getLoop() const
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class uses information about analyze scalars to rewrite expressions in canonical form.
static LLVM_ABI bool canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi, PHINode *WidePhi, Instruction *OrigInc, Instruction *WideInc)
Return true if both increments directly increment the corresponding IV PHI nodes and have the same op...
This class represents an analyzed expression in the program.
static constexpr auto FlagNUW
static constexpr auto FlagNSW
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI std::optional< SCEVFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
The instances of the Type class are immutable: once they are created, they are never changed.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
@ User
could "use" a pointer
NodeAddr< DefNode * > Def
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
@ Unknown
Not known to have no common set bits.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
@ BinaryOp
One of the operands is a binary op.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI PHINode * createWideIV(const WideIVInfo &WI, LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, unsigned &NumElimExt, unsigned &NumWidened, bool HasGuards, bool UsePostIncrementRanges)
Widen Induction Variables - Extend the width of an IV to cover its widest uses.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
LLVM_ABI bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
LLVM_ABI std::pair< bool, bool > simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead, SCEVExpander &Rewriter, IVVisitor *V=nullptr)
simplifyUsersOfIV - Simplify instructions that use this induction variable by using ScalarEvolution t...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Collect information about induction variables that are used by sign/zero extend operations.