82#define DEBUG_TYPE "loop-unroll"
85STATISTIC(NumCompletelyUnrolled,
"Number of loops completely unrolled");
86STATISTIC(NumUnrolled,
"Number of loops unrolled (completely or otherwise)");
87STATISTIC(NumUnrolledNotLatch,
"Number of loops unrolled without a conditional "
88 "latch (completely or otherwise)");
92 cl::desc(
"Allow runtime unrolled loops to be unrolled "
93 "with epilog instead of prolog."));
97 cl::desc(
"Verify domtree after unrolling"),
98#ifdef EXPENSIVE_CHECKS
107 cl::desc(
"Verify loopinfo after unrolling"),
108#ifdef EXPENSIVE_CHECKS
126 const std::vector<BasicBlock *> &
Blocks,
132 for (
Use &U :
I.operands()) {
133 if (
const auto *Def = dyn_cast<Instruction>(U)) {
155 assert(OldLoop &&
"Should (at least) be in the loop being unrolled!");
157 Loop *&NewLoop = NewLoops[OldLoop];
161 "Header should be first in RPO");
205 BasicBlock *PreHeader = L->getLoopPreheader();
207 assert(PreHeader && Header);
208 for (
const PHINode &PN : Header->phis()) {
209 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
225 unsigned CurrentGeneration;
226 unsigned ChildGeneration;
230 bool Processed =
false;
236 : LoadScope(AvailableLoads), CurrentGeneration(cg), ChildGeneration(cg),
237 Node(
N), ChildIter(Child), EndIter(
End) {}
270 if (!MSSA->
dominates(LaterDef, EarlierMA))
284 unsigned CurrentGeneration = 0;
285 while (!NodesToProcess.
empty()) {
304 auto *Load = dyn_cast<LoadInst>(&
I);
305 if (!Load || !Load->isSimple()) {
306 if (
I.mayWriteToMemory())
311 const SCEV *PtrSCEV = SE.
getSCEV(Load->getPointerOperand());
316 Load->replaceAllUsesWith(M);
317 Load->eraseFromParent();
325 }
else if (NodeToProcess->
childIter() != NodeToProcess->
end()) {
328 if (!L->contains(Child->
getBlock()))
352 if (SE && SimplifyIVs) {
358 while (!DeadInsts.
empty()) {
360 if (
Instruction *Inst = dyn_cast_or_null<Instruction>(V))
365 std::unique_ptr<MemorySSA> MSSA =
nullptr;
381 if (BB->getParent()->getSubprogram())
387 Inst.replaceAllUsesWith(V);
397 const APInt *C1, *C2;
399 auto *InnerI = dyn_cast<Instruction>(Inst.getOperand(0));
400 auto *InnerOBO = cast<OverflowingBinaryOperator>(Inst.getOperand(0));
403 Inst.setOperand(0,
X);
404 Inst.setOperand(1, ConstantInt::get(Inst.getType(), NewC));
405 Inst.setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap() &&
406 InnerOBO->hasNoUnsignedWrap());
407 Inst.setHasNoSignedWrap(Inst.hasNoSignedWrap() &&
408 InnerOBO->hasNoSignedWrap() &&
430 for (
auto &BB : L->blocks()) {
431 for (
auto &
I : *BB) {
432 if (isa<ConvergenceControlInst>(
I))
434 if (
auto *CB = dyn_cast<CallBase>(&
I))
435 if (CB->isConvergent())
436 return CB->getConvergenceControlToken();
464 assert(DT &&
"DomTree is required");
466 if (!L->getLoopPreheader()) {
467 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop preheader-insertion failed.\n");
468 return LoopUnrollResult::Unmodified;
471 if (!L->getLoopLatch()) {
472 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop exit-block-insertion failed.\n");
473 return LoopUnrollResult::Unmodified;
477 if (!L->isSafeToClone()) {
478 LLVM_DEBUG(
dbgs() <<
" Can't unroll; Loop body cannot be cloned.\n");
479 return LoopUnrollResult::Unmodified;
482 if (L->getHeader()->hasAddressTaken()) {
485 dbgs() <<
" Won't unroll loop: address of header block is taken.\n");
486 return LoopUnrollResult::Unmodified;
493 BasicBlock *Preheader = L->getLoopPreheader();
497 L->getExitBlocks(ExitBlocks);
498 std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
502 unsigned EstimatedLoopInvocationWeight = 0;
503 std::optional<unsigned> OriginalTripCount =
508 if (MaxTripCount && ULO.
Count > MaxTripCount)
509 ULO.
Count = MaxTripCount;
513 unsigned TripMultiple;
514 unsigned BreakoutTrip;
521 L->getExitingBlocks(ExitingBlocks);
522 for (
auto *ExitingBlock : ExitingBlocks) {
525 auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
532 if (
Info.TripCount != 0) {
534 Info.TripMultiple = 0;
536 Info.BreakoutTrip =
Info.TripMultiple =
539 Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
540 Info.ExitingBlocks.push_back(ExitingBlock);
541 LLVM_DEBUG(
dbgs() <<
" Exiting block %" << ExitingBlock->getName()
542 <<
": TripCount=" <<
Info.TripCount
543 <<
", TripMultiple=" <<
Info.TripMultiple
544 <<
", BreakoutTrip=" <<
Info.BreakoutTrip <<
"\n");
550 const bool CompletelyUnroll = ULO.
Count == MaxTripCount;
552 const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
556 if (CompletelyUnroll)
565 bool NeedToFixLCSSA =
566 PreserveLCSSA && CompletelyUnroll &&
580 bool LatchIsExiting = L->isLoopExiting(LatchBlock);
581 if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
583 dbgs() <<
"Can't unroll; a conditional latch must exit the loop");
584 return LoopUnrollResult::Unmodified;
588 "Can't runtime unroll if loop contains a convergent operation.");
590 bool EpilogProfitability =
598 PreserveLCSSA, RemainderLoop)) {
603 "generated when assuming runtime trip count\n");
604 return LoopUnrollResult::Unmodified;
610 if (CompletelyUnroll) {
611 LLVM_DEBUG(
dbgs() <<
"COMPLETELY UNROLLING loop %" << Header->getName()
612 <<
" with trip count " << ULO.
Count <<
"!\n");
617 <<
"completely unrolled loop with "
618 << NV(
"UnrollCount", ULO.
Count) <<
" iterations";
621 LLVM_DEBUG(
dbgs() <<
"UNROLLING loop %" << Header->getName() <<
" by "
631 Diag <<
"unrolled loop by a factor of " << NV(
"UnrollCount", ULO.
Count);
633 Diag <<
" with run-time trip count";
656 ++NumUnrolledNotLatch;
661 std::vector<PHINode*> OrigPHINode;
663 OrigPHINode.push_back(cast<PHINode>(
I));
666 std::vector<BasicBlock *> Headers;
667 std::vector<BasicBlock *> Latches;
668 Headers.push_back(Header);
669 Latches.push_back(LatchBlock);
681 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
688 for (
Loop *SubLoop : *L)
689 LoopsToSimplify.
insert(SubLoop);
693 if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
697 if (!
I.isDebugOrPseudoInst())
699 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.
Count);
701 I.setDebugLoc(*NewDIL);
704 <<
"Failed to create new discriminator: "
705 << DIL->getFilename() <<
" Line: " << DIL->getLine());
716 auto BlockInsertPt = std::next(LatchBlock->
getIterator());
717 for (
unsigned It = 1; It != ULO.
Count; ++It) {
725 Header->getParent()->insert(BlockInsertPt, New);
728 "Header should not be in a sub-loop");
732 LoopsToSimplify.
insert(NewLoops[OldLoop]);
737 for (
PHINode *OrigPHI : OrigPHINode) {
738 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
740 if (
Instruction *InValI = dyn_cast<Instruction>(InVal))
741 if (It > 1 && L->contains(InValI))
742 InVal = LastValueMap[InValI];
743 VMap[OrigPHI] = InVal;
751 Instruction *heartCopy = cast<Instruction>(it->second);
758 LastValueMap[*BB] = New;
761 LastValueMap[VI->first] = VI->second;
765 if (L->contains(Succ))
770 if (It != LastValueMap.
end())
779 Headers.push_back(New);
780 if (*BB == LatchBlock)
781 Latches.push_back(New);
785 auto ExitInfoIt = ExitInfos.
find(*BB);
786 if (ExitInfoIt != ExitInfos.
end())
787 ExitInfoIt->second.ExitingBlocks.push_back(New);
790 UnrolledLoopBlocks.push_back(New);
799 auto BBDomNode = DT->
getNode(*BB);
800 auto BBIDom = BBDomNode->
getIDom();
801 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
803 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
811 if (
auto *
II = dyn_cast<AssumeInst>(&
I))
818 std::string ext = (
Twine(
"It") +
Twine(It)).str();
820 Header->getContext(), ext);
825 for (
PHINode *PN : OrigPHINode) {
826 if (CompletelyUnroll) {
827 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
828 PN->eraseFromParent();
829 }
else if (ULO.
Count > 1) {
830 Value *InVal = PN->removeIncomingValue(LatchBlock,
false);
833 if (
Instruction *InValI = dyn_cast<Instruction>(InVal)) {
834 if (L->contains(InValI))
835 InVal = LastValueMap[InVal];
837 assert(Latches.back() == LastValueMap[LatchBlock] &&
"bad last latch");
838 PN->addIncoming(InVal, Latches.back());
844 for (
unsigned i = 0, e = Latches.size(); i != e; ++i) {
845 unsigned j = (i + 1) % e;
846 Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
854 for (
auto *BB : OriginalLoopBlocks) {
855 auto *BBDomNode = DT->
getNode(BB);
857 for (
auto *ChildDomNode : BBDomNode->children()) {
858 auto *ChildBB = ChildDomNode->getBlock();
859 if (!L->contains(ChildBB))
867 for (
auto *ChildBB : ChildrenToUpdate)
873 DT->
verify(DominatorTree::VerificationLevel::Fast));
876 auto SetDest = [&](
BasicBlock *Src,
bool WillExit,
bool ExitOnTrue) {
877 auto *Term = cast<BranchInst>(Src->getTerminator());
878 const unsigned Idx = ExitOnTrue ^ WillExit;
887 Term->eraseFromParent();
889 DTUpdates.
emplace_back(DominatorTree::Delete, Src, DeadSucc);
892 auto WillExit = [&](
const ExitInfo &
Info,
unsigned i,
unsigned j,
893 bool IsLatch) -> std::optional<bool> {
894 if (CompletelyUnroll) {
895 if (PreserveOnlyFirst) {
903 if (
Info.TripCount && j !=
Info.TripCount)
911 if (IsLatch && j != 0)
916 if (j !=
Info.BreakoutTrip &&
917 (
Info.TripMultiple == 0 || j %
Info.TripMultiple != 0)) {
927 for (
auto &Pair : ExitInfos) {
928 ExitInfo &
Info = Pair.second;
929 for (
unsigned i = 0, e =
Info.ExitingBlocks.size(); i != e; ++i) {
931 unsigned j = (i + 1) % e;
932 bool IsLatch = Pair.first == LatchBlock;
933 std::optional<bool> KnownWillExit = WillExit(
Info, i, j, IsLatch);
934 if (!KnownWillExit) {
935 if (!
Info.FirstExitingBlock)
936 Info.FirstExitingBlock =
Info.ExitingBlocks[i];
945 if (*KnownWillExit && !IsLatch) {
946 if (!
Info.FirstExitingBlock)
947 Info.FirstExitingBlock =
Info.ExitingBlocks[i];
951 SetDest(
Info.ExitingBlocks[i], *KnownWillExit,
Info.ExitOnTrue);
957 if (ExitingBlocks.
size() == 1 && ExitInfos.
size() == 1) {
965 auto &[OriginalExit,
Info] = *ExitInfos.
begin();
966 if (!
Info.FirstExitingBlock)
967 Info.FirstExitingBlock =
Info.ExitingBlocks.back();
969 if (L->contains(
C->getBlock()))
978 if (!LatchIsExiting && CompletelyUnroll) {
988 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
990 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
991 "Need a branch as terminator, except when fully unrolling with "
992 "unconditional latch");
993 if (Term && Term->isUnconditional()) {
999 DTUToUse ?
nullptr : DT)) {
1001 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
1012 DT->
verify(DominatorTree::VerificationLevel::Fast));
1019 NumCompletelyUnrolled += CompletelyUnroll;
1022 Loop *OuterL = L->getParentLoop();
1024 if (CompletelyUnroll) {
1028 }
else if (OriginalTripCount) {
1032 EstimatedLoopInvocationWeight);
1047 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
1057 if (NeedToFixLCSSA) {
1062 Loop *FixLCSSALoop = OuterL;
1063 if (!FixLCSSALoop->
contains(LatchLoop))
1068 }
else if (PreserveLCSSA) {
1070 "Loops should be in LCSSA form after loop-unroll.");
1075 simplifyLoop(OuterL, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1078 for (
Loop *SubLoop : LoopsToSimplify)
1079 simplifyLoop(SubLoop, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1082 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
1083 : LoopUnrollResult::PartiallyUnrolled;
1095 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...
Module.h This file contains the declarations for the Module class.
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)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
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< typename DomTreeT::UpdateType > 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)
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 forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
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...
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.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
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...
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...
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, Loop **ResultLoop=nullptr)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
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