80#define DEBUG_TYPE "loop-unroll"
83STATISTIC(NumCompletelyUnrolled,
"Number of loops completely unrolled");
84STATISTIC(NumUnrolled,
"Number of loops unrolled (completely or otherwise)");
85STATISTIC(NumUnrolledNotLatch,
"Number of loops unrolled without a conditional "
86 "latch (completely or otherwise)");
90 cl::desc(
"Allow runtime unrolled loops to be unrolled "
91 "with epilog instead of prolog."));
95 cl::desc(
"Verify domtree after unrolling"),
96#ifdef EXPENSIVE_CHECKS
105 cl::desc(
"Verify loopinfo after unrolling"),
106#ifdef EXPENSIVE_CHECKS
115 cl::desc(
"Allow unrolling to add parallel reduction phis."));
127 const std::vector<BasicBlock *> &Blocks,
133 for (
Use &U :
I.operands()) {
156 assert(OldLoop &&
"Should (at least) be in the loop being unrolled!");
158 Loop *&NewLoop = NewLoops[OldLoop];
162 "Header should be first in RPO");
206 BasicBlock *PreHeader = L->getLoopPreheader();
208 assert(PreHeader && Header);
209 for (
const PHINode &PN : Header->phis()) {
226 unsigned CurrentGeneration;
227 unsigned ChildGeneration;
229 DomTreeNode::const_iterator ChildIter;
230 DomTreeNode::const_iterator EndIter;
231 bool Processed =
false;
235 unsigned cg,
DomTreeNode *
N, DomTreeNode::const_iterator Child,
236 DomTreeNode::const_iterator End)
237 : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg),
238 Node(
N), ChildIter(Child), EndIter(End) {}
244 DomTreeNode::const_iterator
childIter()
const {
return ChildIter; }
252 DomTreeNode::const_iterator
end()
const {
return EndIter; }
271 if (!MSSA->
dominates(LaterDef, EarlierMA))
285 unsigned CurrentGeneration = 0;
286 while (!NodesToProcess.
empty()) {
306 if (!Load || !Load->isSimple()) {
307 if (
I.mayWriteToMemory())
312 const SCEV *PtrSCEV = SE.
getSCEV(Load->getPointerOperand());
317 Load->replaceAllUsesWith(M);
318 Load->eraseFromParent();
326 }
else if (NodeToProcess->
childIter() != NodeToProcess->
end()) {
329 if (!L->contains(Child->
getBlock()))
354 if (SE && SimplifyIVs) {
360 while (!DeadInsts.
empty()) {
367 std::unique_ptr<MemorySSA> MSSA =
nullptr;
382 if (BB->getParent()->getSubprogram())
387 &Inst, {BB->getDataLayout(),
nullptr, DT, AC}))
389 Inst.replaceAllUsesWith(V);
399 const APInt *C1, *C2;
405 Inst.setOperand(0,
X);
406 Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
407 Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
408 InnerOBO->hasNoUnsignedWrap());
409 Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
410 InnerOBO->hasNoSignedWrap() &&
432 for (
auto &BB : L->blocks()) {
433 for (
auto &
I : *BB) {
437 if (CB->isConvergent())
438 return CB->getConvergenceControlToken();
502 bool CompletelyUnroll,
503 std::vector<unsigned> &IterCounts,
504 const std::vector<BasicBlock *> &CondLatches,
505 std::vector<BasicBlock *> &CondLatchNexts) {
547 if (CondLatches.empty())
555 "Expected to have loop probability to fix");
556 if (OriginalLoopProb.
isOne())
560 double FreqDesired = 1 / (1 - OriginalLoopProb.
toDouble());
563 auto SetProb = [&](
unsigned I,
double Prob) {
565 bool FirstTargetIsNext =
B->getSuccessor(0) == CondLatchNexts[
I];
571 auto SetAllProbs = [&](
double Prob) {
572 for (
unsigned I = 0,
E = CondLatches.size();
I <
E; ++
I)
603 auto ComputeProbForLinear = [&]() {
605 double A = IterCounts[1] + (CompletelyUnroll ? 0 : FreqDesired);
606 double B = IterCounts[0] - FreqDesired;
607 assert(
A > 0 &&
"Expected iterations after last conditional latch");
608 double Prob = -
B /
A;
609 Prob = std::max(Prob, 0.);
610 Prob = std::min(Prob, 1.);
616 auto ComputeProbForQuadratic = [&]() {
618 double A = IterCounts[2] + (CompletelyUnroll ? 0 : FreqDesired);
619 double B = IterCounts[1];
620 double C = IterCounts[0] - FreqDesired;
621 assert(
A > 0 &&
"Expected iterations after last conditional latch");
622 double Prob = (-
B + sqrt(
B *
B - 4 *
A *
C)) / (2 *
A);
623 Prob = std::max(Prob, 0.);
624 Prob = std::min(Prob, 1.);
629 if (CondLatches.size() == 1) {
630 SetAllProbs(ComputeProbForLinear());
631 }
else if (CondLatches.size() == 2) {
632 SetAllProbs(ComputeProbForQuadratic());
684 assert(DT &&
"DomTree is required");
686 if (!L->getLoopPreheader()) {
687 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop preheader-insertion failed.\n");
691 if (!L->getLoopLatch()) {
692 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop exit-block-insertion failed.\n");
697 if (!L->isSafeToClone()) {
698 LLVM_DEBUG(
dbgs() <<
" Can't unroll; Loop body cannot be cloned.\n");
702 if (L->getHeader()->hasAddressTaken()) {
705 dbgs() <<
" Won't unroll loop: address of header block is taken.\n");
713 BasicBlock *Preheader = L->getLoopPreheader();
717 L->getExitBlocks(ExitBlocks);
718 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
722 std::optional<unsigned> OriginalTripCount =
728 if (MaxTripCount && ULO.
Count > MaxTripCount)
729 ULO.
Count = MaxTripCount;
733 unsigned TripMultiple;
734 unsigned BreakoutTrip;
741 L->getExitingBlocks(ExitingBlocks);
742 for (
auto *ExitingBlock : ExitingBlocks) {
749 ExitInfo &Info = ExitInfos[ExitingBlock];
752 if (Info.TripCount != 0) {
753 Info.BreakoutTrip = Info.TripCount % ULO.
Count;
754 Info.TripMultiple = 0;
756 Info.BreakoutTrip = Info.TripMultiple =
759 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
760 Info.ExitingBlocks.push_back(ExitingBlock);
761 LLVM_DEBUG(
dbgs() <<
" Exiting block %" << ExitingBlock->getName()
762 <<
": TripCount=" << Info.TripCount
763 <<
", TripMultiple=" << Info.TripMultiple
764 <<
", BreakoutTrip=" << Info.BreakoutTrip <<
"\n");
770 const bool CompletelyUnroll = ULO.
Count == MaxTripCount;
772 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
776 if (CompletelyUnroll)
785 bool NeedToFixLCSSA =
786 PreserveLCSSA && CompletelyUnroll &&
800 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
804 dbgs() <<
"Can't unroll; a conditional latch must exit the loop");
809 "Can't runtime unroll if loop contains a convergent operation.");
811 bool EpilogProfitability =
820 RemainderLoop, OriginalTripCount, OriginalLoopProb)) {
825 "generated when assuming runtime trip count\n");
832 if (CompletelyUnroll) {
833 LLVM_DEBUG(
dbgs() <<
"COMPLETELY UNROLLING loop %" << Header->getName()
834 <<
" with trip count " << ULO.
Count <<
"!\n");
839 <<
"completely unrolled loop with "
840 << NV(
"UnrollCount", ULO.
Count) <<
" iterations";
843 LLVM_DEBUG(
dbgs() <<
"UNROLLING loop %" << Header->getName() <<
" by "
853 Diag <<
"unrolled loop by a factor of " << NV(
"UnrollCount", ULO.
Count);
855 Diag <<
" with run-time trip count";
878 ++NumUnrolledNotLatch;
883 std::vector<PHINode*> OrigPHINode;
894 bool CanAddAdditionalAccumulators =
898 !CompletelyUnroll && L->getNumBlocks() == 1 &&
900 (ExitInfos.
contains(Header) && ((ExitInfos[Header].TripCount != 0 &&
901 ExitInfos[Header].BreakoutTrip == 0))));
908 if (CanAddAdditionalAccumulators && ULO.
Count <= 4) {
909 for (
PHINode &Phi : Header->phis()) {
923 std::vector<BasicBlock *> Headers;
924 std::vector<BasicBlock *> Latches;
925 Headers.push_back(Header);
926 Latches.push_back(LatchBlock);
938 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
949 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
953 if (!
I.isDebugOrPseudoInst())
955 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.
Count);
957 I.setDebugLoc(*NewDIL);
960 <<
"Failed to create new discriminator: "
961 << DIL->getFilename() <<
" Line: " << DIL->getLine());
972 auto BlockInsertPt = std::next(LatchBlock->
getIterator());
974 for (
unsigned It = 1; It != ULO.
Count; ++It) {
982 Header->getParent()->insert(BlockInsertPt, New);
985 "Header should not be in a sub-loop");
989 LoopsToSimplify.
insert(NewLoops[OldLoop]);
994 for (
PHINode *OrigPHI : OrigPHINode) {
1002 if (PartialReductions.
empty())
1010 L->getLoopPreheader(),
1023 if (It > 1 && L->contains(InValI))
1024 InVal = LastValueMap[InValI];
1025 VMap[OrigPHI] = InVal;
1048 LastValueMap[*BB] = New;
1051 LastValueMap[VI->first] = VI->second;
1055 if (L->contains(Succ))
1058 Value *Incoming =
PHI.getIncomingValueForBlock(*BB);
1060 if (It != LastValueMap.
end())
1062 PHI.addIncoming(Incoming, New);
1069 Headers.push_back(New);
1070 if (*BB == LatchBlock)
1071 Latches.push_back(New);
1075 auto ExitInfoIt = ExitInfos.
find(*BB);
1076 if (ExitInfoIt != ExitInfos.
end())
1077 ExitInfoIt->second.ExitingBlocks.push_back(New);
1080 UnrolledLoopBlocks.push_back(New);
1089 auto BBDomNode = DT->
getNode(*BB);
1090 auto BBIDom = BBDomNode->
getIDom();
1091 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
1109 std::string ext = (
Twine(
"It") +
Twine(It)).str();
1111 Header->getContext(), ext);
1116 for (
PHINode *PN : OrigPHINode) {
1117 if (CompletelyUnroll) {
1118 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
1119 PN->eraseFromParent();
1120 }
else if (ULO.
Count > 1) {
1124 Value *InVal = PN->removeIncomingValue(LatchBlock,
false);
1128 if (L->contains(InValI))
1129 InVal = LastValueMap[InVal];
1131 assert(Latches.back() == LastValueMap[LatchBlock] &&
"bad last latch");
1132 PN->addIncoming(InVal, Latches.back());
1138 for (
unsigned i = 0, e = Latches.size(); i != e; ++i) {
1139 unsigned j = (i + 1) % e;
1140 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
1145 for (
unsigned I = 0, E = Latches.size() - (CompletelyUnroll ? 0 : 1);
I < E;
1147 Latches[
I]->getTerminator()->setMetadata(LLVMContext::MD_loop,
nullptr);
1153 if (ULO.
Count > 1) {
1154 for (
auto *BB : OriginalLoopBlocks) {
1155 auto *BBDomNode = DT->
getNode(BB);
1157 for (
auto *ChildDomNode : BBDomNode->children()) {
1158 auto *ChildBB = ChildDomNode->getBlock();
1159 if (!L->contains(ChildBB))
1167 for (
auto *ChildBB : ChildrenToUpdate)
1173 DT->
verify(DominatorTree::VerificationLevel::Fast));
1176 auto SetDest = [&](
BasicBlock *Src,
bool WillExit,
bool ExitOnTrue) {
1178 const unsigned Idx = ExitOnTrue ^ WillExit;
1180 BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
1187 BI->setDebugLoc(Term->getDebugLoc());
1188 Term->eraseFromParent();
1193 auto WillExit = [&](
const ExitInfo &Info,
unsigned i,
unsigned j,
1194 bool IsLatch) -> std::optional<bool> {
1195 if (CompletelyUnroll) {
1196 if (PreserveOnlyFirst) {
1198 return std::nullopt;
1204 if (Info.TripCount && j != Info.TripCount)
1206 return std::nullopt;
1212 if (IsLatch && j != 0)
1214 return std::nullopt;
1217 if (j != Info.BreakoutTrip &&
1218 (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
1223 return std::nullopt;
1229 bool ProbUpdateRequired =
false;
1230 for (
auto &Pair : ExitInfos) {
1231 ExitInfo &Info = Pair.second;
1232 for (
unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
1234 unsigned j = (i + 1) % e;
1235 bool IsLatch = Pair.first == LatchBlock;
1236 std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
1237 if (!KnownWillExit) {
1238 if (!Info.FirstExitingBlock)
1239 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1248 if (*KnownWillExit && !IsLatch) {
1249 if (!Info.FirstExitingBlock)
1250 Info.FirstExitingBlock = Info.ExitingBlocks[i];
1255 if (!OriginalLoopProb.
isUnknown() && IsLatch) {
1259 ProbUpdateRequired |= OriginalLoopProb != ActualProb;
1262 SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
1268 if (ExitingBlocks.
size() == 1 && ExitInfos.
size() == 1) {
1276 auto &[OriginalExit, Info] = *ExitInfos.
begin();
1277 if (!Info.FirstExitingBlock)
1278 Info.FirstExitingBlock = Info.ExitingBlocks.back();
1280 if (L->contains(
C->getBlock()))
1282 C->setIDom(DT->
getNode(Info.FirstExitingBlock));
1289 if (!LatchIsExiting && CompletelyUnroll) {
1310 "Expected one latch block per unrolled iteration");
1311 std::vector<unsigned> IterCounts(1, 0);
1312 std::vector<BasicBlock *> CondLatches;
1313 std::vector<BasicBlock *> CondLatchNexts;
1314 IterCounts.reserve(Latches.size() + 1);
1315 CondLatches.reserve(Latches.size());
1316 CondLatchNexts.reserve(Latches.size());
1320 ++IterCounts.back();
1322 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
1323 "Need a branch as terminator, except when fully unrolling with "
1324 "unconditional latch");
1331 DTUToUse ?
nullptr : DT)) {
1337 IterCounts.push_back(0);
1338 CondLatches.push_back(Latch);
1339 CondLatchNexts.push_back(Headers[(
I + 1) % Latches.size()]);
1344 if (ProbUpdateRequired) {
1346 CondLatches, CondLatchNexts);
1351 if (!PartialReductions.
empty()) {
1354 "Can only introduce parallel reduction phis with single exit block");
1356 "currently only a single reduction is supported");
1357 Value *FinalRdxValue = PartialReductions.
back();
1358 Value *RdxResult =
nullptr;
1360 if (Phi.getIncomingValueForBlock(L->getLoopLatch()) != FinalRdxValue)
1363 RdxResult = PartialReductions.
front();
1365 Builder.setFastMathFlags(
Reductions.begin()->second.getFastMathFlags());
1368 RdxResult = Builder.CreateBinOp(
1370 RdxPart, RdxResult,
"bin.rdx");
1372 NeedToFixLCSSA =
true;
1374 RdxPart->dropPoisonGeneratingFlags();
1377 Phi.replaceAllUsesWith(RdxResult);
1386 DT->
verify(DominatorTree::VerificationLevel::Fast));
1388 Loop *OuterL = L->getParentLoop();
1389 std::vector<BasicBlock *> Blocks;
1391 if (CompletelyUnroll) {
1392 Blocks = L->getBlocks();
1401 L, !CompletelyUnroll && ULO.
Count > 1, LI, SE, DT, AC,
TTI,
1404 NumCompletelyUnrolled += CompletelyUnroll;
1407 if (!CompletelyUnroll) {
1436 assert((CondLatches.size() == 1 &&
1437 (ProbUpdateRequired || OriginalLoopProb.
isOne())) &&
1438 "Expected ULO.Runtime to give unrolled loop 1 conditional latch, "
1439 "the backedge, requiring a probability update unless infinite");
1444 if (OriginalTripCount) {
1445 unsigned NewTripCount = *OriginalTripCount / ULO.
Count;
1464 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1474 if (NeedToFixLCSSA) {
1479 Loop *FixLCSSALoop = OuterL;
1480 if (!FixLCSSALoop->
contains(LatchLoop))
1485 }
else if (PreserveLCSSA) {
1487 "Loops should be in LCSSA form after loop-unroll.");
1492 simplifyLoop(OuterL, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1495 for (
Loop *SubLoop : LoopsToSimplify)
1496 simplifyLoop(SubLoop, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1530 if (
MDNode *LoopID = L->getLoopID())
1535std::optional<RecurrenceDescriptor>
1541 nullptr,
nullptr, SE))
1542 return std::nullopt;
1544 return std::nullopt;
1552 return std::nullopt;
1555 return std::nullopt;
1558 return std::nullopt;
1565 return std::nullopt;
1572 return std::nullopt;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Optimize for code generation
#define LLVM_ATTRIBUTE_USED
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
static bool needToInsertPhisForLCSSA(Loop *L, const std::vector< BasicBlock * > &Blocks, LoopInfo *LI)
Check if unrolling created a situation where we need to insert phi nodes to preserve LCSSA form.
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale.
static void fixProbContradiction(UnrollLoopOptions ULO, BranchProbability OriginalLoopProb, bool CompletelyUnroll, std::vector< unsigned > &IterCounts, const std::vector< BasicBlock * > &CondLatches, std::vector< BasicBlock * > &CondLatchNexts)
void loadCSE(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
Value * getMatchingValue(LoadValue LV, LoadInst *LI, unsigned CurrentGeneration, BatchAAResults &BAA, function_ref< MemorySSA *()> GetMSSA)
static cl::opt< bool > UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolled loops to be unrolled " "with epilog instead of prolog."))
static cl::opt< bool > UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden, cl::desc("Verify loopinfo after unrolling"), cl::init(false))
static cl::opt< bool > UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, cl::desc("Verify domtree after unrolling"), cl::init(false))
static LLVM_ATTRIBUTE_USED bool canHaveUnrollRemainder(const Loop *L)
static cl::opt< bool > UnrollAddParallelReductions("unroll-add-parallel-reductions", cl::init(false), cl::Hidden, cl::desc("Allow unrolling to add parallel reduction phis."))
This file implements a map that provides insertion order iteration.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
This file implements a set that has insertion order iteration characteristics.
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)
void childGeneration(unsigned generation)
unsigned currentGeneration() const
unsigned childGeneration() const
StackNode(ScopedHashTable< const SCEV *, LoadValue > &AvailableLoads, unsigned cg, DomTreeNode *N, DomTreeNode::const_iterator Child, DomTreeNode::const_iterator End)
DomTreeNode::const_iterator end() const
DomTreeNode * nextChild()
DomTreeNode::const_iterator childIter() const
Class for arbitrary precision integers.
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
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.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
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.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
LLVM_ABI BranchProbability pow(unsigned N) const
Compute pow(Probability, N).
static BranchProbability getOne()
static BranchProbability getZero()
Conditional Branch instruction.
A parsed version of the target data layout string in and methods for querying it.
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...
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
static constexpr UpdateKind Delete
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 Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
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.
An instruction for reading from memory.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Represents a single loop in the control flow graph.
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
Tracking metadata reference owned by Metadata.
LLVM_ABI StringRef getString() const
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
bool contains(const KeyT &Key) const
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Encapsulates MemorySSA, including all data associated with memory accesses.
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
FastMathFlags getFastMathFlags() const
bool hasExactFPMath() const
Returns true if the recurrence has floating-point math that requires precise (ordered) operations.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static LLVM_ABI bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, DemandedBits *DB=nullptr, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr, ScalarEvolution *SE=nullptr)
Returns true if Phi is a reduction in TheLoop.
bool hasUsesOutsideReductionChain() const
Returns true if the reduction PHI has any uses outside the reduction chain.
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
RecurKind getRecurrenceKind() const
StoreInst * IntermediateStore
Reductions may store temporary or final result to an invariant address.
static bool isFindRecurrenceKind(RecurKind Kind)
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
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...
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI void forgetAllLoops()
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
ScopedHashTableScope< K, V, KInfo, AllocatorTy > ScopeTy
ScopeTy - A type alias for easy access to the name of the scope for this hash table.
void insert_range(Range &&R)
bool insert(const value_type &X)
Insert a new element into the SetVector.
A SetVector that performs no allocations if smaller than a certain size.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
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.
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
iterator find(const KeyT &Val)
ValueMapIteratorImpl< MapT, const Value *, false > iterator
bool erase(const KeyT &Val)
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Abstract Attribute helper functions.
@ C
The default llvm calling convention, compatible with C.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
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 std::optional< RecurrenceDescriptor > canParallelizeReductionWhenUnrolling(PHINode &Phi, Loop *L, ScalarEvolution *SE)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
SmallDenseMap< const Loop *, Loop *, 4 > NewLoopsMap
LLVM_ABI cl::opt< bool > EnableFSDiscriminator
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
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...
LLVM_ABI void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, ArrayRef< BasicBlock * > Blocks, AAResults *AA=nullptr)
Perform some cleanup and simplifications on loops after unrolling.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
DomTreeNodeBase< BasicBlock > DomTreeNode
auto dyn_cast_or_null(const Y &Val)
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
void setBranchProbability(CondBrInst *B, BranchProbability P, bool ForFirstTarget)
Set branch weight metadata for B to indicate that P and 1 - P are the probabilities of control flowin...
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, const TargetTransformInfo *TTI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
BranchProbability getLoopProbability(Loop *L)
Based on branch weight metadata, return either:
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
@ PartiallyUnrolled
The loop was partially unrolled – we still have a loop, but with a smaller trip count.
@ Unmodified
The loop was not modified.
@ FullyUnrolled
The loop was fully unrolled into straight-line code.
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 unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
bool setLoopProbability(Loop *L, BranchProbability P)
Set branch weight metadata for the latch of L to indicate that, at the end of any iteration,...
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
RecurKind
These are the kinds of recurrences that we support.
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
LLVM_ABI MDNode * getUnrollMetadataForLoop(const Loop *L, StringRef Name)
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, std::optional< unsigned > EstimatedLoopInvocationWeight=std::nullopt)
Set llvm.loop.estimated_trip_count with the value EstimatedTripCount in the loop metadata of L.
LLVM_ABI const Loop * addClonedBlockToLoopInfo(BasicBlock *OriginalBB, BasicBlock *ClonedBB, LoopInfo *LI, NewLoopsMap &NewLoops)
Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary and adds a mapping from the o...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, bool PreserveLCSSA, unsigned SCEVExpansionBudget, bool RuntimeUnrollMultiExit, Loop **ResultLoop=nullptr, std::optional< unsigned > OriginalTripCount=std::nullopt, BranchProbability OriginalLoopProb=BranchProbability::getUnknown())
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
LLVM_ABI MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
LLVM_ABI LoopUnrollResult UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const llvm::TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop=nullptr, AAResults *AA=nullptr)
Unroll the given loop by Count.
LoadValue(Instruction *Inst, unsigned Generation)
const Instruction * Heart
bool RuntimeUnrollMultiExit
bool AllowExpensiveTripCount
bool AddAdditionalAccumulators
unsigned SCEVExpansionBudget
std::conditional_t< IsConst, const ValueT &, ValueT & > second