69#define DEBUG_TYPE "simple-loop-unswitch"
74STATISTIC(NumBranches,
"Number of branches unswitched");
75STATISTIC(NumSwitches,
"Number of switches unswitched");
76STATISTIC(NumSelects,
"Number of selects turned into branches for unswitching");
77STATISTIC(NumGuards,
"Number of guards turned into branches for unswitching");
78STATISTIC(NumTrivial,
"Number of unswitches that are trivial");
80 NumCostMultiplierSkipped,
81 "Number of unswitch candidates that had their cost multiplier skipped");
83 "Number of invariant conditions injected and unswitched");
93 : Term(Term), Invariant(Invariant), InLoopSucc(InLoopSucc) {}
96struct InjectedInvariant {
97 ICmpInst::Predicate Pred;
102 InjectedInvariant(ICmpInst::Predicate Pred,
Value *LHS,
Value *RHS,
103 BasicBlock *InLoopSucc)
104 : Pred(Pred), LHS(LHS), RHS(RHS), InLoopSucc(InLoopSucc) {}
107struct NonTrivialUnswitchCandidate {
109 TinyPtrVector<Value *> Invariants;
110 std::optional<InstructionCost> Cost;
111 std::optional<InjectedInvariant> PendingInjection;
112 NonTrivialUnswitchCandidate(
114 std::optional<InstructionCost> Cost = std::nullopt,
115 std::optional<InjectedInvariant> PendingInjection = std::nullopt)
116 : TI(TI), Invariants(Invariants), Cost(Cost),
117 PendingInjection(PendingInjection) {};
119 bool hasPendingInjection()
const {
return PendingInjection.has_value(); }
143 assert(!L.isLoopInvariant(&Root) &&
144 "Only need to walk the graph if root itself is not invariant.");
157 for (
Value *OpV :
I.operand_values()) {
163 if (L.isLoopInvariant(OpV)) {
174 if (Visited.
insert(OpI).second)
178 }
while (!Worklist.
empty());
193 if (UserI && L.contains(UserI))
201 return PN && PN->getParent() == L.getHeader();
209 return cast<PHINode>(V)->getIncomingValueForBlock(L.getLoopPreheader());
220 bool AllowHeaderPHIs =
false) {
227 const Value *Incoming = PN->getIncomingValueForBlock(&ExitingBB);
228 if (!L.isLoopInvariant(Incoming) &&
252 bool HasBranchWeights = Opts.simple_loop_unswitch_estimate_profile &&
265 if (HasBranchWeights &&
266 static_cast<double>(BranchWeights[
Direction ? 0 : 1]) /
267 static_cast<double>(
sum_of(BranchWeights)) >
269 HasBranchWeights =
false;
275 for (
Value *Inv : Invariants) {
276 if (Opts.freeze_loop_unswitch_cond &&
286 Direction ? &NormalSucc : &UnswitchedSucc,
287 HasBranchWeights ? ComputeProfFrom.
getMetadata(LLVMContext::MD_prof)
289 if (!HasBranchWeights)
299 for (
auto *Val :
reverse(ToDuplicate)) {
317 auto *DefiningAccess = MemUse->getDefiningAccess();
319 while (L.contains(DefiningAccess->getBlock())) {
324 MemPhi->getIncomingValueForBlock(L.getLoopPreheader());
345 Direction ? &NormalSucc : &UnswitchedSucc, ProfData);
365 for (
auto i :
seq<int>(0, PN.getNumOperands())) {
366 assert(PN.getIncomingBlock(i) == &OldExitingBB &&
367 "Found incoming block different from unique predecessor!");
368 PN.setIncomingBlock(i, &OldPH);
384 assert(&ExitBB != &UnswitchedBB &&
385 "Must have different loop exit and unswitched blocks!");
389 PN.getName() +
".split");
390 NewPN->insertBefore(InsertPt);
401 for (
int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
402 if (PN.getIncomingBlock(i) != &OldExitingBB)
405 Value *Incoming = PN.getIncomingValue(i);
408 PN.removeIncomingValue(i);
415 PN.replaceAllUsesWith(NewPN);
416 NewPN->addIncoming(&PN, &ExitBB);
429 Loop *OldParentL = L.getParentLoop();
434 L.getExitBlocks(Exits);
435 Loop *NewParentL =
nullptr;
436 for (
auto *ExitBB : Exits)
438 if (!NewParentL || NewParentL->
contains(ExitL))
441 if (NewParentL == OldParentL)
447 "Can only hoist this loop up the nest!");
451 "Parent loop of this loop should contain this loop's preheader!");
466 for (
Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
469 return BB == &Preheader || L.contains(BB);
493 Loop *Current = TopMost;
524 LLVM_DEBUG(
dbgs() <<
" Trying to unswitch branch: " << BI <<
"\n");
531 bool FullUnswitch =
false;
534 if (L.isLoopInvariant(
Cond)) {
540 if (Invariants.
empty()) {
546 std::optional<int> LatchIdx = std::nullopt;
547 auto *LoopLatch = L.getLoopLatch();
549 if (SE && FullUnswitch && ULExit) {
556 bool ModifiedBranch =
false;
563 if (CB->isConvergent())
565 return I.mayHaveSideEffects();
578 LoopLatch->removePredecessor(BI.
getParent());
580 for (
PHINode &PN : ULExit->phis()) {
581 Value *V = PN.getIncomingValueForBlock(LoopLatch);
589 ModifiedBranch =
true;
594 bool ExitDirection =
true;
595 int LoopExitSuccIdx = 0;
597 if (L.contains(LoopExitBB)) {
598 ExitDirection =
false;
601 if (L.contains(LoopExitBB)) {
603 assert(!ModifiedBranch &&
"Modified the branch but didn't unswitch");
607 auto *ContinueBB = BI.
getSuccessor(1 - LoopExitSuccIdx);
615 LLVM_DEBUG(
dbgs() <<
" Loop exit PHI's aren't loop-invariant!\n");
628 "non-full unswitch!\n");
629 assert(!ModifiedBranch &&
"Modified the branch but didn't unswitch");
635 dbgs() <<
" unswitching trivial invariant conditions for: " << BI
637 for (
Value *Invariant : Invariants) {
638 dbgs() <<
" " << *Invariant <<
" == true";
639 if (Invariant != Invariants.back())
671 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
673 "A branch's parent isn't a predecessor!");
674 UnswitchedBB = LoopExitBB;
677 SplitBlock(LoopExitBB, LoopExitBB->begin(), &DT, &LI, MSSAU,
"");
710 "Must have an `or` of `i1`s or `select i1 X, true, Y`s for the "
714 "Must have an `and` of `i1`s or `select i1 X, Y, false`s for the"
717 Opts, *OldPH, Invariants, ExitDirection, *UnswitchedBB, *NewPH,
740 Term->eraseFromParent();
750 if (UnswitchedBB == LoopExitBB)
754 *ParentBB, *OldPH, FullUnswitch);
765 for (
Value *Invariant : Invariants)
812 Value *LoopCond =
SI.getCondition();
815 if (!L.isLoopInvariant(LoopCond))
818 auto *ParentBB =
SI.getParent();
825 auto IsTriviallyUnswitchableExitBlock = [&](
BasicBlock &BBToCheck) {
827 if (L.contains(&BBToCheck))
836 auto *TI = BBToCheck.getTerminator();
838 return !isUnreachable || &*BBToCheck.getFirstNonPHIOrDbg() != TI;
842 for (
auto Case :
SI.cases())
843 if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
844 ExitCaseIndices.
push_back(Case.getCaseIndex());
848 if (IsTriviallyUnswitchableExitBlock(*
SI.getDefaultDest())) {
849 DefaultExitBB =
SI.getDefaultDest();
850 }
else if (ExitCaseIndices.
empty())
865 if (!ExitL || ExitL->
contains(OuterL))
868 for (
unsigned Index : ExitCaseIndices) {
869 auto CaseI =
SI.case_begin() + Index;
872 if (!ExitL || ExitL->
contains(OuterL))
886 SI.setDefaultDest(
nullptr);
894 ExitCases.reserve(ExitCaseIndices.
size());
898 for (
unsigned Index :
reverse(ExitCaseIndices)) {
899 auto CaseI =
SI.case_begin() + Index;
902 ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
910 if (
SI.getNumCases() > 0 &&
912 return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor();
914 CommonSuccBB =
SI.case_begin()->getCaseSuccessor();
915 if (!DefaultExitBB) {
919 if (
SI.getNumCases() == 0)
920 CommonSuccBB =
SI.getDefaultDest();
921 else if (
SI.getDefaultDest() != CommonSuccBB)
922 CommonSuccBB =
nullptr;
951 UnswitchedExitBBs.
insert(DefaultExitBB);
960 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
965 for (
auto &ExitCase :
reverse(ExitCases)) {
973 if (UnswitchedExitBBs.
insert(ExitBB).second)
980 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
989 std::get<1>(ExitCase) = SplitExitBB;
994 for (
auto &ExitCase :
reverse(ExitCases)) {
996 BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
998 NewSIW.
addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
1003 if (DefaultExitBB) {
1009 for (
const auto &Case :
SI.cases())
1012 }
else if (DefaultCaseWeight) {
1015 for (
const auto &Case :
SI.cases()) {
1018 "case weight must be defined as default case weight is defined");
1033 bool SkippedFirst = DefaultExitBB ==
nullptr;
1034 for (
auto Case :
SI.cases()) {
1036 "Non-common successor!");
1038 if (!SkippedFirst) {
1039 SkippedFirst =
true;
1049 }
else if (DefaultExitBB) {
1051 "If we had no cases we'd have a common successor!");
1056 auto LastCaseI = std::prev(
SI.case_end());
1058 SI.setDefaultDest(LastCaseI->getCaseSuccessor());
1069 for (
auto *UnswitchedExitBB : UnswitchedExitBBs) {
1073 for (
auto SplitUnswitchedPair : SplitExitBBMap) {
1074 DTUpdates.
push_back({DT.
Delete, ParentBB, SplitUnswitchedPair.first});
1086 assert(DT.
verify(DominatorTree::VerificationLevel::Fast));
1132 Visited.
insert(CurrentBB);
1139 if (!
isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
1143 if (CB->isConvergent())
1145 return I.mayHaveSideEffects();
1173 CurrentBB = BI->getSuccessor();
1207 }
while (L.contains(CurrentBB) && Visited.
insert(CurrentBB).second);
1245 NewBlocks.
reserve(L.getNumBlocks() + ExitBlocks.
size());
1256 VMap[OldBB] = NewBB;
1264 auto It = DominatingSucc.
find(BB);
1265 return It != DominatingSucc.
end() && It->second != UnswitchedSuccBB;
1269 auto *ClonedPH = CloneBlock(LoopPH);
1272 for (
auto *LoopBB : L.blocks())
1273 if (!SkipBlock(LoopBB))
1279 for (
auto *ExitBB : ExitBlocks) {
1280 if (SkipBlock(ExitBB))
1288 auto *MergeBB =
SplitBlock(ExitBB, ExitBB->begin(), &DT, &LI, MSSAU);
1293 MergeBB->takeName(ExitBB);
1294 ExitBB->setName(
Twine(MergeBB->getName()) +
".split");
1297 auto *ClonedExitBB = CloneBlock(ExitBB);
1298 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1299 "Exit block should have been split to have one successor!");
1300 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1301 "Cloned exit block has the wrong successor!");
1307 std::prev(ClonedExitBB->end())))) {
1315 "Bad instruction in exit block!");
1317 assert(VMap.
lookup(&
I) == &ClonedI &&
"Mismatch in the value map!");
1328 MergePN->insertBefore(InsertPt);
1329 MergePN->setDebugLoc(InsertPt->getDebugLoc());
1330 I.replaceAllUsesWith(MergePN);
1331 MergePN->addIncoming(&
I, ExitBB);
1332 MergePN->addIncoming(&ClonedI, ClonedExitBB);
1341 Module *M = ClonedPH->getParent()->getParent();
1342 for (
auto *ClonedBB : NewBlocks)
1354 for (
auto *LoopBB : L.blocks())
1355 if (SkipBlock(LoopBB))
1358 for (
PHINode &PN : ClonedSuccBB->phis())
1359 PN.removeIncomingValue(LoopBB,
false);
1365 if (SuccBB == UnswitchedSuccBB)
1372 ClonedSuccBB->removePredecessor(ClonedParentBB,
1379 Instruction *ClonedTerminator = ClonedParentBB->getTerminator();
1382 Value *ClonedConditionToErase =
nullptr;
1384 ClonedConditionToErase = BI->getCondition();
1386 ClonedConditionToErase =
SI->getCondition();
1392 if (ClonedConditionToErase)
1399 for (
PHINode &PN : ClonedSuccBB->phis()) {
1403 for (
int i = PN.getNumOperands() - 1; i >= 0; --i) {
1404 if (PN.getIncomingBlock(i) != ClonedParentBB)
1410 PN.removeIncomingValue(i,
false);
1416 for (
auto *ClonedBB : NewBlocks) {
1418 if (SuccSet.
insert(SuccBB).second)
1434 auto AddClonedBlocksToLoop = [&](
Loop &OrigL,
Loop &ClonedL) {
1435 assert(ClonedL.getBlocks().empty() &&
"Must start with an empty loop!");
1437 for (
auto *BB : OrigL.
blocks()) {
1439 ClonedL.addBlockEntry(ClonedBB);
1452 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1464 LoopsToClone.
push_back({ClonedRootL, ChildL});
1466 Loop *ClonedParentL, *L;
1467 std::tie(ClonedParentL, L) = LoopsToClone.
pop_back_val();
1470 AddClonedBlocksToLoop(*L, *ClonedL);
1472 LoopsToClone.
push_back({ClonedL, ChildL});
1473 }
while (!LoopsToClone.
empty());
1494 Loop *ClonedL =
nullptr;
1506 Loop *ParentL =
nullptr;
1510 for (
auto *ExitBB : ExitBlocks)
1513 ExitLoopMap[ClonedExitBB] = ExitL;
1514 ClonedExitsInLoops.
push_back(ClonedExitBB);
1515 if (!ParentL || (ParentL != ExitL && ParentL->
contains(ExitL)))
1520 "The computed parent loop should always contain (or be) the parent of "
1521 "the original loop.");
1528 for (
auto *BB : OrigL.
blocks())
1530 ClonedLoopBlocks.
insert(ClonedBB);
1541 if (Pred == ClonedPH)
1546 assert(ClonedLoopBlocks.
count(Pred) &&
"Found a predecessor of the loop "
1547 "header other than the preheader "
1548 "that is not part of the loop!");
1553 if (BlocksInClonedLoop.
insert(Pred).second && Pred != ClonedHeader)
1560 if (!BlocksInClonedLoop.
empty()) {
1561 BlocksInClonedLoop.
insert(ClonedHeader);
1563 while (!Worklist.
empty()) {
1566 "Didn't put block into the loop set!");
1574 if (ClonedLoopBlocks.
count(Pred) &&
1575 BlocksInClonedLoop.
insert(Pred).second)
1594 for (
auto *BB : OrigL.
blocks()) {
1596 if (!ClonedBB || !BlocksInClonedLoop.
count(ClonedBB))
1608 for (
Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1609 PL->addBlockEntry(ClonedBB);
1616 for (
Loop *ChildL : OrigL) {
1617 auto *ClonedChildHeader =
1619 if (!ClonedChildHeader || !BlocksInClonedLoop.
count(ClonedChildHeader))
1625 for (
auto *ChildLoopBB : ChildL->blocks())
1628 "Child cloned loop has a header within the cloned outer "
1629 "loop but not all of its blocks!");
1644 if (BlocksInClonedLoop.
empty())
1645 UnloopedBlockSet.
insert(ClonedPH);
1646 for (
auto *ClonedBB : ClonedLoopBlocks)
1647 if (!BlocksInClonedLoop.
count(ClonedBB))
1648 UnloopedBlockSet.
insert(ClonedBB);
1654 auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1656 return ExitLoopMap.
lookup(
LHS)->getLoopDepth() <
1657 ExitLoopMap.
lookup(
RHS)->getLoopDepth();
1662 while (!UnloopedBlockSet.
empty() && !OrderedClonedExitsInLoops.empty()) {
1663 assert(Worklist.
empty() &&
"Didn't clear worklist!");
1665 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1680 if (!UnloopedBlockSet.
erase(PredBB)) {
1682 (BlocksInClonedLoop.
count(PredBB) || ExitLoopMap.
count(PredBB)) &&
1683 "Predecessor not mapped to a loop!");
1690 bool Inserted = ExitLoopMap.
insert({PredBB, ExitL}).second;
1692 assert(Inserted &&
"Should only visit an unlooped block once!");
1697 }
while (!Worklist.
empty());
1707 ArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1709 OuterL->addBasicBlockToLoop(BB, LI);
1712 for (
auto &BBAndL : ExitLoopMap) {
1713 auto *BB = BBAndL.first;
1714 auto *OuterL = BBAndL.second;
1716 "Failed to put all blocks into outer loops!");
1723 for (
Loop *ChildL : OrigL) {
1724 auto *ClonedChildHeader =
1726 if (!ClonedChildHeader || BlocksInClonedLoop.
count(ClonedChildHeader))
1730 for (
auto *ChildLoopBB : ChildL->blocks())
1732 "Cloned a child loop header but not all of that loops blocks!");
1736 *ChildL, ExitLoopMap.
lookup(ClonedChildHeader), VMap, LI));
1742 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1747 for (
const auto &VMap : VMaps)
1751 SuccBB->removePredecessor(ClonedBB);
1764 BB->dropAllReferences();
1767 BB->eraseFromParent();
1784 DeathCandidates.
append(L.blocks().begin(), L.blocks().end());
1785 while (!DeathCandidates.
empty()) {
1789 SuccBB->removePredecessor(BB);
1806 for (
Loop *Cur = &L; Cur; Cur = Cur->getParentLoop())
1812 for (
Loop *ChildL : L) {
1813 if (!DeadBlockSet.
count(ChildL->getHeader()))
1818 return DeadBlockSet.count(ChildBB);
1820 "If the child loop header is dead all blocks in the child loop must "
1821 "be dead as well!");
1827 return DeadBlockSet.count(ChildL->getHeader());
1834 for (
auto *BB : DeadBlockSet) {
1836 assert(!DT.
getNode(BB) &&
"Should already have cleared domtree!");
1843 BB->dropAllReferences();
1848 for (
auto *BB : DeadBlockSet)
1870 RemovedSet.
insert(RemovedL);
1872 for (
Loop *ChildL : Children)
1873 if (!RemovedSet.
contains(ChildL) && ChildL->getParentLoop() != &L)
1876 if (SE && !Removed.
empty())
1879 for (
auto [RemovedL, Header] : Removed) {
1881 "Unswitching can only remove loops from the current nest!");
1895template <
typename CallableT>
1907 if (!Callable(
N->getBlock()))
1913 "Cannot visit a node twice when walking a tree!");
1916 }
while (!DomWorklist.
empty());
1920 bool CurrentLoopValid,
bool PartiallyInvariant,
1923 if (!NewLoops.
empty())
1924 U.addSiblingLoops(NewLoops);
1928 if (CurrentLoopValid) {
1929 if (PartiallyInvariant) {
1932 L.addStringLoopAttribute(
"llvm.loop.unswitch.partial.disable",
1933 {
"llvm.loop.unswitch.partial"});
1934 }
else if (InjectedCondition) {
1936 L.addStringLoopAttribute(
"llvm.loop.unswitch.injection.disable",
1937 {
"llvm.loop.unswitch.injection"});
1939 U.revisitCurrentLoop();
1941 U.markLoopAsDeleted(L, LoopName);
1949 bool InjectedCondition) {
1956 std::string LoopName(L.getName());
1961 assert((
SI || BI) &&
"Can only unswitch switches and conditional branch!");
1965 !PartiallyInvariant);
1968 "Cannot have other invariants with full unswitching!");
1971 "Partial unswitching requires an instruction as the condition!");
1984 if (!FullUnswitch) {
1988 PartiallyInvariant) &&
1989 "Only `or`, `and`, an `select`, partially invariant instructions "
1990 "can combine invariants being unswitched.");
2006 for (
auto Case :
SI->cases())
2007 if (Case.getCaseSuccessor() != RetainedSuccBB)
2008 UnswitchedSuccBBs.
insert(Case.getCaseSuccessor());
2010 assert(!UnswitchedSuccBBs.
count(RetainedSuccBB) &&
2011 "Should not unswitch the same successor we are retaining!");
2020 Loop *ParentL = L.getParentLoop();
2029 Loop *OuterExitL = &L;
2031 L.getUniqueExitBlocks(ExitBlocks);
2032 for (
auto *ExitBB : ExitBlocks) {
2036 if (!NewOuterExitL) {
2038 OuterExitL =
nullptr;
2041 if (NewOuterExitL != OuterExitL && NewOuterExitL->
contains(OuterExitL))
2042 OuterExitL = NewOuterExitL;
2064 if (SuccBB->getUniquePredecessor() ||
2066 return PredBB == ParentBB || DT.
dominates(SuccBB, PredBB);
2069 DominatingSucc[BB] = SuccBB;
2088 for (
auto *SuccBB : UnswitchedSuccBBs) {
2091 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2092 DominatingSucc, *VMaps.
back(), DTUpdates, AC, DT, LI, MSSAU, SE);
2097 if (TI.
getMetadata(LLVMContext::MD_make_implicit)) {
2098 if (Opts.simple_loop_unswitch_drop_non_trivial_implicit_null_checks)
2101 TI.
setMetadata(LLVMContext::MD_make_implicit,
nullptr);
2107 TI.
setMetadata(LLVMContext::MD_make_implicit,
nullptr);
2118 NewTI->
insertInto(ParentBB, ParentBB->end());
2141 assert(
SI &&
"Must either be a branch or switch!");
2144 assert(
SI->getDefaultDest() == RetainedSuccBB &&
2145 "Not retaining default successor!");
2146 SI->setDefaultDest(LoopPH);
2147 for (
const auto &Case :
SI->cases())
2148 if (Case.getCaseSuccessor() == RetainedSuccBB)
2149 Case.setSuccessor(LoopPH);
2151 Case.setSuccessor(ClonedPHs.
find(Case.getCaseSuccessor())->second);
2155 SI->getCondition()->getName() +
".fr",
2156 SI->getIterator()));
2177 for (
auto &VMap : VMaps)
2193 "Only one possible unswitched block for a branch!");
2207 "Not retaining default successor!");
2208 for (
const auto &Case : NewSI->
cases())
2209 Case.getCaseSuccessor()->removePredecessor(
2228 assert(BI &&
"Only branches have partial unswitching.");
2230 "Only one possible unswitched block for a branch!");
2234 if (PartiallyInvariant)
2236 *SplitBB, Invariants,
Direction, *ClonedPH, *LoopPH, L, MSSAU, *BI);
2249 for (
auto &VMap : VMaps)
2269 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2287#ifdef EXPENSIVE_CHECKS
2293 assert(DT.
verify(DominatorTree::VerificationLevel::Fast));
2296 if (BI && !PartiallyInvariant) {
2302 "Only one possible unswitched block for a branch!");
2314 bool ReplaceUnswitched =
2315 FullUnswitch || (Invariants.
size() == 1) || PartiallyInvariant;
2323 for (
Value *Invariant : Invariants) {
2325 "Should not be replacing constant values!");
2335 U.set(ContinueReplacement);
2336 else if (ReplaceUnswitched &&
2338 U.set(UnswitchedReplacement);
2355 auto UpdateLoop = [&](
Loop &UpdateL) {
2357 UpdateL.verifyLoop();
2358 for (
Loop *ChildL : UpdateL) {
2359 ChildL->verifyLoop();
2360 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2361 "Perturbed a child loop's LCSSA form!");
2381 for (
Loop *UpdatedL :
2383 UpdateLoop(*UpdatedL);
2384 if (UpdatedL->isOutermost())
2385 OuterExitL =
nullptr;
2389 if (L.isOutermost())
2390 OuterExitL =
nullptr;
2395 if (OuterExitL != &L)
2396 for (
Loop *OuterL = ParentL; OuterL != OuterExitL;
2398 UpdateLoop(*OuterL);
2400#ifdef EXPENSIVE_CHECKS
2411 if (UpdatedL->getParentLoop() == ParentL)
2413 postUnswitch(L, LoopUpdater, LoopName, IsStillLoop, PartiallyInvariant,
2414 InjectedCondition, SibLoops);
2437 auto BBCostIt = BBCostMap.
find(
N.getBlock());
2438 if (BBCostIt == BBCostMap.
end())
2442 auto DTCostIt = DTCostMap.
find(&
N);
2443 if (DTCostIt != DTCostMap.
end())
2444 return DTCostIt->second;
2449 N.begin(),
N.end(), BBCostIt->second,
2451 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2453 bool Inserted = DTCostMap.
insert({&
N, Cost}).second;
2455 assert(Inserted &&
"Should not insert a node while visiting children!");
2490 SI->getMetadata(LLVMContext::MD_prof), &DTU, &LI);
2492 BasicBlock *ThenBB = CondBr->getSuccessor(0),
2493 *TailBB = CondBr->getSuccessor(1);
2499 Phi->addIncoming(
SI->getTrueValue(), ThenBB);
2500 Phi->addIncoming(
SI->getFalseValue(), HeadBB);
2501 Phi->setDebugLoc(
SI->getDebugLoc());
2502 SI->replaceAllUsesWith(Phi);
2503 SI->eraseFromParent();
2548 Opts.simple_loop_unswitch_estimate_profile
2558 GuardedBlock->
setName(
"guarded");
2609 return L.contains(SuccBB);
2611 NumCostMultiplierSkipped++;
2622 auto *ParentL = L.getParentLoop();
2623 int ParentLoopSizeMultiplier = 1;
2625 ParentLoopSizeMultiplier = std::max<int>(
2626 ParentL->getNumBlocks() / Opts.unswitch_parent_blocks_div, 1);
2633 int UnswitchedClones = 0;
2634 for (
const auto &Candidate : UnswitchCandidates) {
2637 bool SkipExitingSuccessors = DT.
dominates(CondBlock, Latch);
2643 if (!SkipExitingSuccessors)
2647 int NonExitingSuccessors =
2649 [SkipExitingSuccessors, &L](
const BasicBlock *SuccBB) {
2650 return !SkipExitingSuccessors || L.contains(SuccBB);
2652 UnswitchedClones +=
Log2_32(NonExitingSuccessors);
2660 unsigned ClonesPower = std::max(
2661 UnswitchedClones - Opts.unswitch_num_initial_unscaled_candidates, 0);
2664 int SiblingsMultiplier =
2665 std::max((ParentL ? SiblingsCount
2666 : SiblingsCount / Opts.unswitch_siblings_toplevel_div),
2671 if (ClonesPower >
Log2_32(Opts.unswitch_threshold) ||
2672 SiblingsMultiplier > Opts.unswitch_threshold ||
2673 ParentLoopSizeMultiplier > Opts.unswitch_threshold)
2674 CostMultiplier = Opts.unswitch_threshold;
2676 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2677 Opts.unswitch_threshold);
2680 <<
" (siblings " << SiblingsMultiplier <<
" * parent size "
2681 << ParentLoopSizeMultiplier <<
" * clones "
2682 << (1 << ClonesPower) <<
")"
2683 <<
" for unswitch candidate: " << TI <<
"\n");
2684 return CostMultiplier;
2688 const ScalarOptions &Opts,
2693 assert(UnswitchCandidates.
empty() &&
"Should be!");
2699 if (L.isLoopInvariant(
Cond)) {
2707 if (!Invariants.
empty())
2708 UnswitchCandidates.
push_back({
I, std::move(Invariants)});
2713 bool CollectGuards =
false;
2714 if (Opts.simple_loop_unswitch_guards) {
2716 L.getHeader()->getParent()->getParent(), Intrinsic::experimental_guard);
2717 if (GuardDecl && !GuardDecl->use_empty())
2718 CollectGuards =
true;
2721 for (
auto *BB : L.blocks()) {
2725 for (
auto &
I : *BB) {
2727 auto *
Cond =
SI->getCondition();
2729 if (
Cond->getType()->isIntegerTy(1) && !
SI->getType()->isIntegerTy(1))
2730 AddUnswitchCandidatesForInst(
SI,
Cond);
2731 }
else if (CollectGuards &&
isGuard(&
I)) {
2744 L.isLoopInvariant(
SI->getCondition()) && !BB->getUniqueSuccessor())
2750 if (!BI || BI->getSuccessor(0) == BI->getSuccessor(1))
2753 AddUnswitchCandidatesForInst(BI, BI->getCondition());
2758 bool HeaderCondGuaranteedToExecute =
2760 Header->begin(), Header->getTerminator()->getIterator());
2761 if (MSSAU && HeaderCondGuaranteedToExecute &&
2763 !
any_of(UnswitchCandidates, [&L](
auto &TerminatorAndInvariants) {
2764 return TerminatorAndInvariants.TI == L.getHeader()->getTerminator();
2768 L, Opts.simple_loop_unswitch_memoryssa_threshold, *MSSA,
AA)) {
2770 dbgs() <<
"simple-loop-unswitch: Found partially invariant condition "
2771 << *Info->InstToDuplicate[0] <<
"\n");
2772 PartialIVInfo = *Info;
2773 PartialIVCondBranch = Header->getTerminator();
2777 {Header->getTerminator(), std::move(ValsToDuplicate)});
2780 return !UnswitchCandidates.
empty();
2795 if (!L.contains(IfTrue)) {
2801 if (L.isLoopInvariant(
LHS)) {
2809 RHS = ConstantInt::get(
2821 if (L.isLoopInvariant(
LHS) || !L.isLoopInvariant(
RHS))
2827 if (!L.contains(IfTrue) || L.contains(IfFalse))
2831 if (L.getHeader() == IfTrue)
2847 Opts.simple_loop_unswitch_inject_invariant_condition_hotness_threshold;
2850 assert(Weights.
size() == 2 &&
"Unexpected profile data!");
2852 auto Num = Weights[Idx];
2853 auto Denom = Weights[0] + Weights[1];
2855 if (Denom == 0 || Num > Denom)
2858 if (LikelyTaken > ActualTaken)
2881static NonTrivialUnswitchCandidate
2885 assert(Candidate.hasPendingInjection() &&
"Nothing to inject!");
2886 BasicBlock *Preheader = L.getLoopPreheader();
2887 assert(Preheader &&
"Loop is not in simplified form?");
2889 "Unswitching branch of inner loop!");
2891 auto Pred = Candidate.PendingInjection->Pred;
2892 auto *
LHS = Candidate.PendingInjection->LHS;
2893 auto *
RHS = Candidate.PendingInjection->RHS;
2894 auto *InLoopSucc = Candidate.PendingInjection->InLoopSucc;
2897 auto *OutOfLoopSucc = InLoopSucc == TI->getSuccessor(0) ? TI->getSuccessor(1)
2898 : TI->getSuccessor(0);
2900 assert(L.contains(InLoopSucc) &&
"Not supported yet!");
2901 assert(!L.contains(OutOfLoopSucc) &&
"Not supported yet!");
2902 auto &Ctx = BB->getContext();
2906 if (
LHS->getType() !=
RHS->getType()) {
2907 if (
LHS->getType()->getIntegerBitWidth() <
2908 RHS->getType()->getIntegerBitWidth())
2909 LHS = Builder.CreateZExt(
LHS,
RHS->getType(),
LHS->getName() +
".wide");
2911 RHS = Builder.CreateZExt(
RHS,
LHS->getType(),
RHS->getName() +
".wide");
2915 auto *InjectedCond =
2920 BB->getParent(), InLoopSucc);
2921 Builder.SetInsertPoint(TI);
2923 Builder.CreateCondBr(InjectedCond, InLoopSucc, CheckBlock);
2927 Builder.SetInsertPoint(CheckBlock);
2928 Builder.CreateCondBr(TI->getCondition(), TI->getSuccessor(0),
2929 TI->getSuccessor(1),
2930 TI->getMetadata(LLVMContext::MD_prof));
2931 TI->eraseFromParent();
2934 for (
auto &
I : *InLoopSucc) {
2938 auto *Inc = PN->getIncomingValueForBlock(BB);
2939 PN->addIncoming(Inc, CheckBlock);
2941 OutOfLoopSucc->replacePhiUsesWith(BB, CheckBlock);
2953 L.addBasicBlockToLoop(CheckBlock, LI);
2965 LLVM_DEBUG(
dbgs() <<
"Injected a new loop-invariant branch " << *InvariantBr
2966 <<
" and considering it for unswitching.");
2967 ++NumInvariantConditionsInjected;
2968 return NonTrivialUnswitchCandidate(InvariantBr, { InjectedCond },
2990 if (Compares.
size() < 2)
2998 InjectedInvariant ToInject(NonStrictPred,
LHS,
RHS, InLoopSucc);
2999 NonTrivialUnswitchCandidate Candidate(Prev->Term, { LHS, RHS },
3000 std::nullopt, std::move(ToInject));
3001 UnswitchCandidates.
push_back(std::move(Candidate));
3022 const ScalarOptions &Opts,
3027 if (!Opts.simple_loop_unswitch_inject_invariant_conditions)
3032 auto *Latch = L.getLoopLatch();
3036 assert(L.getLoopPreheader() &&
"Must have a preheader!");
3041 for (
auto *DTN = DT.
getNode(Latch); L.contains(DTN->getBlock());
3042 DTN = DTN->getIDom()) {
3045 BasicBlock *IfTrue =
nullptr, *IfFalse =
nullptr;
3046 auto *BB = DTN->getBlock();
3050 auto *Term = BB->getTerminator();
3054 if (!
LHS->getType()->isIntegerTy())
3066 LHS = Zext->getOperand(0);
3067 CandidatesULT[
LHS].push_back(
Desc);
3071 for (
auto &It : CandidatesULT)
3079 if (!L.isSafeToCloneConditionally(DT))
3094 L.getUniqueExitBlocks(ExitBlocks);
3099 for (
auto *ExitBB : ExitBlocks) {
3100 auto It = ExitBB->getFirstNonPHIIt();
3102 LLVM_DEBUG(
dbgs() <<
"Cannot unswitch because of cleanuppad/catchswitch "
3112 const ScalarOptions &Opts,
3131 L.getHeader()->getParent()->hasMinSize()
3135 for (
auto *BB : L.blocks()) {
3137 for (
auto &
I : *BB) {
3142 assert(Cost >= 0 &&
"Must not have negative costs!");
3144 assert(LoopCost >= 0 &&
"Must not have negative loop costs!");
3145 BBCostMap[BB] = Cost;
3178 if (!Visited.
insert(SuccBB).second)
3186 if (!FullUnswitch) {
3190 if (SuccBB == BI.getSuccessor(1))
3193 if (SuccBB == BI.getSuccessor(0))
3196 SuccBB == BI.getSuccessor(0)) ||
3198 SuccBB == BI.getSuccessor(1)))
3206 if (SuccBB->getUniquePredecessor() ||
3208 return PredBB == &BB || DT.
dominates(SuccBB, PredBB);
3211 assert(Cost <= LoopCost &&
3212 "Non-duplicated cost should never exceed total loop cost!");
3221 int SuccessorsCount =
isGuard(&TI) ? 2 : Visited.
size();
3222 assert(SuccessorsCount > 1 &&
3223 "Cannot unswitch a condition without multiple distinct successors!");
3224 return (LoopCost - Cost) * (SuccessorsCount - 1);
3227 std::optional<NonTrivialUnswitchCandidate> Best;
3228 for (
auto &Candidate : UnswitchCandidates) {
3233 !BI || Candidate.hasPendingInjection() ||
3234 (Invariants.
size() == 1 &&
3236 InstructionCost CandidateCost = ComputeUnswitchedCost(TI, FullUnswitch);
3239 if (Opts.enable_unswitch_cost_multiplier) {
3241 UnswitchCandidates);
3243 (CostMultiplier > 0 && CostMultiplier <= Opts.unswitch_threshold) &&
3244 "cost multiplier needs to be in the range of 1..UnswitchThreshold");
3245 CandidateCost *= CostMultiplier;
3247 <<
" (multiplier: " << CostMultiplier <<
")"
3248 <<
" for unswitch candidate: " << TI <<
"\n");
3251 <<
" for unswitch candidate: " << TI <<
"\n");
3254 if (!Best || CandidateCost < Best->Cost) {
3256 Best->Cost = CandidateCost;
3259 assert(Best &&
"Must be!");
3273 if (!Opts.freeze_loop_unswitch_cond)
3286 Cond, &AC, L.getLoopPreheader()->getTerminator(), &DT);
3301 PartialIVCondBranch, L, LI,
AA, MSSAU);
3304 PartialIVInfo, PartialIVCondBranch,
3305 L, DT, LI,
AA, MSSAU);
3307 if (UnswitchCandidates.
empty())
3311 dbgs() <<
"Considering " << UnswitchCandidates.
size()
3312 <<
" non-trivial loop invariant conditions for unswitching.\n");
3315 Opts, UnswitchCandidates, L, DT, LI, AC,
TTI, PartialIVInfo);
3317 assert(Best.TI &&
"Failed to find loop unswitch candidate");
3318 assert(Best.Cost &&
"Failed to compute cost");
3320 if (*Best.Cost >= Opts.unswitch_threshold) {
3321 LLVM_DEBUG(
dbgs() <<
"Cannot unswitch, lowest cost found: " << *Best.Cost
3326 bool InjectedCondition =
false;
3327 if (Best.hasPendingInjection()) {
3329 InjectedCondition =
true;
3331 assert(!Best.hasPendingInjection() &&
3332 "All injections should have been done by now!");
3334 if (Best.TI != PartialIVCondBranch)
3344 SI->getCondition(), &AC, L.getLoopPreheader()->getTerminator(), &DT);
3354 LLVM_DEBUG(
dbgs() <<
" Unswitching non-trivial (cost = " << Best.Cost
3355 <<
") terminator: " << *Best.TI <<
"\n");
3357 PartialIVInfo, DT, LI, AC, SE, MSSAU,
3358 LoopUpdater, InsertFreeze, InjectedCondition);
3388 const ScalarOptions &Opts = ScalarOptions::Global;
3389 assert(L.isRecursivelyLCSSAForm(DT, LI) &&
3390 "Loops must be in LCSSA form before unswitching.");
3393 if (!L.isLoopSimplifyForm())
3406 const Function *
F = L.getHeader()->getParent();
3419 bool ContinueWithNonTrivial = Opts.enable_nontrivial_unswitch ||
3420 (NonTrivial && !
TTI.hasBranchDivergence(
F));
3421 if (!ContinueWithNonTrivial)
3425 if (
F->hasOptSize())
3451 Function &
F = *L.getHeader()->getParent();
3453 LLVM_DEBUG(
dbgs() <<
"Unswitching loop in " <<
F.getName() <<
": " << L
3456 std::optional<MemorySSAUpdater> MSSAU;
3463 &AR.
SE, MSSAU ? &*MSSAU :
nullptr, U))
3469#ifdef EXPENSIVE_CHECKS
3483 static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *
>(
this)->
printPipeline(
3484 OS, MapClassName2PassName);
3487 OS << (NonTrivial ?
"" :
"no-") <<
"nontrivial;";
3488 OS << (Trivial ?
"" :
"no-") <<
"trivial";
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
This file defines the DenseMap class.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
static Value * getCondition(Instruction *I)
Module.h This file contains the declarations for the Module class.
This defines the Use class.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
This header provides classes for managing per-loop analyses.
Loop::LoopBounds::Direction Direction
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Provides some synthesis utilities to produce sequences of values.
This file implements a set that has insertion order iteration characteristics.
static void buildPartialUnswitchConditionalBranch(const ScalarOptions &Opts, BasicBlock &BB, ArrayRef< Value * > Invariants, bool Direction, BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, const Instruction *I, AssumptionCache *AC, const DominatorTree &DT, const CondBrInst &ComputeProfFrom)
Copy a set of loop invariant values Invariants and insert them at the end of BB and conditionally bra...
static TinyPtrVector< Value * > collectHomogenousInstGraphLoopInvariants(const Loop &L, Instruction &Root, const LoopInfo &LI)
Collect all of the loop invariant input values transitively used by the homogeneous instruction graph...
static void deleteDeadClonedBlocks(Loop &L, ArrayRef< BasicBlock * > ExitBlocks, ArrayRef< std::unique_ptr< ValueToValueMapTy > > VMaps, DominatorTree &DT, MemorySSAUpdater *MSSAU)
void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable)
Helper to visit a dominator subtree, invoking a callable on each node.
static bool rebuildLoopAfterUnswitch(Loop &L, DominatorTree &DT, LoopInfo &LI, SmallVectorImpl< Loop * > &HoistedLoops, ScalarEvolution *SE, LPMUpdater &LoopUpdater)
Rebuild the loop forest after unswitching removes some subset of blocks and edges.
static CondBrInst * turnGuardIntoBranch(const ScalarOptions &Opts, IntrinsicInst *GI, Loop &L, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU)
Turns a llvm.experimental.guard intrinsic into implicit control flow branch, making the following rep...
static void rewritePHINodesForUnswitchedExitBlock(const Loop &L, BasicBlock &UnswitchedBB, BasicBlock &OldExitingBB, BasicBlock &OldPH)
Rewrite the PHI nodes in an unswitched loop exit basic block.
static bool isSafeForNoNTrivialUnswitching(const DominatorTree &DT, Loop &L, LoopInfo &LI)
void postUnswitch(Loop &L, LPMUpdater &U, StringRef LoopName, bool CurrentLoopValid, bool PartiallyInvariant, bool InjectedCondition, ArrayRef< Loop * > NewLoops)
static bool unswitchAllTrivialConditions(const ScalarOptions &Opts, 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.
static bool shouldTryInjectInvariantCondition(const ICmpInst::Predicate Pred, const Value *LHS, const Value *RHS, const BasicBlock *IfTrue, const BasicBlock *IfFalse, const Loop &L)
Returns true, if predicate described by ( Pred, LHS, RHS ) succeeding into blocks ( IfTrue,...
static void buildPartialInvariantUnswitchConditionalBranch(BasicBlock &BB, ArrayRef< Value * > ToDuplicate, bool Direction, BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L, MemorySSAUpdater *MSSAU, const CondBrInst &OriginalBranch)
Copy a set of loop invariant values, and conditionally branch on them.
static Value * skipTrivialSelect(Value *Cond)
static Loop * getTopMostExitingLoop(const BasicBlock *ExitBB, const LoopInfo &LI)
static void replaceLoopInvariantUses(const Loop &L, Value *Invariant, Constant &Replacement)
static InstructionCost computeDomSubtreeCost(DomTreeNode &N, const SmallDenseMap< BasicBlock *, InstructionCost, 4 > &BBCostMap, SmallDenseMap< DomTreeNode *, InstructionCost, 4 > &DTCostMap)
Recursively compute the cost of a dominator subtree based on the per-block cost map provided.
static NonTrivialUnswitchCandidate findBestNonTrivialUnswitchCandidate(const ScalarOptions &Opts, ArrayRef< NonTrivialUnswitchCandidate > UnswitchCandidates, const Loop &L, const DominatorTree &DT, const LoopInfo &LI, AssumptionCache &AC, const TargetTransformInfo &TTI, const IVConditionInfo &PartialIVInfo)
static int calculateUnswitchCostMultiplier(const ScalarOptions &Opts, const Instruction &TI, const Loop &L, const LoopInfo &LI, const DominatorTree &DT, ArrayRef< NonTrivialUnswitchCandidate > UnswitchCandidates)
Cost multiplier is a way to limit potentially exponential behavior of loop-unswitch.
static bool isLoopHeaderPHI(const Loop &L, const Value *V)
Return true if V is a PHI node in the header of L.
static void canonicalizeForInvariantConditionInjection(CmpPredicate &Pred, Value *&LHS, Value *&RHS, BasicBlock *&IfTrue, BasicBlock *&IfFalse, const Loop &L)
Tries to canonicalize condition described by:
static bool areLoopExitPHIsTrivial(const Loop &L, const BasicBlock &ExitingBB, const BasicBlock &ExitBB, bool AllowHeaderPHIs=false)
Check that all the LCSSA PHI nodes in ExitBB have trivial incoming values along the edge from Exiting...
static bool insertCandidatesWithPendingInjections(SmallVectorImpl< NonTrivialUnswitchCandidate > &UnswitchCandidates, Loop &L, ICmpInst::Predicate Pred, ArrayRef< CompareDesc > Compares, const DominatorTree &DT)
Given chain of loop branch conditions looking like: br (Variant < Invariant1) br (Variant < Invariant...
bool shouldTryInjectBasingOnMetadata(const ScalarOptions &Opts, const CondBrInst *BI, const BasicBlock *TakenSucc)
Returns true, if metadata on BI allows us to optimize branching into TakenSucc via injection of invar...
static bool unswitchTrivialBranch(const ScalarOptions &Opts, Loop &L, CondBrInst &BI, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE, MemorySSAUpdater *MSSAU)
Unswitch a trivial branch if the condition is loop invariant.
static NonTrivialUnswitchCandidate injectPendingInvariantConditions(NonTrivialUnswitchCandidate Candidate, Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, MemorySSAUpdater *MSSAU)
Materialize pending invariant condition of the given candidate into IR.
static bool collectUnswitchCandidatesWithInjections(const ScalarOptions &Opts, SmallVectorImpl< NonTrivialUnswitchCandidate > &UnswitchCandidates, IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch, Loop &L, const DominatorTree &DT, const LoopInfo &LI, AAResults &AA, const MemorySSAUpdater *MSSAU)
Collect unswitch candidates by invariant conditions that are not immediately present in the loop.
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.
static void rewritePHINodesForExitAndUnswitchedBlocks(const Loop &L, 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.
static void unswitchNontrivialInvariants(const ScalarOptions &Opts, Loop &L, Instruction &TI, ArrayRef< Value * > Invariants, IVConditionInfo &PartialIVInfo, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, ScalarEvolution *SE, MemorySSAUpdater *MSSAU, LPMUpdater &LoopUpdater, bool InsertFreeze, bool InjectedCondition)
static bool unswitchBestCondition(const ScalarOptions &Opts, Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, AAResults &AA, TargetTransformInfo &TTI, ScalarEvolution *SE, MemorySSAUpdater *MSSAU, LPMUpdater &LoopUpdater)
static CondBrInst * turnSelectIntoBranch(SelectInst *SI, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU, AssumptionCache *AC)
Turns a select instruction into implicit control flow branch, making the following replacement:
static Value * getLoopEntryValue(const Loop &L, Value *V)
Return the value V holds on entry to L.
static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, AAResults &AA, TargetTransformInfo &TTI, bool Trivial, bool NonTrivial, ScalarEvolution *SE, MemorySSAUpdater *MSSAU, LPMUpdater &LoopUpdater)
Unswitch control flow predicated on loop invariant conditions.
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, ScalarEvolution *SE)
Build the cloned blocks for an unswitched copy of the given loop.
static void deleteDeadBlocksFromLoop(Loop &L, SmallVectorImpl< BasicBlock * > &ExitBlocks, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU, ScalarEvolution *SE, LPMUpdater &LoopUpdater)
static bool collectUnswitchCandidates(const ScalarOptions &Opts, SmallVectorImpl< NonTrivialUnswitchCandidate > &UnswitchCandidates, IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch, const Loop &L, const LoopInfo &LI, AAResults &AA, const MemorySSAUpdater *MSSAU)
static bool shouldInsertFreeze(const ScalarOptions &Opts, Loop &L, Instruction &TI, DominatorTree &DT, AssumptionCache &AC)
static Loop * cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, const ValueToValueMapTy &VMap, LoopInfo &LI)
Recursively clone the specified loop and all of its children.
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.
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.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction * getTerminatorOrNull() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static LLVM_ABI bool isStrictPredicate(Predicate predicate)
This is a static version that you can use without an instruction available.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
static DebugLoc getCompilerGenerated()
static DebugLoc getDropped()
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
void insertEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge insertion and update the tree.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
void deleteEdge(NodeT *From, NodeT *To)
Inform the dominator tree about a CFG edge deletion and update the tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class represents a freeze function that returns random concrete value if an operand is either a ...
This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to give precise answers on "may...
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT) const override
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Value * CreateFreeze(Value *V, const Twine &Name="")
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void dropLocation()
Drop the instruction's debug location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
void reserveBlocks(unsigned Size)
interface to do reserve() for Blocks
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
SmallVector< std::pair< LoopT *, BlockT * >, 4 > recompute(const DominatorTreeBase< BlockT, false > &DomTree)
Rebuild the loop forest from the CFG, refilling the existing loop object of every block that still he...
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
SmallVector< LoopT *, 4 > takeChildrenIf(LoopT *Parent, PredicateT Pred)
Detach and return the children of Parent (the top-level loops if Parent is null) that satisfy Pred,...
BlockT * getUniqueLatchExitBlock(const LoopT &L) const
Return the unique exit block for the latch of L, or null if there are multiple different exit blocks ...
void removeBlocksIf(LoopT &L, PredicateT Pred)
Remove every block satisfying Pred from L's block list, preserving the order of the remaining blocks.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
Represents a single loop in the control flow graph.
LLVM_ABI MDNode * createUnlikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards false destination.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
An analysis that produces MemorySSA for a function.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void removeEdge(BasicBlock *From, BasicBlock *To)
Update the MemoryPhi in To following an edge deletion between From and To.
LLVM_ABI 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...
LLVM_ABI 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...
LLVM_ABI void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
LLVM_ABI void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was spliced into From and To.
LLVM_ABI MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point, bool CreationMustSucceed=true)
Create a MemoryAccess in MemorySSA at a specified point in a block.
LLVM_ABI void applyInsertUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT)
Apply CFG insert updates, analogous with the DT edge updates.
LLVM_ABI void applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT, bool UpdateDTFirst=false)
Apply CFG updates, analogous with the DT edge updates.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
LLVM_ABI void updateExitBlocksForClonedLoop(ArrayRef< BasicBlock * > ExitBlocks, const ValueToValueMapTy &VMap, DominatorTree &DT)
Update phi nodes in exit block successors following cloning.
Encapsulates MemorySSA, including all data associated with memory accesses.
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
A Module instance is used to store all the information related to an LLVM module.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
LLVM_ABI 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...
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
iterator begin()
Get an iterator to the beginning of the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
LLVM_ABI void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
LLVM_ABI Instruction::InstListType::iterator eraseFromParent()
Delegate the call to the underlying SwitchInst::eraseFromParent() and mark this object to not touch t...
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
LLVM_ABI CaseWeightOpt getSuccessorWeight(unsigned idx)
std::optional< uint32_t > CaseWeightOpt
LLVM_ABI SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight.
unsigned getSuccessorIndex() const
Returns successor index for current case successor.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
ConstantIntT * getCaseValue() const
Resolves case value for current case.
BasicBlock * getDefaultDest() const
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
void setDefaultDest(BasicBlock *DefaultCase)
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
void push_back(EltTy NewVal)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
LLVM Value Representation.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< use_iterator > uses()
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
LogicalOp_match< LHS, RHS, Instruction::And > m_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R either in the form of L & R or L ?
bool match(Val *V, const Pattern &P)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
LogicalOp_match< LHS, RHS, Instruction::Or > m_LogicalOr(const LHS &L, const RHS &R)
Matches L || R either in the form of L | R or L ?
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
DomTreeNodeBase< BasicBlock > DomTreeNode
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
auto reverse(ContainerTy &&C)
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
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.
void sort(IteratorTy Start, IteratorTy End)
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
bool pred_empty(const BasicBlock *BB)
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI std::optional< IVConditionInfo > hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold, const MemorySSA &MSSA, AAResults &AA)
Check if the loop header has a conditional branch that is not loop-invariant, because it involves loa...
LLVM_ABI bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A special type used by analysis passes to provide an address that identifies that particular analysis...
static LLVM_ABI 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).
Struct to hold information about a partially invariant condition.
SmallVector< Instruction * > InstToDuplicate
Instructions that need to be duplicated and checked for the unswitching condition.
Constant * KnownValue
Constant to indicate for which value the condition is invariant.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
TargetTransformInfo & TTI