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
124 const std::vector<BasicBlock *> &
Blocks,
130 for (
Use &U :
I.operands()) {
131 if (
const auto *Def = dyn_cast<Instruction>(U)) {
153 assert(OldLoop &&
"Should (at least) be in the loop being unrolled!");
155 Loop *&NewLoop = NewLoops[OldLoop];
159 "Header should be first in RPO");
203 BasicBlock *PreHeader = L->getLoopPreheader();
205 assert(PreHeader && Header);
206 for (
const PHINode &PN : Header->phis()) {
207 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
223 unsigned CurrentGeneration;
224 unsigned ChildGeneration;
228 bool Processed =
false;
234 : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg),
235 Node(
N), ChildIter(Child), EndIter(
End) {}
268 if (!MSSA->
dominates(LaterDef, EarlierMA))
282 unsigned CurrentGeneration = 0;
283 while (!NodesToProcess.
empty()) {
302 auto *Load = dyn_cast<LoadInst>(&
I);
303 if (!Load || !Load->isSimple()) {
304 if (
I.mayWriteToMemory())
309 const SCEV *PtrSCEV = SE.
getSCEV(Load->getPointerOperand());
314 Load->replaceAllUsesWith(M);
315 Load->eraseFromParent();
323 }
else if (NodeToProcess->
childIter() != NodeToProcess->
end()) {
326 if (!L->contains(Child->
getBlock()))
350 if (SE && SimplifyIVs) {
356 while (!DeadInsts.
empty()) {
358 if (
Instruction *Inst = dyn_cast_or_null<Instruction>(V))
363 std::unique_ptr<MemorySSA> MSSA =
nullptr;
379 if (BB->getParent()->getSubprogram())
385 Inst.replaceAllUsesWith(V);
395 const APInt *C1, *C2;
397 auto *InnerI = dyn_cast<Instruction>(Inst.getOperand(0));
398 auto *InnerOBO = cast<OverflowingBinaryOperator>(Inst.getOperand(0));
401 Inst.setOperand(0,
X);
402 Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
403 Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
404 InnerOBO->hasNoUnsignedWrap());
405 Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
406 InnerOBO->hasNoSignedWrap() &&
428 for (
auto &BB : L->blocks()) {
429 for (
auto &
I : *BB) {
430 if (isa<ConvergenceControlInst>(
I))
432 if (
auto *CB = dyn_cast<CallBase>(&
I))
433 if (CB->isConvergent())
434 return CB->getConvergenceControlToken();
462 assert(DT &&
"DomTree is required");
464 if (!L->getLoopPreheader()) {
465 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop preheader-insertion failed.\n");
466 return LoopUnrollResult::Unmodified;
469 if (!L->getLoopLatch()) {
470 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop exit-block-insertion failed.\n");
471 return LoopUnrollResult::Unmodified;
475 if (!L->isSafeToClone()) {
476 LLVM_DEBUG(
dbgs() <<
" Can't unroll; Loop body cannot be cloned.\n");
477 return LoopUnrollResult::Unmodified;
480 if (L->getHeader()->hasAddressTaken()) {
483 dbgs() <<
" Won't unroll loop: address of header block is taken.\n");
484 return LoopUnrollResult::Unmodified;
491 BasicBlock *Preheader = L->getLoopPreheader();
495 L->getExitBlocks(ExitBlocks);
496 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
500 unsigned EstimatedLoopInvocationWeight = 0;
501 std::optional<unsigned> OriginalTripCount =
506 if (MaxTripCount && ULO.
Count > MaxTripCount)
507 ULO.
Count = MaxTripCount;
511 unsigned TripMultiple;
512 unsigned BreakoutTrip;
519 L->getExitingBlocks(ExitingBlocks);
520 for (
auto *ExitingBlock : ExitingBlocks) {
523 auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
527 ExitInfo &
Info = ExitInfos[ExitingBlock];
530 if (
Info.TripCount != 0) {
532 Info.TripMultiple = 0;
534 Info.BreakoutTrip =
Info.TripMultiple =
537 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
538 Info.ExitingBlocks.push_back(ExitingBlock);
539 LLVM_DEBUG(
dbgs() <<
" Exiting block %" << ExitingBlock->getName()
540 <<
": TripCount=" <<
Info.TripCount
541 <<
", TripMultiple=" <<
Info.TripMultiple
542 <<
", BreakoutTrip=" <<
Info.BreakoutTrip <<
"\n");
548 const bool CompletelyUnroll = ULO.
Count == MaxTripCount;
550 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
554 if (CompletelyUnroll)
563 bool NeedToFixLCSSA =
564 PreserveLCSSA && CompletelyUnroll &&
578 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
579 if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
581 dbgs() <<
"Can't unroll; a conditional latch must exit the loop");
582 return LoopUnrollResult::Unmodified;
586 "Can't runtime unroll if loop contains a convergent operation.");
588 bool EpilogProfitability =
601 "generated when assuming runtime trip count\n");
602 return LoopUnrollResult::Unmodified;
608 if (CompletelyUnroll) {
609 LLVM_DEBUG(
dbgs() <<
"COMPLETELY UNROLLING loop %" << Header->getName()
610 <<
" with trip count " << ULO.
Count <<
"!\n");
615 <<
"completely unrolled loop with "
616 << NV(
"UnrollCount", ULO.
Count) <<
" iterations";
619 LLVM_DEBUG(
dbgs() <<
"UNROLLING loop %" << Header->getName() <<
" by "
629 Diag <<
"unrolled loop by a factor of " << NV(
"UnrollCount", ULO.
Count);
631 Diag <<
" with run-time trip count";
654 ++NumUnrolledNotLatch;
659 std::vector<PHINode*> OrigPHINode;
661 OrigPHINode.push_back(cast<PHINode>(
I));
664 std::vector<BasicBlock *> Headers;
665 std::vector<BasicBlock *> Latches;
666 Headers.push_back(Header);
667 Latches.push_back(LatchBlock);
679 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
686 for (
Loop *SubLoop : *L)
687 LoopsToSimplify.
insert(SubLoop);
691 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
695 if (!
I.isDebugOrPseudoInst())
697 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.
Count);
699 I.setDebugLoc(*NewDIL);
702 <<
"Failed to create new discriminator: "
703 << DIL->getFilename() <<
" Line: " << DIL->getLine());
714 auto BlockInsertPt = std::next(LatchBlock->
getIterator());
715 for (
unsigned It = 1; It != ULO.
Count; ++It) {
723 Header->getParent()->insert(BlockInsertPt, New);
726 "Header should not be in a sub-loop");
730 LoopsToSimplify.
insert(NewLoops[OldLoop]);
735 for (
PHINode *OrigPHI : OrigPHINode) {
736 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
738 if (
Instruction *InValI = dyn_cast<Instruction>(InVal))
739 if (It > 1 && L->contains(InValI))
740 InVal = LastValueMap[InValI];
741 VMap[OrigPHI] = InVal;
749 Instruction *heartCopy = cast<Instruction>(it->second);
756 LastValueMap[*BB] = New;
759 LastValueMap[VI->first] = VI->second;
763 if (L->contains(Succ))
768 if (It != LastValueMap.
end())
777 Headers.push_back(New);
778 if (*BB == LatchBlock)
779 Latches.push_back(New);
783 auto ExitInfoIt = ExitInfos.
find(*BB);
784 if (ExitInfoIt != ExitInfos.
end())
785 ExitInfoIt->second.ExitingBlocks.push_back(New);
788 UnrolledLoopBlocks.push_back(New);
797 auto BBDomNode = DT->
getNode(*BB);
798 auto BBIDom = BBDomNode->
getIDom();
799 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
801 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
809 if (
auto *
II = dyn_cast<AssumeInst>(&
I))
816 std::string ext = (
Twine(
"It") +
Twine(It)).str();
818 Header->getContext(), ext);
823 for (
PHINode *PN : OrigPHINode) {
824 if (CompletelyUnroll) {
825 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
826 PN->eraseFromParent();
827 }
else if (ULO.
Count > 1) {
828 Value *InVal = PN->removeIncomingValue(LatchBlock,
false);
831 if (
Instruction *InValI = dyn_cast<Instruction>(InVal)) {
832 if (L->contains(InValI))
833 InVal = LastValueMap[InVal];
835 assert(Latches.back() == LastValueMap[LatchBlock] &&
"bad last latch");
836 PN->addIncoming(InVal, Latches.back());
842 for (
unsigned i = 0, e = Latches.size(); i != e; ++i) {
843 unsigned j = (i + 1) % e;
844 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
852 for (
auto *BB : OriginalLoopBlocks) {
853 auto *BBDomNode = DT->
getNode(BB);
855 for (
auto *ChildDomNode : BBDomNode->children()) {
856 auto *ChildBB = ChildDomNode->getBlock();
857 if (!L->contains(ChildBB))
865 for (
auto *ChildBB : ChildrenToUpdate)
871 DT->
verify(DominatorTree::VerificationLevel::Fast));
874 auto SetDest = [&](
BasicBlock *Src,
bool WillExit,
bool ExitOnTrue) {
875 auto *Term = cast<BranchInst>(Src->getTerminator());
876 const unsigned Idx = ExitOnTrue ^ WillExit;
885 BI->setDebugLoc(Term->getDebugLoc());
886 Term->eraseFromParent();
888 DTUpdates.
emplace_back(DominatorTree::Delete, Src, DeadSucc);
891 auto WillExit = [&](
const ExitInfo &
Info,
unsigned i,
unsigned j,
892 bool IsLatch) -> std::optional<bool> {
893 if (CompletelyUnroll) {
894 if (PreserveOnlyFirst) {
902 if (
Info.TripCount && j !=
Info.TripCount)
910 if (IsLatch && j != 0)
915 if (j !=
Info.BreakoutTrip &&
916 (
Info.TripMultiple == 0 || j %
Info.TripMultiple != 0)) {
926 for (
auto &Pair : ExitInfos) {
927 ExitInfo &
Info = Pair.second;
928 for (
unsigned i = 0, e =
Info.ExitingBlocks.size(); i != e; ++i) {
930 unsigned j = (i + 1) % e;
931 bool IsLatch = Pair.first == LatchBlock;
932 std::optional<bool> KnownWillExit = WillExit(
Info, i, j, IsLatch);
933 if (!KnownWillExit) {
934 if (!
Info.FirstExitingBlock)
935 Info.FirstExitingBlock =
Info.ExitingBlocks[i];
944 if (*KnownWillExit && !IsLatch) {
945 if (!
Info.FirstExitingBlock)
946 Info.FirstExitingBlock =
Info.ExitingBlocks[i];
950 SetDest(
Info.ExitingBlocks[i], *KnownWillExit,
Info.ExitOnTrue);
956 if (ExitingBlocks.
size() == 1 && ExitInfos.
size() == 1) {
964 auto &[OriginalExit,
Info] = *ExitInfos.
begin();
965 if (!
Info.FirstExitingBlock)
966 Info.FirstExitingBlock =
Info.ExitingBlocks.back();
968 if (L->contains(
C->getBlock()))
977 if (!LatchIsExiting && CompletelyUnroll) {
987 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
989 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
990 "Need a branch as terminator, except when fully unrolling with "
991 "unconditional latch");
992 if (Term && Term->isUnconditional()) {
998 DTUToUse ?
nullptr : DT)) {
1000 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
1011 DT->
verify(DominatorTree::VerificationLevel::Fast));
1018 NumCompletelyUnrolled += CompletelyUnroll;
1021 Loop *OuterL = L->getParentLoop();
1023 if (CompletelyUnroll) {
1027 }
else if (OriginalTripCount) {
1031 EstimatedLoopInvocationWeight);
1046 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1056 if (NeedToFixLCSSA) {
1061 Loop *FixLCSSALoop = OuterL;
1062 if (!FixLCSSALoop->
contains(LatchLoop))
1067 }
else if (PreserveLCSSA) {
1069 "Loops should be in LCSSA form after loop-unroll.");
1074 simplifyLoop(OuterL, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1077 for (
Loop *SubLoop : LoopsToSimplify)
1078 simplifyLoop(SubLoop, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1081 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
1082 : LoopUnrollResult::PartiallyUnrolled;
1094 MDNode *MD = dyn_cast<MDNode>(MDO);
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Analysis containing CSE Info
Optimize for code generation
#define LLVM_ATTRIBUTE_USED
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
DenseMap< Block *, BlockRelaxAux > Blocks
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
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.
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)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
A cache of @llvm.assume calls within a function.
void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
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 if the block is well formed or null if the block is not well forme...
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...
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
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 find(const_arg_type_t< KeyT > Val)
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
typename SmallVector< DomTreeNodeBase *, 4 >::const_iterator const_iterator
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.
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.
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.
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.
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.
StringRef getString() 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.
bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This class represents an analyzed expression in the program.
The main scalar evolution driver.
unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
void forgetTopmostLoop(const Loop *L)
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
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...
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.
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
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...
A Use represents the edge between a Value definition and its users.
iterator find(const KeyT &Val)
bool erase(const KeyT &Val)
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()
@ C
The default llvm calling convention, compatible with C.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
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.
bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, const TargetTransformInfo *TTI, AAResults *AA=nullptr)
Perform some cleanup and simplifications on loops after unrolling.
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.
auto successors(const MachineBasicBlock *BB)
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...
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, Loop **ResultLoop=nullptr)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
cl::opt< bool > EnableFSDiscriminator
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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.
CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
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...
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
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...
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
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.
bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, unsigned EstimatedLoopInvocationWeight)
Set a loop's branch weight metadata to reflect that loop has EstimatedTripCount iterations and Estima...
void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
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...
void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
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...
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)
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
const Instruction * Heart
bool AllowExpensiveTripCount
unsigned SCEVExpansionBudget