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 {
138 bool isValidRewrite(
Value *FromVal,
Value *ToVal);
141 bool rewriteNonIntegerIVs(
Loop *L);
147 bool rewriteFirstIterationLoopExitValues(
Loop *L);
150 bool linearFunctionTestReplace(
Loop *L,
const SCEV *BackedgeTakenCount,
153 bool sinkUnusedInvariants(
Loop *L);
159 : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
170 bool IndVarSimplify::isValidRewrite(
Value *FromVal,
Value *ToVal) {
181 Value *FromPtr = FromVal;
182 Value *ToPtr = ToVal;
183 if (
auto *
GEP = dyn_cast<GEPOperator>(FromVal)) {
184 FromPtr =
GEP->getPointerOperand();
186 if (
auto *
GEP = dyn_cast<GEPOperator>(ToVal)) {
187 ToPtr =
GEP->getPointerOperand();
189 if (FromPtr != FromVal || ToPtr != ToVal) {
191 if (FromPtr == ToPtr)
205 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
206 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
207 if (FromBase == ToBase)
210 LLVM_DEBUG(
dbgs() <<
"INDVARS: GEP rewrite bail out " << *FromBase
211 <<
" != " << *ToBase <<
"\n");
241 assert(InsertPt &&
"Missing phi operand");
247 assert(DT->
dominates(DefI, InsertPt) &&
"def does not dominate all uses");
252 for (
auto *DTN = (*DT)[InsertPt->
getParent()]; DTN; DTN = DTN->getIDom())
254 return DTN->getBlock()->getTerminator();
265 bool isExact =
false;
284 bool IndVarSimplify::handleFloatingPointIV(
Loop *L,
PHINode *PN) {
286 unsigned BackEdge = IncomingEdge^1;
292 if (!InitValueVal || !
ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
298 if (Incr ==
nullptr || Incr->getOpcode() != Instruction::FAdd)
return false;
304 if (IncValueVal ==
nullptr || Incr->
getOperand(0) != PN ||
312 if (IncrUse == Incr->user_end())
return false;
314 if (IncrUse != Incr->user_end())
return false;
341 if (ExitValueVal ==
nullptr ||
348 default:
return false;
381 if (InitValue >= ExitValue)
388 if (++Range == 0)
return false;
391 unsigned Leftover = Range %
uint32_t(IncValue);
402 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
407 if (InitValue <= ExitValue)
414 if (++Range == 0)
return false;
417 unsigned Leftover = Range %
uint32_t(-IncValue);
428 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
478 bool IndVarSimplify::rewriteNonIntegerIVs(
Loop *L) {
488 bool Changed =
false;
489 for (
unsigned i = 0, e = PHIs.
size(); i != e; ++i)
490 if (
PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
491 Changed |= handleFloatingPointIV(L, PN);
518 : PN(P), Ith(I), Val(V), HighCost(H) {}
528 bool IndVarSimplify::hasHardUserWithinLoop(
const Loop *L,
const Instruction *
I)
const {
533 while (!WorkList.
empty()) {
542 for (
auto U : Curr->
users()) {
543 auto *UI = cast<Instruction>(U);
544 if (Visited.
insert(UI).second)
564 "Indvars did not preserve LCSSA!");
583 while ((PN = dyn_cast<PHINode>(BBI++))) {
587 if (!SE->isSCEVable(PN->
getType()))
598 for (
unsigned i = 0; i != NumPreds; ++i) {
602 if (!isa<Instruction>(InVal))
618 if (!SE->isLoopInvariant(ExitValue, L) ||
625 if (!isa<SCEVConstant>(ExitValue) && hasHardUserWithinLoop(L, Inst))
633 <<
" LoopVal = " << *Inst <<
"\n");
635 if (!isValidRewrite(Inst, ExitVal)) {
636 DeadInsts.push_back(ExitVal);
644 if (
auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
645 if (
auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
647 assert(EVL->contains(L) &&
"LCSSA breach detected!");
656 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
658 bool Changed =
false;
660 for (
const RewritePhi &Phi : RewritePhiSet) {
662 Value *ExitVal = Phi.Val;
666 if (ReplaceExitValue ==
OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
667 DeadInsts.push_back(ExitVal);
679 DeadInsts.push_back(Inst);
683 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
704 bool IndVarSimplify::rewriteFirstIterationLoopExitValues(
Loop *L) {
711 assert(LoopHeader &&
"Invalid loop");
713 bool MadeAnyChanges =
false;
714 for (
auto *ExitBB : ExitBlocks) {
717 for (
PHINode &PN : ExitBB->phis()) {
719 IncomingValIdx !=
E; ++IncomingValIdx) {
726 if (IncomingBB != LoopHeader)
732 Value *Cond =
nullptr;
733 if (
auto *BI = dyn_cast<BranchInst>(TermInst)) {
736 Cond = BI->getCondition();
737 }
else if (
auto *
SI = dyn_cast<SwitchInst>(TermInst))
738 Cond =
SI->getCondition();
755 assert(LoopPreheader &&
"Invalid loop");
756 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
757 if (PreheaderIdx != -1) {
758 assert(ExitVal->getParent() == LoopHeader &&
759 "ExitVal must be in loop header");
760 MadeAnyChanges =
true;
762 ExitVal->getIncomingValue(PreheaderIdx));
767 return MadeAnyChanges;
773 bool IndVarSimplify::canLoopBeDeleted(
788 if (ExitBlocks.
size() > 1 || ExitingBlocks.
size() > 1)
793 while (
PHINode *
P = dyn_cast<PHINode>(BI)) {
794 Value *Incoming =
P->getIncomingValueForBlock(ExitingBlocks[0]);
800 for (
const RewritePhi &Phi : RewritePhiSet) {
801 unsigned i = Phi.Ith;
802 if (Phi.PN ==
P && (Phi.PN)->getIncomingValue(i) == Incoming) {
809 if (!found && (I = dyn_cast<Instruction>(Incoming)))
816 for (
auto *BB : L->
blocks())
838 Type *WidestNativeType =
nullptr;
841 bool IsSigned =
false;
851 bool IsSigned = Cast->
getOpcode() == Instruction::SExt;
852 if (!IsSigned && Cast->
getOpcode() != Instruction::ZExt)
865 if (NarrowIVWidth >= Width)
881 if (!WI.WidestNativeType) {
883 WI.IsSigned = IsSigned;
888 if (WI.IsSigned != IsSigned)
900 struct NarrowIVDefUse {
908 bool NeverNegative =
false;
912 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
913 NeverNegative(NeverNegative) {}
938 const SCEV *WideIncExpr =
nullptr;
944 enum ExtendKind { ZeroExtended, SignExtended,
Unknown };
962 DefUserPair
Key(Def, UseI);
963 auto It = PostIncRangeInfos.
find(Key);
964 return It == PostIncRangeInfos.
end()
969 void calculatePostIncRanges(
PHINode *OrigPhi);
973 DefUserPair
Key(Def, UseI);
974 auto It = PostIncRangeInfos.
find(Key);
975 if (It == PostIncRangeInfos.
end())
976 PostIncRangeInfos.
insert({Key, R});
985 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
987 HasGuards(HasGuards), DeadInsts(DI) {
989 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
995 Value *createExtendInst(
Value *NarrowOper,
Type *WideType,
bool IsSigned,
999 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1001 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1005 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1007 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1009 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1011 const SCEV *getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
1012 unsigned OpCode)
const;
1016 bool widenLoopCompare(NarrowIVDefUse DU);
1017 bool widenWithVariantLoadUse(NarrowIVDefUse DU);
1018 void widenWithVariantLoadUseCodegen(NarrowIVDefUse DU);
1036 Value *WidenIV::createExtendInst(
Value *NarrowOper,
Type *WideType,
1046 return IsSigned ? Builder.
CreateSExt(NarrowOper, WideType) :
1053 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1055 unsigned Opcode = DU.NarrowUse->getOpcode();
1060 case Instruction::Mul:
1061 case Instruction::UDiv:
1062 case Instruction::Sub:
1063 return cloneArithmeticIVUser(DU, WideAR);
1065 case Instruction::And:
1066 case Instruction::Or:
1067 case Instruction::Xor:
1068 case Instruction::Shl:
1069 case Instruction::LShr:
1070 case Instruction::AShr:
1071 return cloneBitwiseIVUser(DU);
1075 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1080 LLVM_DEBUG(
dbgs() <<
"Cloning bitwise IVUser: " << *NarrowUse <<
"\n");
1086 bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1089 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1090 IsSigned, NarrowUse);
1093 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1094 IsSigned, NarrowUse);
1096 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1100 Builder.Insert(WideBO);
1101 WideBO->copyIRFlags(NarrowBO);
1105 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1111 LLVM_DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1113 unsigned IVOpIdx = (NarrowUse->
getOperand(0) == NarrowDef) ? 0 : 1;
1124 auto GuessNonIVOperand = [&](
bool SignExt) {
1125 const SCEV *WideLHS;
1126 const SCEV *WideRHS;
1128 auto GetExtend = [
this, SignExt](
const SCEV *S,
Type *Ty) {
1130 return SE->getSignExtendExpr(S, Ty);
1131 return SE->getZeroExtendExpr(S, Ty);
1135 WideLHS = SE->getSCEV(WideDef);
1137 WideRHS = GetExtend(NarrowRHS, WideType);
1140 WideLHS = GetExtend(NarrowLHS, WideType);
1141 WideRHS = SE->getSCEV(WideDef);
1145 const SCEV *WideUse =
nullptr;
1152 WideUse = SE->getAddExpr(WideLHS, WideRHS);
1155 case Instruction::Mul:
1156 WideUse = SE->getMulExpr(WideLHS, WideRHS);
1159 case Instruction::UDiv:
1160 WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1163 case Instruction::Sub:
1164 WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1168 return WideUse == WideAR;
1171 bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1172 if (!GuessNonIVOperand(SignExtend)) {
1173 SignExtend = !SignExtend;
1174 if (!GuessNonIVOperand(SignExtend))
1180 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1181 SignExtend, NarrowUse);
1184 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1185 SignExtend, NarrowUse);
1187 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1192 Builder.Insert(WideBO);
1193 WideBO->copyIRFlags(NarrowBO);
1197 WidenIV::ExtendKind WidenIV::getExtendKind(
Instruction *I) {
1198 auto It = ExtendKindMap.find(I);
1199 assert(It != ExtendKindMap.end() &&
"Instruction not yet extended!");
1203 const SCEV *WidenIV::getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
1204 unsigned OpCode)
const {
1206 return SE->getAddExpr(LHS, RHS);
1207 if (OpCode == Instruction::Sub)
1208 return SE->getMinusSCEV(LHS, RHS);
1209 if (OpCode == Instruction::Mul)
1210 return SE->getMulExpr(LHS, RHS);
1220 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1222 const unsigned OpCode = DU.NarrowUse->getOpcode();
1225 OpCode != Instruction::Mul)
1230 const unsigned ExtendOperIdx =
1231 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1232 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef &&
"bad DU");
1234 const SCEV *ExtendOperExpr =
nullptr;
1236 cast<OverflowingBinaryOperator>(DU.NarrowUse);
1237 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1239 ExtendOperExpr = SE->getSignExtendExpr(
1240 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1242 ExtendOperExpr = SE->getZeroExtendExpr(
1243 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1252 const SCEV *lhs = SE->getSCEV(DU.WideDef);
1253 const SCEV *rhs = ExtendOperExpr;
1257 if (ExtendOperIdx == 0)
1262 if (!AddRec || AddRec->
getLoop() != L)
1265 return {AddRec, ExtKind};
1273 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1274 if (!SE->isSCEVable(DU.NarrowUse->getType()))
1277 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1278 if (SE->getTypeSizeInBits(NarrowExpr->
getType()) >=
1279 SE->getTypeSizeInBits(WideType)) {
1285 const SCEV *WideExpr;
1287 if (DU.NeverNegative) {
1288 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1289 if (isa<SCEVAddRecExpr>(WideExpr))
1290 ExtKind = SignExtended;
1292 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1293 ExtKind = ZeroExtended;
1295 }
else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1296 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1297 ExtKind = SignExtended;
1299 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1300 ExtKind = ZeroExtended;
1303 if (!AddRec || AddRec->
getLoop() != L)
1305 return {AddRec, ExtKind};
1311 LLVM_DEBUG(
dbgs() <<
"INDVARS: Truncate IV " << *DU.WideDef <<
" for user " 1312 << *DU.NarrowUse <<
"\n");
1316 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1322 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1341 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1342 if (!(DU.NeverNegative || IsSigned == Cmp->
isSigned()))
1346 unsigned CastWidth = SE->getTypeSizeInBits(Op->
getType());
1347 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1348 assert(CastWidth <= IVWidth &&
"Unexpected width while widening compare.");
1353 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1356 if (CastWidth < IVWidth) {
1357 Value *ExtOp = createExtendInst(Op, WideType, Cmp->
isSigned(), Cmp);
1358 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1376 bool WidenIV::widenWithVariantLoadUse(NarrowIVDefUse DU) {
1382 const unsigned OpCode = NarrowUse->
getOpcode();
1385 OpCode != Instruction::Mul)
1390 unsigned ExtendOperIdx = DU.NarrowUse->getOperand(0) == NarrowDef ? 1 : 0;
1391 assert(DU.NarrowUse->getOperand(1 - ExtendOperIdx) == DU.NarrowDef &&
1394 const SCEV *ExtendOperExpr =
nullptr;
1396 cast<OverflowingBinaryOperator>(NarrowUse);
1397 ExtendKind ExtKind = getExtendKind(NarrowDef);
1399 ExtendOperExpr = SE->getSignExtendExpr(
1400 SE->getSCEV(NarrowUse->
getOperand(ExtendOperIdx)), WideType);
1402 ExtendOperExpr = SE->getZeroExtendExpr(
1403 SE->getSCEV(NarrowUse->
getOperand(ExtendOperIdx)), WideType);
1414 const SCEV *Op1 = SE->getSCEV(WideDef);
1416 if (!AddRecOp1 || AddRecOp1->
getLoop() != L)
1419 if (ExtKind == SignExtended) {
1420 if (!isa<SCEVSignExtendExpr>(ExtendOperExpr))
1423 if (!isa<SCEVZeroExtendExpr>(ExtendOperExpr))
1427 if (ExtKind == SignExtended) {
1428 for (Use &U : NarrowUse->
uses()) {
1430 if (!User || User->
getType() != WideType)
1434 for (Use &U : NarrowUse->
uses()) {
1436 if (!User || User->
getType() != WideType)
1446 void WidenIV::widenWithVariantLoadUseCodegen(NarrowIVDefUse DU) {
1451 ExtendKind ExtKind = getExtendKind(NarrowDef);
1453 LLVM_DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1458 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1459 ExtKind, NarrowUse);
1462 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1463 ExtKind, NarrowUse);
1465 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1469 Builder.Insert(WideBO);
1470 WideBO->copyIRFlags(NarrowBO);
1472 if (ExtKind == SignExtended)
1473 ExtendKindMap[NarrowUse] = SignExtended;
1475 ExtendKindMap[NarrowUse] = ZeroExtended;
1478 if (ExtKind == SignExtended) {
1479 for (Use &U : NarrowUse->
uses()) {
1481 if (User && User->
getType() == WideType) {
1482 LLVM_DEBUG(
dbgs() <<
"INDVARS: eliminating " << *User <<
" replaced by " 1483 << *WideBO <<
"\n");
1486 DeadInsts.emplace_back(User);
1490 for (Use &U : NarrowUse->
uses()) {
1492 if (User && User->
getType() == WideType) {
1493 LLVM_DEBUG(
dbgs() <<
"INDVARS: eliminating " << *User <<
" replaced by " 1494 << *WideBO <<
"\n");
1497 DeadInsts.emplace_back(User);
1506 assert(ExtendKindMap.count(DU.NarrowDef) &&
1507 "Should already know the kind of extension used to widen NarrowDef");
1510 if (
PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1511 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1515 if (UsePhi->getNumOperands() != 1)
1521 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1525 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() +
".wide",
1527 WidePhi->
addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1529 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1531 DeadInsts.emplace_back(UsePhi);
1532 LLVM_DEBUG(
dbgs() <<
"INDVARS: Widen lcssa phi " << *UsePhi <<
" to " 1533 << *WidePhi <<
"\n");
1541 auto canWidenBySExt = [&]() {
1542 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1544 auto canWidenByZExt = [&]() {
1545 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1549 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1550 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1551 Value *NewDef = DU.WideDef;
1552 if (DU.NarrowUse->getType() != WideType) {
1553 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1554 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1555 if (CastWidth < IVWidth) {
1558 NewDef = Builder.
CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1565 <<
" not wide enough to subsume " << *DU.NarrowUse
1567 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1568 NewDef = DU.NarrowUse;
1571 if (NewDef != DU.NarrowUse) {
1573 <<
" replaced by " << *DU.WideDef <<
"\n");
1575 DU.NarrowUse->replaceAllUsesWith(NewDef);
1576 DeadInsts.emplace_back(DU.NarrowUse);
1589 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1590 if (!WideAddRec.first)
1591 WideAddRec = getWideRecurrence(DU);
1593 assert((WideAddRec.first ==
nullptr) == (WideAddRec.second ==
Unknown));
1594 if (!WideAddRec.first) {
1597 if (widenLoopCompare(DU))
1605 if (widenWithVariantLoadUse(DU)) {
1606 widenWithVariantLoadUseCodegen(DU);
1618 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1619 "SCEV is not expected to evaluate a block terminator");
1624 if (WideAddRec.first == WideIncExpr &&
1628 WideUse = cloneIVUser(DU, WideAddRec.first);
1637 if (WideAddRec.first != SE->getSCEV(WideUse)) {
1638 LLVM_DEBUG(
dbgs() <<
"Wide use expression mismatch: " << *WideUse <<
": " 1639 << *SE->getSCEV(WideUse) <<
" != " << *WideAddRec.first
1641 DeadInsts.emplace_back(WideUse);
1645 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1652 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1653 bool NonNegativeDef =
1655 SE->getConstant(NarrowSCEV->
getType(), 0));
1660 if (!Widened.insert(NarrowUser).second)
1663 bool NonNegativeUse =
false;
1664 if (!NonNegativeDef) {
1666 if (
auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1667 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1670 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1671 NonNegativeDef || NonNegativeUse);
1690 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1691 ? SE->getSignExtendExpr(AddRec, WideType)
1692 : SE->getZeroExtendExpr(AddRec, WideType);
1694 assert(SE->getEffectiveSCEVType(WideIVExpr->
getType()) == WideType &&
1695 "Expect the new IV expression to preserve its type");
1699 if (!AddRec || AddRec->
getLoop() != L)
1708 "Loop header phi recurrence inputs do not dominate the loop");
1720 if (UsePostIncrementRanges)
1721 calculatePostIncRanges(OrigPhi);
1728 WidePhi = cast<PHINode>(Rewriter.
expandCodeFor(AddRec, WideType, InsertPt));
1736 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1737 WideIncExpr = SE->getSCEV(WideInc);
1741 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1749 assert(Widened.empty() && NarrowIVUsers.empty() &&
"expect initial state" );
1751 Widened.insert(OrigPhi);
1752 pushNarrowIVUsers(OrigPhi, WidePhi);
1754 while (!NarrowIVUsers.empty()) {
1755 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1763 pushNarrowIVUsers(DU.NarrowUse, WideUse);
1766 if (DU.NarrowDef->use_empty())
1767 DeadInsts.emplace_back(DU.NarrowDef);
1776 for (
auto &DbgValue : DbgValues)
1777 DbgValue->setOperand(0, MDPhi);
1783 void WidenIV::calculatePostIncRange(
Instruction *NarrowDef,
1787 Value *NarrowDefLHS;
1788 const APInt *NarrowDefRHS;
1794 auto UpdateRangeFromCondition = [&] (
Value *Condition,
1805 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1806 auto CmpConstrainedLHSRange =
1808 auto NarrowDefRange =
1809 CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS);
1811 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1814 auto UpdateRangeFromGuards = [&](
Instruction *Ctx) {
1819 Ctx->getParent()->rend())) {
1821 if (
match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
m_Value(C))))
1822 UpdateRangeFromCondition(C,
true);
1826 UpdateRangeFromGuards(NarrowUser);
1831 if (!DT->isReachableFromEntry(NarrowUserBB))
1834 for (
auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1836 DTB = DTB->getIDom()) {
1837 auto *BB = DTB->getBlock();
1839 UpdateRangeFromGuards(TI);
1842 if (!BI || !BI->isConditional())
1846 auto *FalseSuccessor = BI->getSuccessor(1);
1848 auto DominatesNarrowUser = [
this, NarrowUser] (
BasicBlockEdge BBE) {
1849 return BBE.isSingleEdge() &&
1850 DT->dominates(BBE, NarrowUser->
getParent());
1854 UpdateRangeFromCondition(BI->getCondition(),
true);
1857 UpdateRangeFromCondition(BI->getCondition(),
false);
1862 void WidenIV::calculatePostIncRanges(
PHINode *OrigPhi) {
1868 while (!Worklist.
empty()) {
1871 for (Use &U : NarrowDef->
uses()) {
1872 auto *NarrowUser = cast<Instruction>(U.getUser());
1875 auto *NarrowUserLoop = (*LI)[NarrowUser->
getParent()];
1876 if (!NarrowUserLoop || !L->
contains(NarrowUserLoop))
1879 if (!Visited.
insert(NarrowUser).second)
1884 calculatePostIncRange(NarrowDef, NarrowUser);
1899 class IndVarSimplifyVisitor :
public IVVisitor {
1910 : SE(SCEV), TTI(TTI), IVPhi(IV) {
1912 WI.NarrowIV = IVPhi;
1926 bool IndVarSimplify::simplifyAndExtend(
Loop *L,
1931 auto *GuardDecl = L->
getBlocks()[0]->getModule()->getFunction(
1933 bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1943 bool Changed =
false;
1944 while (!LoopPhis.
empty()) {
1955 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1960 if (Visitor.WI.WidestNativeType) {
1963 }
while(!LoopPhis.
empty());
1966 WidenIV Widener(WideIVs.
back(), LI, SE, DT, DeadInsts, HasGuards);
1967 if (
PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1996 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1997 BackedgeTakenCount->
isZero())
2021 case Instruction::Sub:
2023 case Instruction::GetElementPtr:
2038 if (IncI->
getOpcode() == Instruction::GetElementPtr)
2060 assert(BI &&
"expected exit branch");
2109 if (isa<Constant>(V))
2110 return !isa<UndefValue>(V);
2153 if (U != Cond && U != IncV)
return false;
2156 if (U != Cond && U != Phi)
return false;
2182 const SCEV *BestInit =
nullptr;
2184 assert(LatchBlock &&
"needsLFTR should guarantee a loop latch");
2208 if (!Step || !Step->
isOne())
2231 if (BestPhi && !
AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2245 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->
getType()))
2278 "Computed iteration count is not loop invariant!");
2287 cast<PointerType>(GEPBase->
getType())
2288 ->getElementType())->isOne() &&
2289 "unit stride pointer IV must be i8*");
2292 return Builder.
CreateGEP(
nullptr, GEPBase, GEPOffset,
"lftr.limit");
2305 const SCEV *IVLimit =
nullptr;
2325 "Computed iteration count is not loop invariant!");
2340 bool IndVarSimplify::
2341 linearFunctionTestReplace(
Loop *L,
const SCEV *BackedgeTakenCount,
2346 Value *CmpIndVar = IndVar;
2347 const SCEV *IVCount = BackedgeTakenCount;
2358 IVCount = SE->getAddExpr(BackedgeTakenCount,
2359 SE->getOne(BackedgeTakenCount->
getType()));
2369 "genLoopLimit missed a cast");
2374 if (L->
contains(BI->getSuccessor(0)))
2379 LLVM_DEBUG(
dbgs() <<
"INDVARS: Rewriting loop exit condition to:\n" 2380 <<
" LHS:" << *CmpIndVar <<
'\n' 2383 <<
" RHS:\t" << *ExitCnt <<
"\n" 2384 <<
" IVCount:\t" << *IVCount <<
"\n");
2390 if (
auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2395 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->
getType());
2396 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->
getType());
2397 if (CmpIndVarSize > ExitCntSize) {
2398 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2402 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
2403 const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
2404 APInt Count = cast<SCEVConstant>(IVCount)->getAPInt();
2407 if (IVCount != BackedgeTakenCount && Count == 0) {
2412 Count = Count.
zext(CmpIndVarSize);
2414 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2415 NewLimit = Start - Count;
2417 NewLimit = Start + Count;
2426 bool Extended =
false;
2427 const SCEV *IV = SE->getSCEV(CmpIndVar);
2428 const SCEV *ZExtTrunc =
2429 SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2433 if (ZExtTrunc == IV) {
2438 const SCEV *SExtTrunc =
2439 SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2442 if (SExtTrunc == IV) {
2455 Value *OrigCond = BI->getCondition();
2461 BI->setCondition(Cond);
2462 DeadInsts.push_back(OrigCond);
2475 bool IndVarSimplify::sinkUnusedInvariants(
Loop *L) {
2477 if (!ExitBlock)
return false;
2480 if (!Preheader)
return false;
2482 bool MadeAnyChanges =
false;
2485 while (I != Preheader->
begin()) {
2488 if (isa<PHINode>(I))
2501 if (isa<DbgInfoIntrinsic>(I))
2512 if (isa<AllocaInst>(I))
2517 bool UsedInLoop =
false;
2518 for (Use &U : I->
uses()) {
2521 if (
PHINode *
P = dyn_cast<PHINode>(User)) {
2524 UseBB =
P->getIncomingBlock(i);
2526 if (UseBB == Preheader || L->
contains(UseBB)) {
2540 if (I != Preheader->
begin()) {
2544 }
while (isa<DbgInfoIntrinsic>(I) && I != Preheader->
begin());
2546 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->
begin())
2552 MadeAnyChanges =
true;
2558 return MadeAnyChanges;
2565 bool IndVarSimplify::run(
Loop *L) {
2568 "LCSSA required to run indvars!");
2569 bool Changed =
false;
2585 Changed |= rewriteNonIntegerIVs(L);
2587 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2602 Changed |= simplifyAndExtend(L, Rewriter, LI);
2611 !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2612 Changed |= rewriteLoopExitValues(L, Rewriter);
2633 Changed |= linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
2644 while (!DeadInsts.empty())
2646 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2653 Changed |= sinkUnusedInvariants(L);
2658 Changed |= rewriteFirstIterationLoopExitValues(L);
2665 "Indvars did not preserve LCSSA!");
2670 if (
VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2672 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2673 if (SE->getTypeSizeInBits(BackedgeTakenCount->
getType()) <
2674 SE->getTypeSizeInBits(NewBECount->
getType()))
2675 NewBECount = SE->getTruncateOrNoop(NewBECount,
2676 BackedgeTakenCount->
getType());
2678 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2680 assert(BackedgeTakenCount == NewBECount &&
"indvars must preserve SCEV");
2693 IndVarSimplify IVS(&AR.
LI, &AR.
SE, &AR.
DT, DL, &AR.
TLI, &AR.
TTI);
2704 struct IndVarSimplifyLegacyPass :
public LoopPass {
2707 IndVarSimplifyLegacyPass() :
LoopPass(ID) {
2715 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2716 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2717 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2718 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2719 auto *TLI = TLIP ? &TLIP->getTLI() :
nullptr;
2720 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2724 IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2739 "Induction Variable Simplification",
false,
false)
2745 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.
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...
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.
This class represents lattice values for constants.
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 class represents zero extension of integer types.
void push_back(const T &Elt)
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))
This class represents a sign extension of integer types.
static IntegerType * getInt64Ty(LLVMContext &C)
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
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.
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.
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.
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.
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.