60 #define DEBUG_TYPE "simple-loop-unswitch" 64 STATISTIC(NumBranches,
"Number of branches unswitched");
65 STATISTIC(NumSwitches,
"Number of switches unswitched");
66 STATISTIC(NumGuards,
"Number of guards turned into branches for unswitching");
67 STATISTIC(NumTrivial,
"Number of unswitches that are trivial");
69 NumCostMultiplierSkipped,
70 "Number of unswitch candidates that had their cost multiplier skipped");
74 cl::desc(
"Forcibly enables non-trivial loop unswitching rather than " 75 "following the configuration passed into the pass."));
79 cl::desc(
"The cost threshold for unswitching a loop."));
83 cl::desc(
"Enable unswitch cost multiplier that prohibits exponential " 84 "explosion in nontrivial unswitch."));
87 cl::desc(
"Toplevel siblings divisor for cost multiplier."));
90 cl::desc(
"Number of unswitch candidates that are ignored when calculating " 94 cl::desc(
"If enabled, simple loop unswitching will also consider " 95 "llvm.experimental.guard intrinsics as unswitch candidates."));
108 "Only need to walk the graph if root itself is not invariant.");
120 if (isa<Constant>(OpV))
125 Invariants.push_back(OpV);
135 if (Visited.
insert(OpI).second)
138 }
while (!Worklist.
empty());
145 assert(!isa<Constant>(Invariant) &&
"Why are we unswitching on a constant?");
148 for (
auto UI = Invariant->
use_begin(), UE = Invariant->
use_end(); UI != UE;) {
155 U->set(&Replacement);
188 IRB.
CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
189 Direction ? &NormalSucc : &UnswitchedSucc);
206 for (
auto i : seq<int>(0, PN.getNumOperands())) {
207 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
208 "Found incoming block different from unique predecessor!");
209 PN.setIncomingBlock(i, &OldPH);
226 assert(&ExitBB != &UnswitchedBB &&
227 "Must have different loop exit and unswitched blocks!");
231 PN.getName() +
".split", InsertPt);
242 for (
int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
243 if (PN.getIncomingBlock(i) != &OldExitingBB)
246 Value *Incoming = PN.getIncomingValue(i);
249 PN.removeIncomingValue(i);
251 NewPN->addIncoming(Incoming, &OldPH);
257 NewPN->addIncoming(&PN, &ExitBB);
276 Loop *NewParentL =
nullptr;
277 for (
auto *ExitBB : Exits)
279 if (!NewParentL || NewParentL->
contains(ExitL))
282 if (NewParentL == OldParentL)
288 "Can only hoist this loop up the nest!");
293 "Parent loop of this loop should contain this loop's preheader!");
308 for (
Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
312 return BB == &Preheader || L.
contains(BB);
315 OldContainingL->getBlocksSet().erase(&Preheader);
317 OldContainingL->getBlocksSet().erase(BB);
339 Loop *Current = TopMost;
369 LLVM_DEBUG(
dbgs() <<
" Trying to unswitch branch: " << BI <<
"\n");
376 bool FullUnswitch =
false;
382 if (
auto *CondInst = dyn_cast<Instruction>(BI.
getCondition()))
384 if (Invariants.
empty())
390 bool ExitDirection =
true;
391 int LoopExitSuccIdx = 0;
394 ExitDirection =
false;
400 auto *ContinueBB = BI.
getSuccessor(1 - LoopExitSuccIdx);
421 dbgs() <<
" unswitching trivial invariant conditions for: " << BI
423 for (
Value *Invariant : Invariants) {
424 dbgs() <<
" " << *Invariant <<
" == true";
425 if (Invariant != Invariants.back())
456 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
458 "A branch's parent isn't a predecessor!");
459 UnswitchedBB = LoopExitBB;
462 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
481 ParentBB->getInstList().push_back(BI.
clone());
495 "Must have an `or` of `i1`s for the condition!");
499 "Must have an `and` of `i1`s for the condition!");
501 *UnswitchedBB, *NewPH);
519 ParentBB->getTerminator()->eraseFromParent();
531 if (UnswitchedBB == LoopExitBB)
535 *ParentBB, *OldPH, FullUnswitch);
546 for (
Value *Invariant : Invariants)
592 LLVM_DEBUG(
dbgs() <<
" Trying to unswitch switch: " << SI <<
"\n");
602 for (
auto Case : SI.
cases()) {
603 auto *SuccBB = Case.getCaseSuccessor();
606 ExitCaseIndices.
push_back(Case.getCaseIndex());
615 }
else if (ExitCaseIndices.
empty())
633 if (!ExitL || ExitL->
contains(OuterL))
642 ExitCases.reserve(ExitCaseIndices.
size());
650 if (!ExitL || ExitL->
contains(OuterL))
654 ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(),
W);
668 BasicBlock *CommonSuccBB =
nullptr;
672 return Case.getCaseSuccessor() ==
675 CommonSuccBB = SI.
case_begin()->getCaseSuccessor();
676 if (!DefaultExitBB) {
683 CommonSuccBB =
nullptr;
709 UnswitchedExitBBs.
insert(DefaultExitBB);
717 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
722 for (
auto &ExitCase :
reverse(ExitCases)) {
724 BasicBlock *ExitBB = std::get<1>(ExitCase);
730 if (UnswitchedExitBBs.
insert(ExitBB).second)
737 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
746 std::get<1>(ExitCase) = SplitExitBB;
751 for (
auto &ExitCase :
reverse(ExitCases)) {
752 ConstantInt *CaseVal = std::get<0>(ExitCase);
753 BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
755 NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
761 NewSIW->setDefaultDest(DefaultExitBB);
762 NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
766 for (
const auto &Case : SI.
cases())
767 NewSIW.addCase(Case.getCaseValue(), NewPH,
769 }
else if (DefaultCaseWeight) {
771 uint64_t SW = *DefaultCaseWeight;
772 for (
const auto &Case : SI.
cases()) {
775 "case weight must be defined as default case weight is defined");
778 NewSIW.setSuccessorWeight(0, SW);
790 bool SkippedFirst = DefaultExitBB ==
nullptr;
791 for (
auto Case : SI.
cases()) {
792 assert(Case.getCaseSuccessor() == CommonSuccBB &&
793 "Non-common successor!");
805 }
else if (DefaultExitBB) {
807 "If we had no cases we'd have a common successor!");
812 auto LastCaseI = std::prev(SI.
case_end());
825 for (
auto *UnswitchedExitBB : UnswitchedExitBBs) {
829 for (
auto SplitUnswitchedPair : SplitExitBBMap) {
871 bool Changed =
false;
886 Visited.
insert(CurrentBB);
893 if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
901 if (
auto *
SI = dyn_cast<SwitchInst>(CurrentTerm)) {
905 if (isa<Constant>(
SI->getCondition()))
920 if (!BI || BI->isConditional())
923 CurrentBB = BI->getSuccessor(0);
935 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
949 if (BI->isConditional())
953 CurrentBB = BI->getSuccessor(0);
958 }
while (L.
contains(CurrentBB) && Visited.
insert(CurrentBB).second);
1006 VMap[OldBB] = NewBB;
1014 auto It = DominatingSucc.
find(BB);
1015 return It != DominatingSucc.
end() && It->second != UnswitchedSuccBB;
1019 auto *ClonedPH = CloneBlock(LoopPH);
1022 for (
auto *LoopBB : L.
blocks())
1023 if (!SkipBlock(LoopBB))
1029 for (
auto *ExitBB : ExitBlocks) {
1030 if (SkipBlock(ExitBB))
1038 auto *MergeBB =
SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
1044 ExitBB->setName(
Twine(MergeBB->getName()) +
".split");
1047 auto *ClonedExitBB = CloneBlock(ExitBB);
1048 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1049 "Exit block should have been split to have one successor!");
1050 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1051 "Cloned exit block has the wrong successor!");
1057 std::prev(ClonedExitBB->end())))) {
1064 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1065 "Bad instruction in exit block!");
1067 assert(VMap.
lookup(&I) == &ClonedI &&
"Mismatch in the value map!");
1071 &*MergeBB->getFirstInsertionPt());
1073 MergePN->addIncoming(&I, ExitBB);
1074 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1083 for (
auto *ClonedBB : NewBlocks)
1087 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
1088 if (II->getIntrinsicID() == Intrinsic::assume)
1094 for (
auto *LoopBB : L.
blocks())
1095 if (SkipBlock(LoopBB))
1097 if (
auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.
lookup(SuccBB)))
1098 for (
PHINode &PN : ClonedSuccBB->phis())
1099 PN.removeIncomingValue(LoopBB,
false);
1103 auto *ClonedParentBB = cast<BasicBlock>(VMap.
lookup(ParentBB));
1105 if (SuccBB == UnswitchedSuccBB)
1108 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.
lookup(SuccBB));
1112 ClonedSuccBB->removePredecessor(ClonedParentBB,
1118 auto *ClonedSuccBB = cast<BasicBlock>(VMap.
lookup(UnswitchedSuccBB));
1119 ClonedParentBB->getTerminator()->eraseFromParent();
1125 for (
PHINode &PN : ClonedSuccBB->phis()) {
1129 for (
int i = PN.getNumOperands() - 1; i >= 0; --i) {
1130 if (PN.getIncomingBlock(i) != ClonedParentBB)
1136 PN.removeIncomingValue(i,
false);
1142 for (
auto *ClonedBB : NewBlocks) {
1144 if (SuccSet.
insert(SuccBB).second)
1145 DTUpdates.
push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1160 auto AddClonedBlocksToLoop = [&](
Loop &OrigL,
Loop &ClonedL) {
1161 assert(ClonedL.getBlocks().empty() &&
"Must start with an empty loop!");
1163 for (
auto *BB : OrigL.
blocks()) {
1164 auto *ClonedBB = cast<BasicBlock>(VMap.
lookup(BB));
1165 ClonedL.addBlockEntry(ClonedBB);
1178 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1180 if (OrigRootL.
empty())
1190 LoopsToClone.
push_back({ClonedRootL, ChildL});
1192 Loop *ClonedParentL, *L;
1193 std::tie(ClonedParentL, L) = LoopsToClone.
pop_back_val();
1196 AddClonedBlocksToLoop(*L, *ClonedL);
1198 LoopsToClone.
push_back({ClonedL, ChildL});
1199 }
while (!LoopsToClone.
empty());
1220 Loop *ClonedL =
nullptr;
1225 auto *ClonedPH = cast<BasicBlock>(VMap.
lookup(OrigPH));
1226 auto *ClonedHeader = cast<BasicBlock>(VMap.
lookup(OrigHeader));
1232 Loop *ParentL =
nullptr;
1236 for (
auto *ExitBB : ExitBlocks)
1237 if (
auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.
lookup(ExitBB)))
1239 ExitLoopMap[ClonedExitBB] = ExitL;
1240 ClonedExitsInLoops.
push_back(ClonedExitBB);
1241 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1246 "The computed parent loop should always contain (or be) the parent of " 1247 "the original loop.");
1254 for (
auto *BB : OrigL.
blocks())
1255 if (
auto *ClonedBB = cast_or_null<BasicBlock>(VMap.
lookup(BB)))
1256 ClonedLoopBlocks.
insert(ClonedBB);
1267 if (Pred == ClonedPH)
1272 assert(ClonedLoopBlocks.count(Pred) &&
"Found a predecessor of the loop " 1273 "header other than the preheader " 1274 "that is not part of the loop!");
1279 if (BlocksInClonedLoop.
insert(Pred).second && Pred != ClonedHeader)
1286 if (!BlocksInClonedLoop.
empty()) {
1287 BlocksInClonedLoop.
insert(ClonedHeader);
1289 while (!Worklist.
empty()) {
1292 "Didn't put block into the loop set!");
1300 if (ClonedLoopBlocks.count(Pred) &&
1301 BlocksInClonedLoop.
insert(Pred).second)
1308 ParentL->addChildLoop(ClonedL);
1320 for (
auto *BB : OrigL.
blocks()) {
1321 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.
lookup(BB));
1322 if (!ClonedBB || !BlocksInClonedLoop.
count(ClonedBB))
1335 PL->addBlockEntry(ClonedBB);
1342 for (
Loop *ChildL : OrigL) {
1343 auto *ClonedChildHeader =
1344 cast_or_null<BasicBlock>(VMap.
lookup(ChildL->getHeader()));
1345 if (!ClonedChildHeader || !BlocksInClonedLoop.
count(ClonedChildHeader))
1351 for (
auto *ChildLoopBB : ChildL->blocks())
1353 cast<BasicBlock>(VMap.
lookup(ChildLoopBB))) &&
1354 "Child cloned loop has a header within the cloned outer " 1355 "loop but not all of its blocks!");
1370 if (BlocksInClonedLoop.
empty())
1371 UnloopedBlockSet.
insert(ClonedPH);
1372 for (
auto *ClonedBB : ClonedLoopBlocks)
1373 if (!BlocksInClonedLoop.
count(ClonedBB))
1374 UnloopedBlockSet.
insert(ClonedBB);
1380 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1388 while (!UnloopedBlockSet.
empty() && !OrderedClonedExitsInLoops.empty()) {
1389 assert(Worklist.
empty() &&
"Didn't clear worklist!");
1391 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1406 if (!UnloopedBlockSet.
erase(PredBB)) {
1408 (BlocksInClonedLoop.
count(PredBB) || ExitLoopMap.
count(PredBB)) &&
1409 "Predecessor not mapped to a loop!");
1416 bool Inserted = ExitLoopMap.
insert({PredBB, ExitL}).
second;
1418 assert(Inserted &&
"Should only visit an unlooped block once!");
1423 }
while (!Worklist.
empty());
1432 for (
auto *BB : llvm::concat<BasicBlock *const>(
1433 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1435 OuterL->addBasicBlockToLoop(BB, LI);
1438 for (
auto &BBAndL : ExitLoopMap) {
1439 auto *BB = BBAndL.first;
1440 auto *OuterL = BBAndL.second;
1442 "Failed to put all blocks into outer loops!");
1449 for (
Loop *ChildL : OrigL) {
1450 auto *ClonedChildHeader =
1451 cast_or_null<BasicBlock>(VMap.
lookup(ChildL->getHeader()));
1452 if (!ClonedChildHeader || BlocksInClonedLoop.
count(ClonedChildHeader))
1456 for (
auto *ChildLoopBB : ChildL->blocks())
1458 "Cloned a child loop header but not all of that loops blocks!");
1462 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1468 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1472 for (
BasicBlock *BB : llvm::concat<BasicBlock *const>(L.
blocks(), ExitBlocks))
1473 for (
auto &VMap : VMaps)
1474 if (
BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1477 SuccBB->removePredecessor(ClonedBB);
1490 BB->dropAllReferences();
1493 BB->eraseFromParent();
1509 while (!DeathCandidates.empty()) {
1510 auto *BB = DeathCandidates.pop_back_val();
1513 SuccBB->removePredecessor(BB);
1514 DeathCandidates.push_back(SuccBB);
1531 for (
auto *BB : DeadBlockSet)
1532 ParentL->getBlocksSet().erase(BB);
1534 [&](
BasicBlock *BB) {
return DeadBlockSet.count(BB); });
1540 if (!DeadBlockSet.
count(ChildL->getHeader()))
1545 return DeadBlockSet.
count(ChildBB);
1547 "If the child loop header is dead all blocks in the child loop must " 1548 "be dead as well!");
1556 for (
auto *BB : DeadBlockSet) {
1558 assert(!DT.
getNode(BB) &&
"Should already have cleared domtree!");
1565 for (
auto *BB : DeadBlockSet)
1599 assert(L.
contains(Pred) &&
"Found a predecessor of the loop header other " 1600 "than the preheader that is not part of the " 1606 if (LoopBlockSet.
insert(Pred).second && Pred != Header)
1611 if (LoopBlockSet.
empty())
1612 return LoopBlockSet;
1615 while (!Worklist.
empty()) {
1617 assert(LoopBlockSet.
count(BB) &&
"Didn't put block into the loop set!");
1630 "Should not reach a loop *outside* this loop!");
1633 auto *InnerPH = InnerL->getLoopPreheader();
1634 assert(L.
contains(InnerPH) &&
"Cannot contain an inner loop block " 1635 "but not contain the inner loop " 1637 if (!LoopBlockSet.
insert(InnerPH).second)
1647 for (
auto *InnerBB : InnerL->blocks()) {
1648 if (InnerBB == BB) {
1650 "Block should already be in the set!");
1654 LoopBlockSet.
insert(InnerBB);
1670 assert(LoopBlockSet.
count(Header) &&
"Cannot fail to add the header!");
1674 return LoopBlockSet;
1698 Loop *ParentL =
nullptr;
1702 for (
auto *ExitBB : ExitBlocks)
1706 if (!ParentL || (ParentL != ExitL && ParentL->
contains(ExitL)))
1718 if (!LoopBlockSet.empty() && L.
getParentLoop() != ParentL) {
1722 IL->getBlocksSet().erase(PH);
1723 for (
auto *BB : L.
blocks())
1724 IL->getBlocksSet().erase(BB);
1741 LoopBlockSet.empty()
1743 : std::stable_partition(
1744 Blocks.begin(), Blocks.end(),
1745 [&](
BasicBlock *BB) {
return LoopBlockSet.count(BB); });
1749 if (LoopBlockSet.empty())
1750 UnloopedBlocks.
insert(PH);
1753 for (
auto *BB :
make_range(BlocksSplitI, Blocks.end()))
1755 Blocks.erase(BlocksSplitI, Blocks.end());
1767 auto RemoveUnloopedBlocksFromLoop =
1769 for (
auto *BB : UnloopedBlocks)
1772 return UnloopedBlocks.count(BB);
1777 while (!UnloopedBlocks.empty() && !ExitsInLoops.
empty()) {
1778 assert(Worklist.
empty() &&
"Didn't clear worklist!");
1779 assert(NewExitLoopBlocks.empty() &&
"Didn't clear loop set!");
1784 assert(ExitL.
contains(&L) &&
"Exit loop must contain the inner loop!");
1790 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->
getParentLoop())
1791 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1805 if (!UnloopedBlocks.erase(PredBB)) {
1806 assert((NewExitLoopBlocks.count(PredBB) ||
1808 "Predecessor not in a nested loop (or already visited)!");
1815 bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1817 assert(Inserted &&
"Should only visit an unlooped block once!");
1822 }
while (!Worklist.
empty());
1827 for (
auto *BB : NewExitLoopBlocks)
1834 NewExitLoopBlocks.clear();
1840 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1841 for (
auto *BB : UnloopedBlocks)
1850 auto SubLoopsSplitI =
1851 LoopBlockSet.empty()
1853 : std::stable_partition(
1854 SubLoops.begin(), SubLoops.end(), [&](
Loop *SubL) {
1855 return LoopBlockSet.count(SubL->getHeader());
1857 for (
auto *HoistedL :
make_range(SubLoopsSplitI, SubLoops.end())) {
1859 HoistedL->setParentLoop(
nullptr);
1869 if (
auto *NewParentL = LI.
getLoopFor(HoistedL->getLoopPreheader()))
1870 NewParentL->addChildLoop(HoistedL);
1874 SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1877 if (Blocks.empty()) {
1878 assert(SubLoops.empty() &&
1879 "Failed to remove all subloops from the original loop!");
1894 template <
typename CallableT>
1912 "Cannot visit a node twice when walking a tree!");
1915 }
while (!DomWorklist.
empty());
1930 "Can only unswitch switches and conditional branch!");
1931 bool FullUnswitch = SI || BI->
getCondition() == Invariants[0];
1934 "Cannot have other invariants with full unswitching!");
1937 "Partial unswitching requires an instruction as the condition!");
1950 if (!FullUnswitch) {
1954 "Only `or` and `and` instructions can combine invariants being " 1962 BI ? BI->
getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1967 for (
auto Case : SI->cases())
1968 if (Case.getCaseSuccessor() != RetainedSuccBB)
1969 UnswitchedSuccBBs.
insert(Case.getCaseSuccessor());
1971 assert(!UnswitchedSuccBBs.
count(RetainedSuccBB) &&
1972 "Should not unswitch the same successor we are retaining!");
1990 Loop *OuterExitL = &L;
1991 for (
auto *ExitBB : ExitBlocks) {
1993 if (!NewOuterExitL) {
1995 OuterExitL =
nullptr;
1998 if (NewOuterExitL != OuterExitL && NewOuterExitL->
contains(OuterExitL))
1999 OuterExitL = NewOuterExitL;
2018 for (
auto *SuccBB : llvm::concat<BasicBlock *const>(
2020 if (SuccBB->getUniquePredecessor() ||
2022 return PredBB == ParentBB || DT.
dominates(SuccBB, PredBB);
2025 DominatingSucc[BB] = SuccBB;
2044 for (
auto *SuccBB : UnswitchedSuccBBs) {
2047 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2048 DominatingSucc, *VMaps.
back(), DTUpdates, AC, DT, LI, MSSAU);
2058 SplitBB->getInstList().
splice(SplitBB->end(), ParentBB->getInstList(), TI);
2062 ParentBB->getInstList().push_back(NewTI);
2071 assert(SI &&
"Must either be a branch or switch!");
2074 assert(SI->getDefaultDest() == RetainedSuccBB &&
2075 "Not retaining default successor!");
2076 SI->setDefaultDest(LoopPH);
2077 for (
auto &Case : SI->cases())
2078 if (Case.getCaseSuccessor() == RetainedSuccBB)
2079 Case.setSuccessor(LoopPH);
2081 Case.setSuccessor(ClonedPHs.
find(Case.getCaseSuccessor())->
second);
2087 DTUpdates.push_back(
2102 for (
auto &VMap : VMaps)
2117 assert(UnswitchedSuccBBs.size() == 1 &&
2118 "Only one possible unswitched block for a branch!");
2120 UnswitchedSuccBB->removePredecessor(ParentBB,
2132 "Not retaining default successor!");
2133 for (
auto &Case : NewSI->
cases())
2134 Case.getCaseSuccessor()->removePredecessor(
2146 ParentBB->getTerminator()->eraseFromParent();
2152 assert(BI &&
"Only branches have partial unswitching.");
2153 assert(UnswitchedSuccBBs.size() == 1 &&
2154 "Only one possible unswitched block for a branch!");
2159 *ClonedPH, *LoopPH);
2167 for (
auto &VMap : VMaps)
2187 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2216 assert(UnswitchedSuccBBs.size() == 1 &&
2217 "Only one possible unswitched block for a branch!");
2229 bool ReplaceUnswitched = FullUnswitch || (Invariants.
size() == 1);
2237 for (
Value *Invariant : Invariants)
2238 for (
auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2249 U->set(ContinueReplacement);
2250 else if (ReplaceUnswitched &&
2252 U->set(UnswitchedReplacement);
2268 auto UpdateLoop = [&](
Loop &UpdateL) {
2270 UpdateL.verifyLoop();
2271 for (
Loop *ChildL : UpdateL) {
2272 ChildL->verifyLoop();
2273 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2274 "Perturbed a child loop's LCSSA form!");
2294 for (
Loop *UpdatedL :
2295 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2296 UpdateLoop(*UpdatedL);
2297 if (!UpdatedL->getParentLoop())
2298 OuterExitL =
nullptr;
2303 OuterExitL =
nullptr;
2308 if (OuterExitL != &L)
2309 for (
Loop *OuterL = ParentL; OuterL != OuterExitL;
2311 UpdateLoop(*OuterL);
2323 for (
Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2324 if (UpdatedL->getParentLoop() == ParentL)
2326 UnswitchCB(IsStillLoop, SibLoops);
2350 if (BBCostIt == BBCostMap.
end())
2354 auto DTCostIt = DTCostMap.
find(&N);
2355 if (DTCostIt != DTCostMap.
end())
2356 return DTCostIt->second;
2360 int Cost = std::accumulate(
2366 assert(Inserted &&
"Should not insert a node while visiting children!");
2406 if (Successors.
insert(Succ).second)
2407 DTUpdates.
push_back({DominatorTree::Delete, CheckBB, Succ});
2416 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2417 GuardedBlock->
setName(
"guarded");
2418 CheckBI->getSuccessor(1)->setName(
"deopt");
2419 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2422 ExitBlocks.
push_back(CheckBI->getSuccessor(1));
2432 DTUpdates.
push_back({DominatorTree::Insert, CheckBB, Succ});
2436 for (
auto *Succ : Successors)
2471 UnswitchCandidates) {
2484 NumCostMultiplierSkipped++;
2489 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2490 : std::distance(LI.
begin(), LI.
end()));
2493 int UnswitchedClones = 0;
2494 for (
auto Candidate : UnswitchCandidates) {
2497 bool SkipExitingSuccessors = DT.
dominates(CondBlock, Latch);
2499 if (!SkipExitingSuccessors)
2505 return !SkipExitingSuccessors || L.
contains(SuccBB);
2507 UnswitchedClones +=
Log2_32(NonExitingSuccessors);
2515 unsigned ClonesPower =
2519 int SiblingsMultiplier =
2530 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2534 <<
" (siblings " << SiblingsMultiplier <<
" * clones " 2535 << (1 << ClonesPower) <<
")" 2536 <<
" for unswitch candidate: " << TI <<
"\n");
2537 return CostMultiplier;
2551 bool CollectGuards =
false;
2555 if (GuardDecl && !GuardDecl->use_empty())
2556 CollectGuards =
true;
2559 for (
auto *BB : L.
blocks()) {
2566 auto *Cond = cast<IntrinsicInst>(&
I)->getArgOperand(0);
2569 UnswitchCandidates.
push_back({&I, {Cond}});
2572 if (
auto *
SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2575 if (!isa<Constant>(
SI->getCondition()) &&
2577 UnswitchCandidates.
push_back({SI, {SI->getCondition()}});
2582 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2583 BI->getSuccessor(0) == BI->getSuccessor(1))
2587 UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2591 Instruction &CondI = *cast<Instruction>(BI->getCondition());
2592 if (CondI.
getOpcode() != Instruction::And &&
2598 if (Invariants.
empty())
2601 UnswitchCandidates.push_back({BI, std::move(Invariants)});
2605 if (UnswitchCandidates.empty())
2616 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2626 for (
auto *ExitBB : ExitBlocks)
2627 if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) {
2628 dbgs() <<
"Cannot unswitch because of cleanuppad in exit block\n";
2633 dbgs() <<
"Considering " << UnswitchCandidates.size()
2634 <<
" non-trivial loop invariant conditions for unswitching.\n");
2651 for (
auto *BB : L.
blocks()) {
2653 for (
auto &
I : *BB) {
2654 if (EphValues.count(&
I))
2657 if (
I.getType()->isTokenTy() &&
I.isUsedOutsideOfBlock(BB))
2660 if (CS.isConvergent() || CS.cannotDuplicate())
2663 Cost += TTI.getUserCost(&
I);
2665 assert(Cost >= 0 &&
"Must not have negative costs!");
2667 assert(LoopCost >= 0 &&
"Must not have negative loop costs!");
2668 BBCostMap[BB] = Cost;
2689 auto ComputeUnswitchedCost = [&](
Instruction &TI,
bool FullUnswitch) {
2693 int Cost = LoopCost;
2696 if (!Visited.
insert(SuccBB).second)
2703 if (!FullUnswitch) {
2704 auto &BI = cast<BranchInst>(TI);
2705 if (cast<Instruction>(BI.getCondition())->
getOpcode() ==
2707 if (SuccBB == BI.getSuccessor(1))
2712 "Only `and` and `or` conditions can result in a partial " 2714 if (SuccBB == BI.getSuccessor(0))
2723 if (SuccBB->getUniquePredecessor() ||
2725 return PredBB == &BB || DT.
dominates(SuccBB, PredBB);
2729 "Non-duplicated cost should never exceed total loop cost!");
2738 int SuccessorsCount =
isGuard(&TI) ? 2 : Visited.
size();
2739 assert(SuccessorsCount > 1 &&
2740 "Cannot unswitch a condition without multiple distinct successors!");
2741 return Cost * (SuccessorsCount - 1);
2744 int BestUnswitchCost = 0;
2746 for (
auto &TerminatorAndInvariants : UnswitchCandidates) {
2750 int CandidateCost = ComputeUnswitchedCost(
2751 TI, !BI || (Invariants.
size() == 1 &&
2756 int CostMultiplier =
2760 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
2761 CandidateCost *= CostMultiplier;
2763 <<
" (multiplier: " << CostMultiplier <<
")" 2764 <<
" for unswitch candidate: " << TI <<
"\n");
2767 <<
" for unswitch candidate: " << TI <<
"\n");
2770 if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2771 BestUnswitchTI = &TI;
2772 BestUnswitchCost = CandidateCost;
2773 BestUnswitchInvariants = Invariants;
2776 assert(BestUnswitchTI &&
"Failed to find loop unswitch candidate");
2780 << BestUnswitchCost <<
"\n");
2787 ExitBlocks, DT, LI, MSSAU);
2790 << BestUnswitchCost <<
") terminator: " << *BestUnswitchTI
2793 ExitBlocks, DT, LI, AC, UnswitchCB, SE, MSSAU);
2824 "Loops must be in LCSSA form before unswitching.");
2825 bool Changed =
false;
2835 UnswitchCB(
true, {});
2871 std::string LoopName = L.
getName();
2873 auto UnswitchCB = [&L, &U, &LoopName](
bool CurrentLoopValid,
2876 if (!NewLoops.empty())
2877 U.addSiblingLoops(NewLoops);
2881 if (CurrentLoopValid)
2882 U.revisitCurrentLoop();
2884 U.markLoopAsDeleted(L, LoopName);
2912 class SimpleLoopUnswitchLegacyPass :
public LoopPass {
2918 explicit SimpleLoopUnswitchLegacyPass(
bool NonTrivial =
false)
2919 :
LoopPass(ID), NonTrivial(NonTrivial) {
2948 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2949 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2950 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2951 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2955 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
2959 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2960 auto *SE = SEWP ? &SEWP->getSE() :
nullptr;
2962 auto UnswitchCB = [&L, &LPM](
bool CurrentLoopValid,
2965 for (
auto *NewL : NewLoops)
2971 if (CurrentLoopValid)
2980 bool Changed =
unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE,
2999 "Simple unswitch loops",
false,
false)
3010 return new SimpleLoopUnswitchLegacyPass(NonTrivial);
Pass interface - Implemented by all 'passes'.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
static cl::opt< int > UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden, cl::desc("The cost threshold for unswitching a loop."))
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
static cl::opt< bool > UnswitchGuards("simple-loop-unswitch-guards", cl::init(true), cl::Hidden, cl::desc("If enabled, simple loop unswitching will also consider " "llvm.experimental.guard intrinsics as unswitch candidates."))
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static BasicBlock * buildClonedLoopBlocks(Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB, ArrayRef< BasicBlock *> ExitBlocks, BasicBlock *ParentBB, BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB, const SmallDenseMap< BasicBlock *, BasicBlock *, 16 > &DominatingSucc, ValueToValueMapTy &VMap, SmallVectorImpl< DominatorTree::UpdateType > &DTUpdates, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU)
Build the cloned blocks for an unswitched copy of the given loop.
This routine provides some synthesis utilities to produce sequences of values.
reference emplace_back(ArgTypes &&... Args)
static ConstantInt * getFalse(LLVMContext &Context)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
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...
static cl::opt< bool > EnableUnswitchCostMultiplier("enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden, cl::desc("Enable unswitch cost multiplier that prohibits exponential " "explosion in nontrivial unswitch."))
static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE, MemorySSAUpdater *MSSAU)
This routine scans the loop to find a branch or switch which occurs before any side effects occur...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
std::vector< BlockT * > & getBlocksVector()
Return a direct, mutable handle to the blocks vector so that we can mutate it efficiently with techni...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
bool VerifyMemorySSA
Enables verification of MemorySSA.
This class represents lattice values for constants.
void swapSuccessors()
Swap the successors of this branch instruction.
size_type size() const
Determine the number of elements in the SetVector.
void updateExitBlocksForClonedLoop(ArrayRef< BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap, DominatorTree &DT)
Update phi nodes in exit block successors following cloning.
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
void applyInsertUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT)
Apply CFG insert updates, analogous with the DT edge updates.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
unsigned getLoopDepth() const
Return the nesting level of this loop.
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void push_back(const T &Elt)
void reserveBlocks(unsigned size)
interface to do reserve() for Blocks
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
An efficient, type-erasing, non-owning reference to a callable.
A cache of @llvm.assume calls within a function.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
LLVMContext & getContext() const
All values hold a context through their type.
auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
std::vector< LoopT * > & getSubLoopsVector()
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
void setArgOperand(unsigned i, Value *v)
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static int computeDomSubtreeCost(DomTreeNode &N, const SmallDenseMap< BasicBlock *, int, 4 > &BBCostMap, SmallDenseMap< DomTreeNode *, int, 4 > &DTCostMap)
Recursively compute the cost of a dominator subtree based on the per-block cost map provided...
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...
This defines the Use class.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB, BasicBlock &ExitBB)
Check that all the LCSSA PHI nodes in the loop exit block have trivial incoming values along this edg...
void reserve(size_type N)
CaseWeightOpt getSuccessorWeight(unsigned idx)
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
static void deleteDeadBlocksFromLoop(Loop &L, SmallVectorImpl< BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU)
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU, ScalarEvolution *SE)
Hoist the current loop up to the innermost loop containing a remaining exit.
void removeEdge(BasicBlock *From, BasicBlock *To)
Update the MemoryPhi in To following an edge deletion between From and To.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void initializeSimpleLoopUnswitchLegacyPassPass(PassRegistry &)
Legacy analysis pass which computes MemorySSA.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static constexpr UpdateKind Delete
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static void unswitchNontrivialInvariants(Loop &L, Instruction &TI, ArrayRef< Value *> Invariants, SmallVectorImpl< BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, function_ref< void(bool, ArrayRef< Loop *>)> UnswitchCB, ScalarEvolution *SE, MemorySSAUpdater *MSSAU)
SmallPtrSetImpl< const BlockT * > & getBlocksSet()
Return a direct, mutable handle to the blocks set so that we can mutate it efficiently.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void deleteSimpleAnalysisLoop(Loop *L)
Invoke deleteAnalysisLoop hook for all passes that implement simple analysis interface.
A Use represents the edge between a Value definition and its users.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Encapsulates MemorySSA, including all data associated with memory accesses.
void applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT)
Apply CFG updates, analogous with the DT edge updates.
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
const DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Direction
An enum for the direction of the loop.
void setName(const Twine &Name)
Change the name of the value.
BlockT * getHeader() const
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
static Loop * getTopMostExitingLoop(BasicBlock *ExitBB, LoopInfo &LI)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
This header provides classes for managing per-loop analyses.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
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...
void insertEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge insertion and update the tree.
static SmallPtrSet< const BasicBlock *, 16 > recomputeLoopBlockSet(Loop &L, LoopInfo &LI)
Recompute the set of blocks in a loop after unswitching.
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight...
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
iterator find(const_arg_type_t< KeyT > Val)
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
initializer< Ty > init(const Ty &Val)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
static void buildClonedLoops(Loop &OrigL, ArrayRef< BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap, LoopInfo &LI, SmallVectorImpl< Loop *> &NonChildClonedLoops)
Build the cloned loops of an original loop from unswitching.
A set of analyses that are preserved following a run of a transformation pass.
static constexpr UpdateKind Insert
static TinyPtrVector< Value * > collectHomogenousInstGraphLoopInvariants(Loop &L, Instruction &Root, LoopInfo &LI)
Collect all of the loop invariant input values transitively used by the homogeneous instruction graph...
void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM Basic Block Representation.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
void push_back(EltTy NewVal)
Conditional or Unconditional Branch instruction.
size_t size() const
size - Get the array size.
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
void removeDuplicatePhiEdgesBetween(const BasicBlock *From, const BasicBlock *To)
Update the MemoryPhi in To to have a single incoming edge from From, following a CFG change that repl...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", "Simple unswitch loops", false, false) INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass
const Instruction & front() const
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.
BasicBlock * getDefaultDest() const
void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was spliced into From and To.
Represent the analysis usage information of a pass.
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
static Loop * cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, const ValueToValueMapTy &VMap, LoopInfo &LI)
Recursively clone the specified loop and all of its children.
const T * getPointer() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool pred_empty(const BasicBlock *BB)
void updateForClonedLoop(const LoopBlocksRPO &LoopBlocks, ArrayRef< BasicBlock *> ExitBlocks, const ValueToValueMapTy &VM, bool IgnoreIncomingWithNoClones=false)
Update MemorySSA after a loop was cloned, given the blocks in RPO order, the exit blocks and a 1:1 ma...
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&... args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
static BranchInst * turnGuardIntoBranch(IntrinsicInst *GI, Loop &L, SmallVectorImpl< BasicBlock *> &ExitBlocks, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU)
Turns a llvm.experimental.guard intrinsic into implicit control flow branch, making the following rep...
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.
static void buildPartialUnswitchConditionalBranch(BasicBlock &BB, ArrayRef< Value *> Invariants, bool Direction, BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc)
Insert code to test a set of loop invariant values, and conditionally branch on them.
void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
TargetTransformInfo & TTI
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void sort(IteratorTy Start, IteratorTy End)
bool formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
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...
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
A SetVector that performs no allocations if smaller than a certain size.
static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE, MemorySSAUpdater *MSSAU)
Unswitch a trivial switch if the condition is loop invariant.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
static void replaceLoopInvariantUses(Loop &L, Value *Invariant, Constant &Replacement)
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
static cl::opt< bool > EnableNonTrivialUnswitch("enable-nontrivial-unswitch", cl::init(false), cl::Hidden, cl::desc("Forcibly enables non-trivial loop unswitching rather than " "following the configuration passed into the pass."))
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.
static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, BasicBlock &OldExitingBB, BasicBlock &OldPH)
Rewrite the PHI nodes in an unswitched loop exit basic block.
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
LoopT * AllocateLoop(ArgsTy &&... Args)
An analysis that produces MemorySSA for a function.
LLVM_NODISCARD T pop_back_val()
simple loop Simple unswitch loops
Pass * createSimpleLoopUnswitchLegacyPass(bool NonTrivial=false)
Create the legacy pass object for the simple loop unswitcher.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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...
pred_range predecessors(BasicBlock *BB)
void markLoopAsDeleted(Loop &L)
static void deleteDeadClonedBlocks(Loop &L, ArrayRef< BasicBlock *> ExitBlocks, ArrayRef< std::unique_ptr< ValueToValueMapTy >> VMaps, DominatorTree &DT, MemorySSAUpdater *MSSAU)
static ConstantInt * getTrue(LLVMContext &Context)
SymbolTableList< Instruction >::iterator eraseFromParent()
Delegate the call to the underlying SwitchInst::eraseFromParent() and mark this object to not touch t...
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental.guard intrinsic.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
static bool unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, TargetTransformInfo &TTI, function_ref< void(bool, ArrayRef< Loop *>)> UnswitchCB, ScalarEvolution *SE, MemorySSAUpdater *MSSAU)
LoopT * getParentLoop() const
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
static cl::opt< int > UnswitchSiblingsToplevelDiv("unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden, cl::desc("Toplevel siblings divisor for cost multiplier."))
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
iterator_range< value_op_iterator > operand_values()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, BasicBlock &UnswitchedBB, BasicBlock &OldExitingBB, BasicBlock &OldPH, bool FullUnswitch)
Rewrite the PHI nodes in the loop exit basic block and the split off unswitched block.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
void stable_sort(R &&Range)
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, TargetTransformInfo &TTI, bool NonTrivial, function_ref< void(bool, ArrayRef< Loop *>)> UnswitchCB, ScalarEvolution *SE, MemorySSAUpdater *MSSAU)
Unswitch control flow predicated on loop invariant conditions.
void setDefaultDest(BasicBlock *DefaultCase)
succ_range successors(Instruction *I)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
The legacy pass manager's analysis pass to compute loop information.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph...
static int calculateUnswitchCostMultiplier(Instruction &TI, Loop &L, LoopInfo &LI, DominatorTree &DT, ArrayRef< std::pair< Instruction *, TinyPtrVector< Value *>>> UnswitchCandidates)
Cost multiplier is a way to limit potentially exponential behavior of loop-unswitch.
A container for analyses that lazily runs them and caches their results.
static cl::opt< int > UnswitchNumInitialUnscaledCandidates("unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden, cl::desc("Number of unswitch candidates that are ignored when calculating " "cost multiplier."))
Legacy analysis pass which computes a DominatorTree.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
iterator_range< block_iterator > blocks() const
static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef< BasicBlock *> ExitBlocks, LoopInfo &LI, SmallVectorImpl< Loop *> &HoistedLoops)
Rebuild a loop after unswitching removes some subset of blocks and edges.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable)
Helper to visit a dominator subtree, invoking a callable on each node.
static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE, MemorySSAUpdater *MSSAU)
Unswitch a trivial branch if the condition is loop invariant.
void forgetTopmostLoop(const Loop *L)