89 #define DEBUG_TYPE "indvars" 91 STATISTIC(NumWidened ,
"Number of indvars widened");
92 STATISTIC(NumReplaced ,
"Number of exit values replaced");
93 STATISTIC(NumLFTR ,
"Number of loop exit tests replaced");
94 STATISTIC(NumElimExt ,
"Number of IV sign/zero extends eliminated");
95 STATISTIC(NumElimIV ,
"Number of congruent IVs eliminated");
102 cl::desc(
"Verify the ScalarEvolution result after running indvars"));
108 cl::desc(
"Choose the strategy to replace exit value in IndVarSimplify"),
111 "only replace exit value when the cost is cheap"),
113 "always replace exit value whenever possible")));
117 cl::desc(
"Use post increment control-dependent ranges in IndVarSimplify"),
122 cl::desc(
"Disable Linear Function Test Replace optimization"));
128 class IndVarSimplify {
137 bool Changed =
false;
139 bool isValidRewrite(
Value *FromVal,
Value *ToVal);
142 void rewriteNonIntegerIVs(
Loop *L);
148 void rewriteFirstIterationLoopExitValues(
Loop *L);
150 Value *linearFunctionTestReplace(
Loop *L,
const SCEV *BackedgeTakenCount,
153 void sinkUnusedInvariants(
Loop *L);
162 : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
173 bool IndVarSimplify::isValidRewrite(
Value *FromVal,
Value *ToVal) {
184 Value *FromPtr = FromVal;
185 Value *ToPtr = ToVal;
186 if (
auto *
GEP = dyn_cast<GEPOperator>(FromVal)) {
187 FromPtr =
GEP->getPointerOperand();
189 if (
auto *
GEP = dyn_cast<GEPOperator>(ToVal)) {
190 ToPtr =
GEP->getPointerOperand();
192 if (FromPtr != FromVal || ToPtr != ToVal) {
194 if (FromPtr == ToPtr)
208 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
209 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
210 if (FromBase == ToBase)
213 LLVM_DEBUG(
dbgs() <<
"INDVARS: GEP rewrite bail out " << *FromBase
214 <<
" != " << *ToBase <<
"\n");
244 assert(InsertPt &&
"Missing phi operand");
250 assert(DT->
dominates(DefI, InsertPt) &&
"def does not dominate all uses");
255 for (
auto *DTN = (*DT)[InsertPt->
getParent()]; DTN; DTN = DTN->getIDom())
257 return DTN->getBlock()->getTerminator();
268 bool isExact =
false;
287 void IndVarSimplify::handleFloatingPointIV(
Loop *L,
PHINode *PN) {
289 unsigned BackEdge = IncomingEdge^1;
295 if (!InitValueVal || !
ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
301 if (Incr ==
nullptr || Incr->getOpcode() != Instruction::FAdd)
return;
307 if (IncValueVal ==
nullptr || Incr->
getOperand(0) != PN ||
315 if (IncrUse == Incr->user_end())
return;
317 if (IncrUse != Incr->user_end())
return;
344 if (ExitValueVal ==
nullptr ||
384 if (InitValue >= ExitValue)
391 if (++Range == 0)
return;
394 unsigned Leftover = Range %
uint32_t(IncValue);
405 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
410 if (InitValue <= ExitValue)
417 if (++Range == 0)
return;
420 unsigned Leftover = Range %
uint32_t(-IncValue);
431 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
481 void IndVarSimplify::rewriteNonIntegerIVs(
Loop *L) {
491 for (
unsigned i = 0, e = PHIs.
size(); i != e; ++i)
492 if (
PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
493 handleFloatingPointIV(L, PN);
519 : PN(P), Ith(I), Val(V), HighCost(H) {}
530 if (ExistingValue->getType() == ResultTy)
531 return ExistingValue;
552 void IndVarSimplify::rewriteLoopExitValues(
Loop *L,
SCEVExpander &Rewriter) {
555 "Indvars did not preserve LCSSA!");
574 while ((PN = dyn_cast<PHINode>(BBI++))) {
578 if (!SE->isSCEVable(PN->
getType()))
589 for (
unsigned i = 0; i != NumPreds; ++i) {
593 if (!isa<Instruction>(InVal))
609 if (!SE->isLoopInvariant(ExitValue, L) ||
619 unsigned NumHardInternalUses = 0;
620 unsigned NumSoftExternalUses = 0;
621 unsigned NumUses = 0;
623 IB !=
IE && NumUses <= 6; ++IB) {
629 NumHardInternalUses++;
631 if (Opc == Instruction::PHI) {
637 PB != PE && NumUses <= 6; ++PB, ++NumUses) {
638 unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
640 NumSoftExternalUses++;
645 NumSoftExternalUses++;
648 if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
654 expandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->
getType());
658 <<
" LoopVal = " << *Inst <<
"\n");
660 if (!isValidRewrite(Inst, ExitVal)) {
661 DeadInsts.push_back(ExitVal);
671 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
674 for (
const RewritePhi &Phi : RewritePhiSet) {
676 Value *ExitVal = Phi.Val;
680 if (ReplaceExitValue ==
OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
681 DeadInsts.push_back(ExitVal);
693 DeadInsts.push_back(Inst);
697 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
717 void IndVarSimplify::rewriteFirstIterationLoopExitValues(
Loop *L) {
724 assert(LoopHeader &&
"Invalid loop");
726 for (
auto *ExitBB : ExitBlocks) {
729 for (
PHINode &PN : ExitBB->phis()) {
731 IncomingValIdx !=
E; ++IncomingValIdx) {
738 if (IncomingBB != LoopHeader)
744 Value *Cond =
nullptr;
745 if (
auto *BI = dyn_cast<BranchInst>(TermInst)) {
748 Cond = BI->getCondition();
749 }
else if (
auto *
SI = dyn_cast<SwitchInst>(TermInst))
750 Cond =
SI->getCondition();
767 assert(LoopPreheader &&
"Invalid loop");
768 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
769 if (PreheaderIdx != -1) {
770 assert(ExitVal->getParent() == LoopHeader &&
771 "ExitVal must be in loop header");
773 ExitVal->getIncomingValue(PreheaderIdx));
783 bool IndVarSimplify::canLoopBeDeleted(
798 if (ExitBlocks.
size() > 1 || ExitingBlocks.
size() > 1)
803 while (
PHINode *
P = dyn_cast<PHINode>(BI)) {
804 Value *Incoming =
P->getIncomingValueForBlock(ExitingBlocks[0]);
810 for (
const RewritePhi &Phi : RewritePhiSet) {
811 unsigned i = Phi.Ith;
812 if (Phi.PN ==
P && (Phi.PN)->getIncomingValue(i) == Incoming) {
819 if (!found && (I = dyn_cast<Instruction>(Incoming)))
826 for (
auto *BB : L->
blocks())
848 Type *WidestNativeType =
nullptr;
851 bool IsSigned =
false;
861 bool IsSigned = Cast->
getOpcode() == Instruction::SExt;
862 if (!IsSigned && Cast->
getOpcode() != Instruction::ZExt)
875 if (NarrowIVWidth >= Width)
891 if (!WI.WidestNativeType) {
893 WI.IsSigned = IsSigned;
898 if (WI.IsSigned != IsSigned)
910 struct NarrowIVDefUse {
918 bool NeverNegative =
false;
922 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
923 NeverNegative(NeverNegative) {}
948 const SCEV *WideIncExpr =
nullptr;
954 enum ExtendKind { ZeroExtended, SignExtended,
Unknown };
972 DefUserPair
Key(Def, UseI);
973 auto It = PostIncRangeInfos.
find(Key);
974 return It == PostIncRangeInfos.
end()
979 void calculatePostIncRanges(
PHINode *OrigPhi);
983 DefUserPair
Key(Def, UseI);
984 auto It = PostIncRangeInfos.
find(Key);
985 if (It == PostIncRangeInfos.
end())
986 PostIncRangeInfos.
insert({Key, R});
995 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
997 HasGuards(HasGuards), DeadInsts(DI) {
999 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
1005 Value *createExtendInst(
Value *NarrowOper,
Type *WideType,
bool IsSigned,
1009 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1011 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1015 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1017 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1019 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1021 const SCEV *getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
1022 unsigned OpCode)
const;
1026 bool widenLoopCompare(NarrowIVDefUse DU);
1044 Value *WidenIV::createExtendInst(
Value *NarrowOper,
Type *WideType,
1054 return IsSigned ? Builder.
CreateSExt(NarrowOper, WideType) :
1061 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1063 unsigned Opcode = DU.NarrowUse->getOpcode();
1068 case Instruction::Mul:
1069 case Instruction::UDiv:
1070 case Instruction::Sub:
1071 return cloneArithmeticIVUser(DU, WideAR);
1073 case Instruction::And:
1074 case Instruction::Or:
1075 case Instruction::Xor:
1076 case Instruction::Shl:
1077 case Instruction::LShr:
1078 case Instruction::AShr:
1079 return cloneBitwiseIVUser(DU);
1083 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1088 LLVM_DEBUG(
dbgs() <<
"Cloning bitwise IVUser: " << *NarrowUse <<
"\n");
1094 bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1097 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1098 IsSigned, NarrowUse);
1101 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1102 IsSigned, NarrowUse);
1104 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1108 Builder.Insert(WideBO);
1109 WideBO->copyIRFlags(NarrowBO);
1113 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1119 LLVM_DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1121 unsigned IVOpIdx = (NarrowUse->
getOperand(0) == NarrowDef) ? 0 : 1;
1132 auto GuessNonIVOperand = [&](
bool SignExt) {
1133 const SCEV *WideLHS;
1134 const SCEV *WideRHS;
1136 auto GetExtend = [
this, SignExt](
const SCEV *S,
Type *Ty) {
1138 return SE->getSignExtendExpr(S, Ty);
1139 return SE->getZeroExtendExpr(S, Ty);
1143 WideLHS = SE->getSCEV(WideDef);
1145 WideRHS = GetExtend(NarrowRHS, WideType);
1148 WideLHS = GetExtend(NarrowLHS, WideType);
1149 WideRHS = SE->getSCEV(WideDef);
1153 const SCEV *WideUse =
nullptr;
1160 WideUse = SE->getAddExpr(WideLHS, WideRHS);
1163 case Instruction::Mul:
1164 WideUse = SE->getMulExpr(WideLHS, WideRHS);
1167 case Instruction::UDiv:
1168 WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1171 case Instruction::Sub:
1172 WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1176 return WideUse == WideAR;
1179 bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1180 if (!GuessNonIVOperand(SignExtend)) {
1181 SignExtend = !SignExtend;
1182 if (!GuessNonIVOperand(SignExtend))
1188 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1189 SignExtend, NarrowUse);
1192 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1193 SignExtend, NarrowUse);
1195 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1200 Builder.Insert(WideBO);
1201 WideBO->copyIRFlags(NarrowBO);
1205 WidenIV::ExtendKind WidenIV::getExtendKind(
Instruction *
I) {
1206 auto It = ExtendKindMap.find(I);
1207 assert(It != ExtendKindMap.end() &&
"Instruction not yet extended!");
1211 const SCEV *WidenIV::getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
1212 unsigned OpCode)
const {
1214 return SE->getAddExpr(LHS, RHS);
1215 if (OpCode == Instruction::Sub)
1216 return SE->getMinusSCEV(LHS, RHS);
1217 if (OpCode == Instruction::Mul)
1218 return SE->getMulExpr(LHS, RHS);
1228 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1230 const unsigned OpCode = DU.NarrowUse->getOpcode();
1233 OpCode != Instruction::Mul)
1238 const unsigned ExtendOperIdx =
1239 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1240 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef &&
"bad DU");
1242 const SCEV *ExtendOperExpr =
nullptr;
1244 cast<OverflowingBinaryOperator>(DU.NarrowUse);
1245 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1247 ExtendOperExpr = SE->getSignExtendExpr(
1248 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1250 ExtendOperExpr = SE->getZeroExtendExpr(
1251 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1260 const SCEV *lhs = SE->getSCEV(DU.WideDef);
1261 const SCEV *rhs = ExtendOperExpr;
1265 if (ExtendOperIdx == 0)
1270 if (!AddRec || AddRec->
getLoop() != L)
1273 return {AddRec, ExtKind};
1281 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1282 if (!SE->isSCEVable(DU.NarrowUse->getType()))
1285 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1286 if (SE->getTypeSizeInBits(NarrowExpr->
getType()) >=
1287 SE->getTypeSizeInBits(WideType)) {
1293 const SCEV *WideExpr;
1295 if (DU.NeverNegative) {
1296 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1297 if (isa<SCEVAddRecExpr>(WideExpr))
1298 ExtKind = SignExtended;
1300 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1301 ExtKind = ZeroExtended;
1303 }
else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1304 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1305 ExtKind = SignExtended;
1307 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1308 ExtKind = ZeroExtended;
1311 if (!AddRec || AddRec->
getLoop() != L)
1313 return {AddRec, ExtKind};
1319 LLVM_DEBUG(
dbgs() <<
"INDVARS: Truncate IV " << *DU.WideDef <<
" for user " 1320 << *DU.NarrowUse <<
"\n");
1324 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1330 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1349 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1350 if (!(DU.NeverNegative || IsSigned == Cmp->
isSigned()))
1354 unsigned CastWidth = SE->getTypeSizeInBits(Op->
getType());
1355 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1356 assert(CastWidth <= IVWidth &&
"Unexpected width while widening compare.");
1361 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1364 if (CastWidth < IVWidth) {
1365 Value *ExtOp = createExtendInst(Op, WideType, Cmp->
isSigned(), Cmp);
1366 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1374 assert(ExtendKindMap.count(DU.NarrowDef) &&
1375 "Should already know the kind of extension used to widen NarrowDef");
1378 if (
PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1379 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1383 if (UsePhi->getNumOperands() != 1)
1389 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1393 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() +
".wide",
1395 WidePhi->
addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1397 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1399 DeadInsts.emplace_back(UsePhi);
1400 LLVM_DEBUG(
dbgs() <<
"INDVARS: Widen lcssa phi " << *UsePhi <<
" to " 1401 << *WidePhi <<
"\n");
1409 auto canWidenBySExt = [&]() {
1410 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1412 auto canWidenByZExt = [&]() {
1413 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1417 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1418 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1419 Value *NewDef = DU.WideDef;
1420 if (DU.NarrowUse->getType() != WideType) {
1421 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1422 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1423 if (CastWidth < IVWidth) {
1426 NewDef = Builder.
CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1433 <<
" not wide enough to subsume " << *DU.NarrowUse
1435 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1436 NewDef = DU.NarrowUse;
1439 if (NewDef != DU.NarrowUse) {
1441 <<
" replaced by " << *DU.WideDef <<
"\n");
1443 DU.NarrowUse->replaceAllUsesWith(NewDef);
1444 DeadInsts.emplace_back(DU.NarrowUse);
1457 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1458 if (!WideAddRec.first)
1459 WideAddRec = getWideRecurrence(DU);
1461 assert((WideAddRec.first ==
nullptr) == (WideAddRec.second ==
Unknown));
1462 if (!WideAddRec.first) {
1465 if (widenLoopCompare(DU))
1476 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1477 "SCEV is not expected to evaluate a block terminator");
1482 if (WideAddRec.first == WideIncExpr &&
1486 WideUse = cloneIVUser(DU, WideAddRec.first);
1495 if (WideAddRec.first != SE->getSCEV(WideUse)) {
1496 LLVM_DEBUG(
dbgs() <<
"Wide use expression mismatch: " << *WideUse <<
": " 1497 << *SE->getSCEV(WideUse) <<
" != " << *WideAddRec.first
1499 DeadInsts.emplace_back(WideUse);
1503 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1510 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1511 bool NonNegativeDef =
1513 SE->getConstant(NarrowSCEV->
getType(), 0));
1518 if (!Widened.insert(NarrowUser).second)
1521 bool NonNegativeUse =
false;
1522 if (!NonNegativeDef) {
1524 if (
auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1525 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1528 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1529 NonNegativeDef || NonNegativeUse);
1548 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1549 ? SE->getSignExtendExpr(AddRec, WideType)
1550 : SE->getZeroExtendExpr(AddRec, WideType);
1552 assert(SE->getEffectiveSCEVType(WideIVExpr->
getType()) == WideType &&
1553 "Expect the new IV expression to preserve its type");
1557 if (!AddRec || AddRec->
getLoop() != L)
1566 "Loop header phi recurrence inputs do not dominate the loop");
1578 if (UsePostIncrementRanges)
1579 calculatePostIncRanges(OrigPhi);
1586 WidePhi = cast<PHINode>(Rewriter.
expandCodeFor(AddRec, WideType, InsertPt));
1594 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1595 WideIncExpr = SE->getSCEV(WideInc);
1599 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1607 assert(Widened.empty() && NarrowIVUsers.empty() &&
"expect initial state" );
1609 Widened.insert(OrigPhi);
1610 pushNarrowIVUsers(OrigPhi, WidePhi);
1612 while (!NarrowIVUsers.empty()) {
1613 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1621 pushNarrowIVUsers(DU.NarrowUse, WideUse);
1624 if (DU.NarrowDef->use_empty())
1625 DeadInsts.emplace_back(DU.NarrowDef);
1634 for (
auto &DbgValue : DbgValues)
1635 DbgValue->setOperand(0, MDPhi);
1641 void WidenIV::calculatePostIncRange(
Instruction *NarrowDef,
1645 Value *NarrowDefLHS;
1646 const APInt *NarrowDefRHS;
1652 auto UpdateRangeFromCondition = [&] (
Value *Condition,
1663 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1664 auto CmpConstrainedLHSRange =
1666 auto NarrowDefRange =
1667 CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS);
1669 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1672 auto UpdateRangeFromGuards = [&](
Instruction *Ctx) {
1677 Ctx->getParent()->rend())) {
1679 if (
match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
m_Value(C))))
1680 UpdateRangeFromCondition(C,
true);
1684 UpdateRangeFromGuards(NarrowUser);
1689 if (!DT->isReachableFromEntry(NarrowUserBB))
1692 for (
auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1694 DTB = DTB->getIDom()) {
1695 auto *BB = DTB->getBlock();
1697 UpdateRangeFromGuards(TI);
1700 if (!BI || !BI->isConditional())
1704 auto *FalseSuccessor = BI->getSuccessor(1);
1706 auto DominatesNarrowUser = [
this, NarrowUser] (
BasicBlockEdge BBE) {
1707 return BBE.isSingleEdge() &&
1708 DT->dominates(BBE, NarrowUser->
getParent());
1712 UpdateRangeFromCondition(BI->getCondition(),
true);
1715 UpdateRangeFromCondition(BI->getCondition(),
false);
1720 void WidenIV::calculatePostIncRanges(
PHINode *OrigPhi) {
1726 while (!Worklist.
empty()) {
1729 for (Use &U : NarrowDef->
uses()) {
1730 auto *NarrowUser = cast<Instruction>(U.getUser());
1733 auto *NarrowUserLoop = (*LI)[NarrowUser->
getParent()];
1734 if (!NarrowUserLoop || !L->
contains(NarrowUserLoop))
1737 if (!Visited.
insert(NarrowUser).second)
1742 calculatePostIncRange(NarrowDef, NarrowUser);
1757 class IndVarSimplifyVisitor :
public IVVisitor {
1768 : SE(SCEV), TTI(TTI), IVPhi(IV) {
1770 WI.NarrowIV = IVPhi;
1784 void IndVarSimplify::simplifyAndExtend(
Loop *L,
1789 auto *GuardDecl = L->
getBlocks()[0]->getModule()->getFunction(
1791 bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1801 while (!LoopPhis.
empty()) {
1812 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1817 if (Visitor.WI.WidestNativeType) {
1820 }
while(!LoopPhis.
empty());
1823 WidenIV Widener(WideIVs.
back(), LI, SE, DT, DeadInsts, HasGuards);
1824 if (
PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1852 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1853 BackedgeTakenCount->
isZero())
1877 case Instruction::Sub:
1879 case Instruction::GetElementPtr:
1894 if (IncI->
getOpcode() == Instruction::GetElementPtr)
1916 assert(BI &&
"expected exit branch");
1965 if (isa<Constant>(V))
1966 return !isa<UndefValue>(V);
2009 if (U != Cond && U != IncV)
return false;
2012 if (U != Cond && U != Phi)
return false;
2038 const SCEV *BestInit =
nullptr;
2040 assert(LatchBlock &&
"needsLFTR should guarantee a loop latch");
2064 if (!Step || !Step->
isOne())
2087 if (BestPhi && !
AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2101 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->
getType()))
2134 "Computed iteration count is not loop invariant!");
2143 cast<PointerType>(GEPBase->
getType())
2144 ->getElementType())->isOne() &&
2145 "unit stride pointer IV must be i8*");
2148 return Builder.
CreateGEP(
nullptr, GEPBase, GEPOffset,
"lftr.limit");
2161 const SCEV *IVLimit =
nullptr;
2181 "Computed iteration count is not loop invariant!");
2196 Value *IndVarSimplify::
2197 linearFunctionTestReplace(
Loop *L,
2198 const SCEV *BackedgeTakenCount,
2204 Value *CmpIndVar = IndVar;
2205 const SCEV *IVCount = BackedgeTakenCount;
2216 IVCount = SE->getAddExpr(BackedgeTakenCount,
2217 SE->getOne(BackedgeTakenCount->
getType()));
2227 "genLoopLimit missed a cast");
2232 if (L->
contains(BI->getSuccessor(0)))
2237 LLVM_DEBUG(
dbgs() <<
"INDVARS: Rewriting loop exit condition to:\n" 2238 <<
" LHS:" << *CmpIndVar <<
'\n' 2241 <<
" RHS:\t" << *ExitCnt <<
"\n" 2242 <<
" IVCount:\t" << *IVCount <<
"\n");
2248 if (
auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2253 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->
getType());
2254 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->
getType());
2255 if (CmpIndVarSize > ExitCntSize) {
2256 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2260 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
2261 const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
2262 APInt Count = cast<SCEVConstant>(IVCount)->getAPInt();
2265 if (IVCount != BackedgeTakenCount && Count == 0) {
2270 Count = Count.
zext(CmpIndVarSize);
2272 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2273 NewLimit = Start - Count;
2275 NewLimit = Start + Count;
2284 bool Extended =
false;
2285 const SCEV *IV = SE->getSCEV(CmpIndVar);
2286 const SCEV *ZExtTrunc =
2287 SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2291 if (ZExtTrunc == IV) {
2296 const SCEV *SExtTrunc =
2297 SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2300 if (SExtTrunc == IV) {
2313 Value *OrigCond = BI->getCondition();
2319 BI->setCondition(Cond);
2320 DeadInsts.push_back(OrigCond);
2334 void IndVarSimplify::sinkUnusedInvariants(
Loop *L) {
2336 if (!ExitBlock)
return;
2339 if (!Preheader)
return;
2343 while (I != Preheader->
begin()) {
2346 if (isa<PHINode>(I))
2359 if (isa<DbgInfoIntrinsic>(I))
2370 if (isa<AllocaInst>(I))
2375 bool UsedInLoop =
false;
2376 for (Use &U : I->
uses()) {
2379 if (
PHINode *
P = dyn_cast<PHINode>(User)) {
2382 UseBB =
P->getIncomingBlock(i);
2384 if (UseBB == Preheader || L->
contains(UseBB)) {
2398 if (I != Preheader->
begin()) {
2402 }
while (isa<DbgInfoIntrinsic>(I) && I != Preheader->
begin());
2404 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->
begin())
2420 bool IndVarSimplify::run(
Loop *L) {
2423 "LCSSA required to run indvars!");
2439 rewriteNonIntegerIVs(L);
2441 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2456 simplifyAndExtend(L, Rewriter, LI);
2465 !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2466 rewriteLoopExitValues(L, Rewriter);
2487 (
void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
2498 while (!DeadInsts.empty())
2500 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2507 sinkUnusedInvariants(L);
2512 rewriteFirstIterationLoopExitValues(L);
2519 "Indvars did not preserve LCSSA!");
2524 if (
VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2526 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2527 if (SE->getTypeSizeInBits(BackedgeTakenCount->
getType()) <
2528 SE->getTypeSizeInBits(NewBECount->
getType()))
2529 NewBECount = SE->getTruncateOrNoop(NewBECount,
2530 BackedgeTakenCount->
getType());
2532 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2534 assert(BackedgeTakenCount == NewBECount &&
"indvars must preserve SCEV");
2547 IndVarSimplify IVS(&AR.
LI, &AR.
SE, &AR.
DT, DL, &AR.
TLI, &AR.
TTI);
2558 struct IndVarSimplifyLegacyPass :
public LoopPass {
2561 IndVarSimplifyLegacyPass() :
LoopPass(ID) {
2569 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2570 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2571 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2572 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2573 auto *TLI = TLIP ? &TLIP->getTLI() :
nullptr;
2574 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2578 IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2593 "Induction Variable Simplification",
false,
false)
2599 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
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
iterator_range< use_iterator > uses()
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
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.
Compute iterated dominance frontiers using a linear time algorithm.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
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...
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
The main scalar evolution driver.
APInt zext(unsigned width) const
Zero extend to a new width.
bool isZero() const
Return true if the expression is a constant zero.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
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.
0 1 0 0 True if ordered and less than
LLVMContext & getContext() const
All values hold a context through their type.
1 1 1 0 True if unordered or not equal
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
void setDebugType(const char *s)
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
BasicBlock * getSuccessor(unsigned i) const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
STATISTIC(NumFunctions, "Total number of functions")
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))
static IntegerType * getInt64Ty(LLVMContext &C)
Value * getCondition() const
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...
This defines the Use class.
static bool hasConcreteDef(Value *V)
Return true if the given value is concrete.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
unsigned getBitWidth() const
Return the number of bits in the APInt.
INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars", "Induction Variable Simplification", false, false) INITIALIZE_PASS_END(IndVarSimplifyLegacyPass
iterator begin()
Instruction iterator methods.
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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...
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
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...
0 1 0 1 True if ordered and less than or equal
This file implements a class to represent arbitrary precision integral constant values and operations...
BlockT * getHeader() const
void findDbgValues(SmallVectorImpl< DbgValueInst *> &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics describing a value.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
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"))
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.
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
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)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
void initializeIndVarSimplifyLegacyPassPass(PassRegistry &)
iterator find(const_arg_type_t< KeyT > Val)
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 ...
initializer< Ty > init(const Ty &Val)
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...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
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...
Conditional or Unconditional Branch instruction.
static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl< Value *> &Visited, unsigned Depth)
Recursive helper for hasConcreteDef().
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
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 mayHaveSideEffects() const
Return true if the instruction may have side effects.
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.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Represent the analysis usage information of a pass.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
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 operators which may exhibit overflow - Add, Sub, Mul, and Shl...
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
self_iterator getIterator()
const SCEV * getStart() const
Class to represent integer types.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
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.
static unsigned getIncomingValueNumForOperand(unsigned i)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
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
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
TargetTransformInfo & TTI
const APFloat & getValueAPF() const
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
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...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
unsigned getSCEVType() const
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Type * getType() const
Return the LLVM type of this SCEV expression.
constexpr bool isInt< 32 >(int64_t x)
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty)
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...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
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.
This class represents a range of values.
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
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.
bool isConditional() const
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:
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
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")))
This class uses information about analyze scalars to rewrite expressions in canonical form...
Represents analyses that only rely on functions' control flow.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
LoopT * getParentLoop() const
Virtual Register Rewriter
Predicate getPredicate() const
Return the predicate for this instruction.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
void emplace_back(ArgTypes &&... Args)
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
user_iterator_impl< User > user_iterator
bool mayReadFromMemory() const
Return true if this instruction may read memory.
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)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead, SCEVExpander &Rewriter, IVVisitor *V=nullptr)
simplifyUsersOfIV - Simplify instructions that use this induction variable by using ScalarEvolution t...
1 0 1 0 True if unordered or greater than
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()
bool isOne() const
Return true if the expression is a constant one.
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.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
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...
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...
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
bool hasOneUse() const
Return true if there is exactly one user of this value.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
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 TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
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...
iterator_range< block_iterator > blocks() const
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
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Pass * createIndVarSimplifyPass()
const BasicBlock * getParent() const
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 hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property...
static PHINode * FindLoopCounter(Loop *L, const SCEV *BECount, ScalarEvolution *SE, DominatorTree *DT)
Find an affine IV in canonical form.