58 #define DEBUG_TYPE "indvars"
60 STATISTIC(NumWidened ,
"Number of indvars widened");
61 STATISTIC(NumReplaced ,
"Number of exit values replaced");
62 STATISTIC(NumLFTR ,
"Number of loop exit tests replaced");
63 STATISTIC(NumElimExt ,
"Number of IV sign/zero extends eliminated");
64 STATISTIC(NumElimIV ,
"Number of congruent IVs eliminated");
71 cl::desc(
"Verify the ScalarEvolution result after running indvars"));
77 cl::desc(
"Choose the strategy to replace exit value in IndVarSimplify"),
80 "only replace exit value when the cost is cheap"),
82 "always replace exit value whenever possible")));
86 cl::desc(
"Use post increment control-dependent ranges in IndVarSimplify"),
91 cl::desc(
"Disable Linear Function Test Replace optimization"));
96 class IndVarSimplify {
105 bool Changed =
false;
107 bool isValidRewrite(
Value *FromVal,
Value *ToVal);
110 void rewriteNonIntegerIVs(
Loop *
L);
116 void rewriteFirstIterationLoopExitValues(
Loop *
L);
118 Value *linearFunctionTestReplace(
Loop *
L,
const SCEV *BackedgeTakenCount,
121 void sinkUnusedInvariants(
Loop *
L);
130 : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
140 bool IndVarSimplify::isValidRewrite(
Value *FromVal,
Value *ToVal) {
151 Value *FromPtr = FromVal;
152 Value *ToPtr = ToVal;
153 if (
auto *
GEP = dyn_cast<GEPOperator>(FromVal)) {
154 FromPtr =
GEP->getPointerOperand();
156 if (
auto *
GEP = dyn_cast<GEPOperator>(ToVal)) {
157 ToPtr =
GEP->getPointerOperand();
159 if (FromPtr != FromVal || ToPtr != ToVal) {
161 if (FromPtr == ToPtr)
175 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
176 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
177 if (FromBase == ToBase)
180 DEBUG(
dbgs() <<
"INDVARS: GEP rewrite bail out "
181 << *FromBase <<
" != " << *ToBase <<
"\n");
211 assert(InsertPt &&
"Missing phi operand");
217 assert(DT->
dominates(DefI, InsertPt) &&
"def does not dominate all uses");
222 for (
auto *DTN = (*DT)[InsertPt->
getParent()]; DTN; DTN = DTN->getIDom())
224 return DTN->getBlock()->getTerminator();
235 bool isExact =
false;
255 void IndVarSimplify::handleFloatingPointIV(
Loop *
L,
PHINode *PN) {
257 unsigned BackEdge = IncomingEdge^1;
263 if (!InitValueVal || !
ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
269 if (Incr ==
nullptr || Incr->getOpcode() != Instruction::FAdd)
return;
275 if (IncValueVal ==
nullptr || Incr->
getOperand(0) != PN ||
283 if (IncrUse == Incr->user_end())
return;
285 if (IncrUse != Incr->user_end())
return;
313 if (ExitValueVal ==
nullptr ||
353 if (InitValue >= ExitValue)
360 if (++Range == 0)
return;
363 unsigned Leftover = Range %
uint32_t(IncValue);
374 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
380 if (InitValue <= ExitValue)
387 if (++Range == 0)
return;
390 unsigned Leftover = Range %
uint32_t(-IncValue);
401 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
451 void IndVarSimplify::rewriteNonIntegerIVs(
Loop *L) {
463 for (
unsigned i = 0, e = PHIs.
size(); i != e; ++i)
464 if (
PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
465 handleFloatingPointIV(L, PN);
484 : PN(P), Ith(I), Val(V), HighCost(H) {}
494 if (ExistingValue->getType() == ResultTy)
495 return ExistingValue;
516 void IndVarSimplify::rewriteLoopExitValues(
Loop *L,
SCEVExpander &Rewriter) {
519 "Indvars did not preserve LCSSA!");
538 while ((PN = dyn_cast<PHINode>(BBI++))) {
542 if (!SE->isSCEVable(PN->
getType()))
553 for (
unsigned i = 0; i != NumPreds; ++i) {
557 if (!isa<Instruction>(InVal))
573 if (!SE->isLoopInvariant(ExitValue, L) ||
583 unsigned NumHardInternalUses = 0;
584 unsigned NumSoftExternalUses = 0;
585 unsigned NumUses = 0;
587 IB !=
IE && NumUses <= 6; ++IB) {
593 NumHardInternalUses++;
595 if (Opc == Instruction::PHI) {
601 PB != PE && NumUses <= 6; ++PB, ++NumUses) {
602 unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
604 NumSoftExternalUses++;
609 NumSoftExternalUses++;
612 if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
618 expandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->
getType());
620 DEBUG(
dbgs() <<
"INDVARS: RLEV: AfterLoopVal = " << *ExitVal <<
'\n'
621 <<
" LoopVal = " << *Inst <<
"\n");
623 if (!isValidRewrite(Inst, ExitVal)) {
624 DeadInsts.push_back(ExitVal);
634 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
637 for (
const RewritePhi &Phi : RewritePhiSet) {
639 Value *ExitVal = Phi.Val;
644 DeadInsts.push_back(ExitVal);
656 DeadInsts.push_back(Inst);
660 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
680 void IndVarSimplify::rewriteFirstIterationLoopExitValues(
Loop *L) {
687 assert(LoopHeader &&
"Invalid loop");
689 for (
auto *ExitBB : ExitBlocks) {
693 while (
auto *PN = dyn_cast<PHINode>(BBI++)) {
695 IncomingValIdx !=
E; ++IncomingValIdx) {
702 if (IncomingBB != LoopHeader)
708 Value *Cond =
nullptr;
709 if (
auto *BI = dyn_cast<BranchInst>(TermInst)) {
712 Cond = BI->getCondition();
713 }
else if (
auto *SI = dyn_cast<SwitchInst>(TermInst))
714 Cond =
SI->getCondition();
732 assert(LoopPreheader &&
"Invalid loop");
733 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
734 if (PreheaderIdx != -1) {
735 assert(ExitVal->getParent() == LoopHeader &&
736 "ExitVal must be in loop header");
738 ExitVal->getIncomingValue(PreheaderIdx));
748 bool IndVarSimplify::canLoopBeDeleted(
764 if (ExitBlocks.
size() > 1 || ExitingBlocks.
size() > 1)
769 while (
PHINode *
P = dyn_cast<PHINode>(BI)) {
770 Value *Incoming =
P->getIncomingValueForBlock(ExitingBlocks[0]);
776 for (
const RewritePhi &Phi : RewritePhiSet) {
777 unsigned i = Phi.Ith;
778 if (Phi.PN ==
P && (Phi.PN)->getIncomingValue(i) == Incoming) {
785 if (!found && (I = dyn_cast<Instruction>(Incoming)))
792 for (
auto *BB : L->
blocks())
809 Type *WidestNativeType =
nullptr;
810 bool IsSigned =
false;
819 bool IsSigned = Cast->
getOpcode() == Instruction::SExt;
820 if (!IsSigned && Cast->
getOpcode() != Instruction::ZExt)
833 if (NarrowIVWidth >= Width)
849 if (!WI.WidestNativeType) {
851 WI.IsSigned = IsSigned;
856 if (WI.IsSigned != IsSigned)
868 struct NarrowIVDefUse {
876 bool NeverNegative =
false;
880 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
881 NeverNegative(NeverNegative) {}
907 const SCEV *WideIncExpr;
913 enum ExtendKind { ZeroExtended, SignExtended,
Unknown };
929 DefUserPair Key(Def, UseI);
930 auto It = PostIncRangeInfos.find(Key);
931 return It == PostIncRangeInfos.end()
936 void calculatePostIncRanges(
PHINode *OrigPhi);
939 DefUserPair Key(Def, UseI);
940 auto It = PostIncRangeInfos.find(Key);
941 if (It == PostIncRangeInfos.end())
942 PostIncRangeInfos.insert({Key, R});
951 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
952 L(LI->getLoopFor(OrigPhi->
getParent())), SE(SEv), DT(DTree),
953 HasGuards(HasGuards), WidePhi(nullptr), WideInc(nullptr),
954 WideIncExpr(nullptr), DeadInsts(DI) {
956 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
962 Value *createExtendInst(
Value *NarrowOper,
Type *WideType,
bool IsSigned,
966 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
968 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
972 typedef std::pair<const SCEVAddRecExpr *, ExtendKind> WidenedRecTy;
974 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
976 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
978 const SCEV *getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
979 unsigned OpCode)
const;
983 bool widenLoopCompare(NarrowIVDefUse DU);
1000 Value *WidenIV::createExtendInst(
Value *NarrowOper,
Type *WideType,
1010 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1011 Builder.CreateZExt(NarrowOper, WideType);
1017 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1019 unsigned Opcode = DU.NarrowUse->getOpcode();
1024 case Instruction::Mul:
1025 case Instruction::UDiv:
1026 case Instruction::Sub:
1027 return cloneArithmeticIVUser(DU, WideAR);
1029 case Instruction::And:
1030 case Instruction::Or:
1031 case Instruction::Xor:
1032 case Instruction::Shl:
1033 case Instruction::LShr:
1034 case Instruction::AShr:
1035 return cloneBitwiseIVUser(DU);
1039 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1044 DEBUG(
dbgs() <<
"Cloning bitwise IVUser: " << *NarrowUse <<
"\n");
1050 bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1053 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1054 IsSigned, NarrowUse);
1057 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1058 IsSigned, NarrowUse);
1060 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1061 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1064 Builder.Insert(WideBO);
1065 WideBO->copyIRFlags(NarrowBO);
1069 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1075 DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1077 unsigned IVOpIdx = (NarrowUse->
getOperand(0) == NarrowDef) ? 0 : 1;
1088 auto GuessNonIVOperand = [&](
bool SignExt) {
1089 const SCEV *WideLHS;
1090 const SCEV *WideRHS;
1092 auto GetExtend = [
this, SignExt](
const SCEV *S,
Type *Ty) {
1094 return SE->getSignExtendExpr(S, Ty);
1095 return SE->getZeroExtendExpr(S, Ty);
1099 WideLHS = SE->getSCEV(WideDef);
1101 WideRHS = GetExtend(NarrowRHS, WideType);
1104 WideLHS = GetExtend(NarrowLHS, WideType);
1105 WideRHS = SE->getSCEV(WideDef);
1109 const SCEV *WideUse =
nullptr;
1116 WideUse = SE->getAddExpr(WideLHS, WideRHS);
1119 case Instruction::Mul:
1120 WideUse = SE->getMulExpr(WideLHS, WideRHS);
1123 case Instruction::UDiv:
1124 WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1127 case Instruction::Sub:
1128 WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1132 return WideUse == WideAR;
1135 bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1136 if (!GuessNonIVOperand(SignExtend)) {
1137 SignExtend = !SignExtend;
1138 if (!GuessNonIVOperand(SignExtend))
1144 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1145 SignExtend, NarrowUse);
1148 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1149 SignExtend, NarrowUse);
1151 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1152 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1156 Builder.Insert(WideBO);
1157 WideBO->copyIRFlags(NarrowBO);
1161 WidenIV::ExtendKind WidenIV::getExtendKind(
Instruction *I) {
1162 auto It = ExtendKindMap.find(I);
1163 assert(It != ExtendKindMap.end() &&
"Instruction not yet extended!");
1167 const SCEV *WidenIV::getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
1168 unsigned OpCode)
const {
1170 return SE->getAddExpr(LHS, RHS);
1171 if (OpCode == Instruction::Sub)
1172 return SE->getMinusSCEV(LHS, RHS);
1173 if (OpCode == Instruction::Mul)
1174 return SE->getMulExpr(LHS, RHS);
1184 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1187 const unsigned OpCode = DU.NarrowUse->getOpcode();
1190 OpCode != Instruction::Mul)
1195 const unsigned ExtendOperIdx =
1196 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1197 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef &&
"bad DU");
1199 const SCEV *ExtendOperExpr =
nullptr;
1201 cast<OverflowingBinaryOperator>(DU.NarrowUse);
1202 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1204 ExtendOperExpr = SE->getSignExtendExpr(
1205 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1207 ExtendOperExpr = SE->getZeroExtendExpr(
1208 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1217 const SCEV *lhs = SE->getSCEV(DU.WideDef);
1218 const SCEV *rhs = ExtendOperExpr;
1222 if (ExtendOperIdx == 0)
1227 if (!AddRec || AddRec->
getLoop() !=
L)
1230 return {AddRec, ExtKind};
1238 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1239 if (!SE->isSCEVable(DU.NarrowUse->getType()))
1242 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1243 if (SE->getTypeSizeInBits(NarrowExpr->
getType()) >=
1244 SE->getTypeSizeInBits(WideType)) {
1250 const SCEV *WideExpr;
1252 if (DU.NeverNegative) {
1253 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1254 if (isa<SCEVAddRecExpr>(WideExpr))
1255 ExtKind = SignExtended;
1257 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1258 ExtKind = ZeroExtended;
1260 }
else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1261 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1262 ExtKind = SignExtended;
1264 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1265 ExtKind = ZeroExtended;
1268 if (!AddRec || AddRec->
getLoop() !=
L)
1270 return {AddRec, ExtKind};
1276 DEBUG(
dbgs() <<
"INDVARS: Truncate IV " << *DU.WideDef
1277 <<
" for user " << *DU.NarrowUse <<
"\n");
1281 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1287 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1306 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1307 if (!(DU.NeverNegative || IsSigned == Cmp->
isSigned()))
1311 unsigned CastWidth = SE->getTypeSizeInBits(Op->
getType());
1312 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1313 assert (CastWidth <= IVWidth &&
"Unexpected width while widening compare.");
1318 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1321 if (CastWidth < IVWidth) {
1322 Value *ExtOp = createExtendInst(Op, WideType, Cmp->
isSigned(), Cmp);
1323 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1331 assert(ExtendKindMap.count(DU.NarrowDef) &&
1332 "Should already know the kind of extension used to widen NarrowDef");
1335 if (
PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1336 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1340 if (UsePhi->getNumOperands() != 1)
1346 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1350 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() +
".wide",
1352 WidePhi->
addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1354 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1356 DeadInsts.emplace_back(UsePhi);
1357 DEBUG(
dbgs() <<
"INDVARS: Widen lcssa phi " << *UsePhi
1358 <<
" to " << *WidePhi <<
"\n");
1366 auto canWidenBySExt = [&]() {
1367 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1369 auto canWidenByZExt = [&]() {
1370 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1374 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1375 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1376 Value *NewDef = DU.WideDef;
1377 if (DU.NarrowUse->getType() != WideType) {
1378 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1379 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1380 if (CastWidth < IVWidth) {
1383 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1389 DEBUG(
dbgs() <<
"INDVARS: New IV " << *WidePhi
1390 <<
" not wide enough to subsume " << *DU.NarrowUse <<
"\n");
1391 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1392 NewDef = DU.NarrowUse;
1395 if (NewDef != DU.NarrowUse) {
1396 DEBUG(
dbgs() <<
"INDVARS: eliminating " << *DU.NarrowUse
1397 <<
" replaced by " << *DU.WideDef <<
"\n");
1399 DU.NarrowUse->replaceAllUsesWith(NewDef);
1400 DeadInsts.emplace_back(DU.NarrowUse);
1413 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1414 if (!WideAddRec.first)
1415 WideAddRec = getWideRecurrence(DU);
1417 assert((WideAddRec.first ==
nullptr) == (WideAddRec.second ==
Unknown));
1418 if (!WideAddRec.first) {
1421 if (widenLoopCompare(DU))
1432 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1433 "SCEV is not expected to evaluate a block terminator");
1438 if (WideAddRec.first == WideIncExpr &&
1442 WideUse = cloneIVUser(DU, WideAddRec.first);
1451 if (WideAddRec.first != SE->getSCEV(WideUse)) {
1452 DEBUG(
dbgs() <<
"Wide use expression mismatch: " << *WideUse
1453 <<
": " << *SE->getSCEV(WideUse) <<
" != " << *WideAddRec.first <<
"\n");
1454 DeadInsts.emplace_back(WideUse);
1458 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1466 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1467 bool NonNegativeDef =
1468 SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1469 SE->getConstant(NarrowSCEV->
getType(), 0));
1474 if (!Widened.insert(NarrowUser).second)
1477 bool NonNegativeUse =
false;
1478 if (!NonNegativeDef) {
1480 if (
auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1481 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1484 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1485 NonNegativeDef || NonNegativeUse);
1505 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1506 ? SE->getSignExtendExpr(AddRec, WideType)
1507 : SE->getZeroExtendExpr(AddRec, WideType);
1509 assert(SE->getEffectiveSCEVType(WideIVExpr->
getType()) == WideType &&
1510 "Expect the new IV expression to preserve its type");
1514 if (!AddRec || AddRec->
getLoop() !=
L)
1523 "Loop header phi recurrence inputs do not dominate the loop");
1536 calculatePostIncRanges(OrigPhi);
1543 WidePhi = cast<PHINode>(Rewriter.
expandCodeFor(AddRec, WideType, InsertPt));
1552 WideIncExpr = SE->getSCEV(WideInc);
1556 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1560 DEBUG(
dbgs() <<
"Wide IV: " << *WidePhi <<
"\n");
1564 assert(Widened.empty() && NarrowIVUsers.empty() &&
"expect initial state" );
1566 Widened.insert(OrigPhi);
1567 pushNarrowIVUsers(OrigPhi, WidePhi);
1569 while (!NarrowIVUsers.empty()) {
1570 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1578 pushNarrowIVUsers(DU.NarrowUse, WideUse);
1581 if (DU.NarrowDef->use_empty())
1582 DeadInsts.emplace_back(DU.NarrowDef);
1589 void WidenIV::calculatePostIncRange(
Instruction *NarrowDef,
1591 using namespace llvm::PatternMatch;
1593 Value *NarrowDefLHS;
1594 const APInt *NarrowDefRHS;
1597 !NarrowDefRHS->isNonNegative())
1600 auto UpdateRangeFromCondition = [&] (
Value *Condition,
1611 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1612 auto CmpConstrainedLHSRange =
1614 auto NarrowDefRange =
1615 CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS);
1617 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1620 auto UpdateRangeFromGuards = [&](
Instruction *Ctx) {
1625 Ctx->getParent()->rend())) {
1627 if (
match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
m_Value(C))))
1628 UpdateRangeFromCondition(C,
true);
1632 UpdateRangeFromGuards(NarrowUser);
1637 if (!DT->isReachableFromEntry(NarrowUserBB))
1640 for (
auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1642 DTB = DTB->getIDom()) {
1643 auto *BB = DTB->getBlock();
1645 UpdateRangeFromGuards(TI);
1648 if (!BI || !BI->isConditional())
1651 auto *TrueSuccessor = BI->getSuccessor(0);
1652 auto *FalseSuccessor = BI->getSuccessor(1);
1654 auto DominatesNarrowUser = [
this, NarrowUser] (
BasicBlockEdge BBE) {
1655 return BBE.isSingleEdge() &&
1656 DT->dominates(BBE, NarrowUser->
getParent());
1660 UpdateRangeFromCondition(BI->getCondition(),
true);
1663 UpdateRangeFromCondition(BI->getCondition(),
false);
1668 void WidenIV::calculatePostIncRanges(
PHINode *OrigPhi) {
1674 while (!Worklist.
empty()) {
1677 for (Use &U : NarrowDef->
uses()) {
1678 auto *NarrowUser = cast<Instruction>(U.getUser());
1681 auto *NarrowUserLoop = (*LI)[NarrowUser->
getParent()];
1682 if (!NarrowUserLoop || !L->
contains(NarrowUserLoop))
1685 if (!Visited.
insert(NarrowUser).second)
1690 calculatePostIncRange(NarrowDef, NarrowUser);
1705 class IndVarSimplifyVisitor :
public IVVisitor {
1716 : SE(SCEV), TTI(TTI), IVPhi(IV) {
1718 WI.NarrowIV = IVPhi;
1732 void IndVarSimplify::simplifyAndExtend(
Loop *L,
1737 auto *GuardDecl = L->
getBlocks()[0]->getModule()->getFunction(
1739 bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1749 while (!LoopPhis.
empty()) {
1760 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1764 if (Visitor.WI.WidestNativeType) {
1767 }
while(!LoopPhis.
empty());
1770 WidenIV Widener(WideIVs.
back(), LI, SE, DT, DeadInsts, HasGuards);
1771 if (
PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1799 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1800 BackedgeTakenCount->
isZero())
1824 case Instruction::Sub:
1826 case Instruction::GetElementPtr:
1841 if (IncI->
getOpcode() == Instruction::GetElementPtr)
1863 assert(BI &&
"expected exit branch");
1878 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1912 if (isa<Constant>(V))
1913 return !isa<UndefValue>(V);
1930 if (!Visited.
insert(Op).second)
1956 if (U != Cond && U != IncV)
return false;
1959 if (U != Cond && U != Phi)
return false;
1981 cast<BranchInst>(L->
getExitingBlock()->getTerminator())->getCondition();
1985 const SCEV *BestInit =
nullptr;
1987 assert(LatchBlock &&
"needsLFTR should guarantee a loop latch");
2011 if (!Step || !Step->
isOne())
2034 if (BestPhi && !
AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2048 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->
getType()))
2081 "Computed iteration count is not loop invariant!");
2090 cast<PointerType>(GEPBase->
getType())
2091 ->getElementType())->isOne() &&
2092 "unit stride pointer IV must be i8*");
2095 return Builder.
CreateGEP(
nullptr, GEPBase, GEPOffset,
"lftr.limit");
2108 const SCEV *IVLimit =
nullptr;
2128 "Computed iteration count is not loop invariant!");
2143 Value *IndVarSimplify::
2144 linearFunctionTestReplace(
Loop *L,
2145 const SCEV *BackedgeTakenCount,
2151 Value *CmpIndVar = IndVar;
2152 const SCEV *IVCount = BackedgeTakenCount;
2163 IVCount = SE->getAddExpr(BackedgeTakenCount,
2164 SE->getOne(BackedgeTakenCount->
getType()));
2174 "genLoopLimit missed a cast");
2179 if (L->
contains(BI->getSuccessor(0)))
2180 P = ICmpInst::ICMP_NE;
2182 P = ICmpInst::ICMP_EQ;
2184 DEBUG(
dbgs() <<
"INDVARS: Rewriting loop exit condition to:\n"
2185 <<
" LHS:" << *CmpIndVar <<
'\n'
2187 << (P == ICmpInst::ICMP_NE ?
"!=" :
"==") <<
"\n"
2188 <<
" RHS:\t" << *ExitCnt <<
"\n"
2189 <<
" IVCount:\t" << *IVCount <<
"\n");
2195 if (
auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2196 Builder.SetCurrentDebugLocation(Cond->getDebugLoc());
2200 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->
getType());
2201 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->
getType());
2202 if (CmpIndVarSize > ExitCntSize) {
2203 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2207 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
2208 const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
2209 APInt Count = cast<SCEVConstant>(IVCount)->getAPInt();
2212 if (IVCount != BackedgeTakenCount && Count == 0) {
2217 Count = Count.
zext(CmpIndVarSize);
2219 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2220 NewLimit = Start - Count;
2222 NewLimit = Start + Count;
2223 ExitCnt = ConstantInt::get(CmpIndVar->
getType(), NewLimit);
2225 DEBUG(
dbgs() <<
" Widen RHS:\t" << *ExitCnt <<
"\n");
2231 bool Extended =
false;
2232 const SCEV *IV = SE->getSCEV(CmpIndVar);
2233 const SCEV *ZExtTrunc =
2234 SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2238 if (ZExtTrunc == IV) {
2240 ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->
getType(),
2243 const SCEV *SExtTrunc =
2244 SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2247 if (SExtTrunc == IV) {
2249 ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->
getType(),
2255 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->
getType(),
2259 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt,
"exitcond");
2260 Value *OrigCond = BI->getCondition();
2266 BI->setCondition(Cond);
2267 DeadInsts.push_back(OrigCond);
2281 void IndVarSimplify::sinkUnusedInvariants(
Loop *L) {
2283 if (!ExitBlock)
return;
2286 if (!Preheader)
return;
2290 while (I != Preheader->
begin()) {
2293 if (isa<PHINode>(I))
2306 if (isa<DbgInfoIntrinsic>(I))
2317 if (isa<AllocaInst>(I))
2322 bool UsedInLoop =
false;
2323 for (Use &U : I->
uses()) {
2326 if (
PHINode *P = dyn_cast<PHINode>(User)) {
2328 PHINode::getIncomingValueNumForOperand(U.getOperandNo());
2329 UseBB = P->getIncomingBlock(i);
2331 if (UseBB == Preheader || L->
contains(UseBB)) {
2345 if (I != Preheader->
begin()) {
2349 }
while (isa<DbgInfoIntrinsic>(I) && I != Preheader->
begin());
2351 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->
begin())
2367 bool IndVarSimplify::run(
Loop *L) {
2370 "LCSSA required to run indvars!");
2386 rewriteNonIntegerIVs(L);
2388 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2403 simplifyAndExtend(L, Rewriter, LI);
2412 !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2413 rewriteLoopExitValues(L, Rewriter);
2434 (
void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
2445 while (!DeadInsts.empty())
2447 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2454 sinkUnusedInvariants(L);
2459 rewriteFirstIterationLoopExitValues(L);
2466 "Indvars did not preserve LCSSA!");
2471 if (
VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2473 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2474 if (SE->getTypeSizeInBits(BackedgeTakenCount->
getType()) <
2475 SE->getTypeSizeInBits(NewBECount->
getType()))
2476 NewBECount = SE->getTruncateOrNoop(NewBECount,
2477 BackedgeTakenCount->
getType());
2479 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2481 assert(BackedgeTakenCount == NewBECount &&
"indvars must preserve SCEV");
2494 IndVarSimplify IVS(&AR.
LI, &AR.
SE, &AR.
DT, DL, &AR.
TLI, &AR.
TTI);
2504 struct IndVarSimplifyLegacyPass :
public LoopPass {
2514 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2515 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2516 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2517 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2518 auto *TLI = TLIP ? &TLIP->getTLI() :
nullptr;
2519 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2520 auto *TTI = TTIP ? &TTIP->getTTI(*L->
getHeader()->getParent()) :
nullptr;
2523 IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2536 "Induction Variable Simplification",
false,
false)
2542 return new IndVarSimplifyLegacyPass();
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
bool hoistIVInc(Instruction *IncV, Instruction *InsertPos)
Utility for hoisting an IV increment.
Induction Variable Simplification
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
iterator_range< use_iterator > uses()
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * getExactExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Try to find existing LLVM IR value for S available at the point At.
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT)
Perform a quick domtree based check for loop invariance assuming that V is used within the loop...
MutableArrayRef< T > makeMutableArrayRef(T &OneElt)
Construct a MutableArrayRef from a single element.
bool isOne() const
Return true if the expression is a constant one.
STATISTIC(NumFunctions,"Total number of functions")
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
This is the interface for a simple mod/ref and alias analysis over globals.
bool isZero() const
Return true if the expression is a constant zero.
unsigned getNumOperands() const
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
The main scalar evolution driver.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
bool isHighCostExpansion(const SCEV *Expr, Loop *L, const Instruction *At=nullptr)
Return true for expressions that may incur non-trivial cost to evaluate at runtime.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
bool isSigned() const
Determine if this instruction is using a signed comparison.
0 1 0 0 True if ordered and less than
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
1 1 1 0 True if unordered or not equal
void setDebugType(const char *s)
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LoopT * getParentLoop() const
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static cl::opt< bool > UsePostIncrementRanges("indvars-post-increment-ranges", cl::Hidden, cl::desc("Use post increment control-dependent ranges in IndVarSimplify"), cl::init(true))
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static 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...
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
static bool hasConcreteDef(Value *V)
Return true if the given value is concrete.
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getHeader() const
const SCEV * getStart() const
StringRef getName() const
Return a constant reference to the value's name.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
1 0 0 1 True if unordered or equal
bool match(Val *V, const Pattern &P)
static Value * genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L, SCEVExpander &Rewriter, ScalarEvolution *SE)
Help linearFunctionTestReplace by generating a value that holds the RHS of the new loop test...
Interface for visiting interesting IV users that are recognized but not simplified by this utility...
#define INITIALIZE_PASS_DEPENDENCY(depName)
This is the interface for a SCEV-based alias analysis.
INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass,"indvars","Induction Variable Simplification", false, false) INITIALIZE_PASS_END(IndVarSimplifyLegacyPass
This is the base class for all instructions that perform data casts.
A Use represents the edge between a Value definition and its users.
static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal)
Convert APF to an integer, if possible.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static StringRef getName(Value *V)
0 1 0 1 True if ordered and less than or equal
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
LLVM_NODISCARD bool empty() const
Value handle that is nullable, but tries to track the Value.
int getMaxValue(MCInstrInfo const &MCII, MCInst const &MCI)
Return the maximum value of an extendable operand.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead, IVVisitor *V=nullptr)
simplifyUsersOfIV - Simplify instructions that use this induction variable by using ScalarEvolution t...
This node represents a polynomial recurrence on the trip count of the specified loop.
This instruction compares its operands according to the predicate given to the constructor.
static Instruction * getInsertPointForUses(Instruction *User, Value *Def, DominatorTree *DT, LoopInfo *LI)
Determine the insertion point for this user.
static cl::opt< bool > VerifyIndvars("verify-indvars", cl::Hidden, cl::desc("Verify the ScalarEvolution result after running indvars"))
BasicBlock * getSuccessor(unsigned i) const
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
const SCEV * getSizeOfExpr(Type *IntTy, Type *AllocTy)
Return an expression for sizeof AllocTy that is type IntTy.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
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...
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
iterator_range< block_iterator > blocks() const
void initializeIndVarSimplifyLegacyPassPass(PassRegistry &)
void clearInsertPoint()
Clear the current insertion point.
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
A set of analyses that are preserved following a run of a transformation pass.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE, SCEVExpander &Rewriter)
Return true if this loop's backedge taken count expression can be safely and cheaply expanded into an...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Type * getType() const
Return the LLVM type of this SCEV expression.
Conditional or Unconditional Branch instruction.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
ConstantFP - Floating Point Values [float, double].
static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE, const TargetTransformInfo *TTI)
Update information about the induction variable that is extended by this sign or zero extend operatio...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer arithmetic operators which may exhibit overflow - Add, Sub, and Mul.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Value * getOperand(unsigned i) const
self_iterator getIterator()
Class to represent integer types.
Predicate getPredicate() const
Return the predicate for this instruction.
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
Return all unique successor blocks of this loop.
LLVMContext & getContext() const
All values hold a context through their type.
static ICmpInst * getLoopTest(Loop *L)
Return the compare guarding the loop latch, or NULL for unrecognized tests.
1 1 0 1 True if unordered, less than, or equal
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
TargetTransformInfo & TTI
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
bool isConditional() const
0 0 1 0 True if ordered and greater than
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
constexpr bool isInt< 32 >(int64_t x)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty)
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
1 1 0 0 True if unordered or less than
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
This class represents a range of values.
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static PHINode * getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT)
Return the loop header phi IFF IncV adds a loop invariant value to the phi.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Value handle that asserts if the Value is deleted.
static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI)
This IV user cannot be widen.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Class for arbitrary precision integers.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
iterator_range< user_iterator > users()
This class uses information about analyze scalars to rewrite expressions in canonical form...
Represents analyses that only rely on functions' control flow.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
llvm_unreachable("Unknown RegBank!")
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Virtual Register Rewriter
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Value * getCondition() const
void emplace_back(ArgTypes &&...Args)
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
virtual void visitCast(CastInst *Cast)=0
Represents a single loop in the control flow graph.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
user_iterator_impl< User > user_iterator
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
0 1 1 0 True if ordered and operands are unequal
static bool needsLFTR(Loop *L, DominatorTree *DT)
linearFunctionTestReplace policy.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const Loop * getLoop() const
1 0 1 0 True if unordered or greater than
const APFloat & getValueAPF() const
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
This class represents a cast from signed integer to floating point.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
unsigned getSCEVType() const
static cl::opt< ReplaceExitVal > ReplaceExitValue("replexitval", cl::Hidden, cl::init(OnlyCheapRepl), cl::desc("Choose the strategy to replace exit value in IndVarSimplify"), cl::values(clEnumValN(NeverRepl,"never","never replace exit value"), clEnumValN(OnlyCheapRepl,"cheap","only replace exit value when the cost is cheap"), clEnumValN(AlwaysRepl,"always","always replace exit value whenever possible")))
0 0 0 1 True if ordered and equal
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
1 0 1 1 True if unordered, greater than, or equal
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond)
Return true if this IV has any uses other than the (soon to be rewritten) loop exit test...
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
void disableCanonicalMode()
Disable the behavior of expanding expressions in canonical form rather than in a more literal form...
APInt zext(unsigned width) const
Zero extend to a new width.
A container for analyses that lazily runs them and caches their results.
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
void setIncomingValue(unsigned i, Value *V)
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
static cl::opt< bool > DisableLFTR("disable-lftr", cl::Hidden, cl::init(false), cl::desc("Disable Linear Function Test Replace optimization"))
0 0 1 1 True if ordered and greater than or equal
static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl< Value * > &Visited, unsigned Depth)
Recursive helper for hasConcreteDef().
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
const BasicBlock * getParent() const
Pass * createIndVarSimplifyPass()
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property...
This class represents a constant integer value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
static PHINode * FindLoopCounter(Loop *L, const SCEV *BECount, ScalarEvolution *SE, DominatorTree *DT)
Find an affine IV in canonical form.