43 #define DEBUG_TYPE "loop-unroll"
47 cl::desc(
"The cost threshold for loop unrolling"));
51 cl::desc(
"The cost threshold for partial loop unrolling"));
55 cl::desc(
"The maximum 'boost' (represented as a percentage >= 100) applied "
56 "to the threshold when aggressively unrolling a loop due to the "
57 "dynamic cost savings. If completely unrolling a loop will reduce "
58 "the total runtime from X to Y, we boost the loop unroll "
59 "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, "
60 "X/Y). This limit avoids excessive code bloat."));
64 cl::desc(
"Don't allow loop unrolling to simulate more than this number of"
65 "iterations when checking full unroll profitability"));
69 cl::desc(
"Use this unroll count for all loops including those with "
70 "unroll_count pragma values, for testing purposes"));
74 cl::desc(
"Set the max unroll count for partial and runtime unrolling, for"
80 "Set the max unroll count for full unrolling, for testing purposes"));
84 cl::desc(
"Allows loops to be partially unrolled until "
85 "-unroll-threshold loop size is reached."));
89 cl::desc(
"Allow generation of a loop remainder (extra iterations) "
90 "when unrolling a loop."));
94 cl::desc(
"Unroll loops with run-time trip counts"));
99 "The max of trip count upper bound that is considered in unrolling"));
103 cl::desc(
"Unrolled size limit for loops with an unroll(full) or "
104 "unroll_count pragma."));
108 cl::desc(
"If the runtime tripcount for the loop is lower than the "
109 "threshold, the loop is considered as flat and will be less "
110 "aggressively unrolled."));
114 cl::desc(
"Allows loops to be peeled when the dynamic "
115 "trip count is known to be low."));
122 cl::desc(
"Enqueue and re-visit child loops in the loop PM after unrolling. "
123 "This shouldn't typically be needed as child loops (or their "
124 "clones) were already visited."));
164 if (L->
getHeader()->getParent()->optForSize()) {
197 UP.
Count = *UserCount;
199 UP.
Partial = *UserAllowPartial;
215 struct UnrolledInstState {
219 unsigned IsCounted : 1;
223 struct UnrolledInstStateKeyInfo {
226 static inline UnrolledInstState getEmptyKey() {
227 return {PtrInfo::getEmptyKey(), 0, 0, 0};
229 static inline UnrolledInstState getTombstoneKey() {
230 return {PtrInfo::getTombstoneKey(), 0, 0, 0};
232 static inline unsigned getHashValue(
const UnrolledInstState &S) {
233 return PairInfo::getHashValue({S.I, S.Iteration});
235 static inline bool isEqual(
const UnrolledInstState &LHS,
236 const UnrolledInstState &RHS) {
243 struct EstimatedUnrollCost {
245 unsigned UnrolledCost;
249 unsigned RolledDynamicCost;
269 unsigned MaxUnrolledLoopSize) {
274 "The unroll iterations max is too large!");
293 unsigned UnrolledCost = 0;
300 unsigned RolledDynamicCost = 0;
316 auto AddCostRecursively = [&](
Instruction &RootI,
int Iteration) {
317 assert(Iteration >= 0 &&
"Cannot have a negative iteration!");
318 assert(CostWorklist.
empty() &&
"Must start with an empty cost list");
319 assert(PHIUsedList.
empty() &&
"Must start with an empty phi used list");
321 for (;; --Iteration) {
327 auto CostIter = InstCostMap.
find({
I, Iteration, 0, 0});
328 if (CostIter == InstCostMap.
end())
333 auto &Cost = *CostIter;
339 Cost.IsCounted =
true;
342 if (
auto *PhiI = dyn_cast<PHINode>(I))
343 if (PhiI->getParent() == L->
getHeader()) {
344 assert(Cost.IsFree &&
"Loop PHIs shouldn't be evaluated as they "
345 "inherently simplify during unrolling.");
352 if (
auto *OpI = dyn_cast<Instruction>(
362 DEBUG(
dbgs() <<
"Adding cost of instruction (iteration " << Iteration
380 }
while (!CostWorklist.
empty());
382 if (PHIUsedList.
empty())
387 "Cannot track PHI-used values past the first iteration!");
397 "Must have loops in LCSSA form to track live-out values.");
399 DEBUG(
dbgs() <<
"Starting LoopUnroll profitability analysis...\n");
405 for (
unsigned Iteration = 0; Iteration < TripCount; ++Iteration) {
406 DEBUG(
dbgs() <<
" Analyzing iteration " << Iteration <<
"\n");
418 PHI->getNumIncomingValues() == 2 &&
419 "Must have an incoming value only for the preheader and the latch.");
421 Value *V = PHI->getIncomingValueForBlock(
424 if (Iteration != 0 && !C)
425 C = SimplifiedValues.
lookup(V);
427 SimplifiedInputValues.
push_back({PHI, C});
431 SimplifiedValues.
clear();
432 while (!SimplifiedInputValues.
empty())
440 for (
unsigned Idx = 0; Idx != BBWorklist.
size(); ++Idx) {
447 if (isa<DbgInfoIntrinsic>(
I))
457 bool IsFree = Analyzer.
visit(
I);
458 bool Inserted = InstCostMap.
insert({&
I, (int)Iteration,
462 assert(Inserted &&
"Cannot have a state for an unvisited instruction!");
469 if(isa<CallInst>(&
I))
474 if (
I.mayHaveSideEffects())
475 AddCostRecursively(
I, Iteration);
478 if (UnrolledCost > MaxUnrolledLoopSize) {
479 DEBUG(
dbgs() <<
" Exceeded threshold.. exiting.\n"
480 <<
" UnrolledCost: " << UnrolledCost
481 <<
", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize
492 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
493 if (BI->isConditional()) {
495 SimplifiedValues.
lookup(BI->getCondition())) {
497 if (isa<UndefValue>(SimpleCond))
498 KnownSucc = BI->getSuccessor(0);
500 dyn_cast<ConstantInt>(SimpleCond))
501 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0);
506 SimplifiedValues.
lookup(
SI->getCondition())) {
508 if (isa<UndefValue>(SimpleCond))
509 KnownSucc =
SI->getSuccessor(0);
511 dyn_cast<ConstantInt>(SimpleCond))
512 KnownSucc =
SI->findCaseValue(SimpleCondVal)->getCaseSuccessor();
517 BBWorklist.
insert(KnownSucc);
519 ExitWorklist.
insert({BB, KnownSucc});
528 ExitWorklist.
insert({BB, Succ});
529 AddCostRecursively(*TI, Iteration);
534 if (UnrolledCost == RolledDynamicCost) {
535 DEBUG(
dbgs() <<
" No opportunities found.. exiting.\n"
536 <<
" UnrolledCost: " << UnrolledCost <<
"\n");
541 while (!ExitWorklist.
empty()) {
543 std::tie(ExitingBB, ExitBB) = ExitWorklist.
pop_back_val();
550 Value *
Op = PN->getIncomingValueForBlock(ExitingBB);
551 if (
auto *OpI = dyn_cast<Instruction>(Op))
553 AddCostRecursively(*OpI, TripCount - 1);
558 <<
"UnrolledCost: " << UnrolledCost <<
", "
559 <<
"RolledDynamicCost: " << RolledDynamicCost <<
"\n");
560 return {{UnrolledCost, RolledDynamicCost}};
578 unsigned LoopSize = Metrics.
NumInsts;
586 LoopSize =
std::max(LoopSize, BEInsns + 1);
627 "Unroll count hint metadata should have two operands.");
629 mdconst::extract<ConstantInt>(MD->
getOperand(1))->getZExtValue();
630 assert(Count >= 1 &&
"Unroll count must be positive.");
648 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
649 bool IsUnrollMetadata =
false;
655 if (!IsUnrollMetadata)
679 unsigned MaxPercentThresholdBoost) {
680 if (Cost.RolledDynamicCost >= UINT_MAX / 100)
682 else if (Cost.UnrolledCost != 0)
684 return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost,
685 MaxPercentThresholdBoost);
687 return MaxPercentThresholdBoost;
694 assert(LoopSize >= UP.
BEInsns &&
"LoopSize should not be less than BEInsns!");
703 unsigned MaxTripCount,
unsigned &TripMultiple,
unsigned LoopSize,
707 bool UserUnrollCount =
UnrollCount.getNumOccurrences() > 0;
708 if (UserUnrollCount) {
718 if (PragmaCount > 0) {
719 UP.
Count = PragmaCount;
728 if (PragmaFullUnroll && TripCount != 0) {
729 UP.
Count = TripCount;
735 bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll ||
736 PragmaEnableUnroll || UserUnrollCount;
738 if (ExplicitUnroll && TripCount != 0) {
755 unsigned ExactTripCount = TripCount;
756 assert((ExactTripCount == 0 || MaxTripCount == 0) &&
757 "ExtractTripCound and MaxTripCount cannot both be non zero.");
758 unsigned FullUnrollTripCount = ExactTripCount ? ExactTripCount : MaxTripCount;
759 UP.
Count = FullUnrollTripCount;
764 UseUpperBound = (MaxTripCount == FullUnrollTripCount);
765 TripCount = FullUnrollTripCount;
766 TripMultiple = UP.
UpperBound ? 1 : TripMultiple;
767 return ExplicitUnroll;
773 L, FullUnrollTripCount, DT, SE, TTI,
777 if (Cost->UnrolledCost < UP.
Threshold * Boost / 100) {
778 UseUpperBound = (MaxTripCount == FullUnrollTripCount);
779 TripCount = FullUnrollTripCount;
780 TripMultiple = UP.
UpperBound ? 1 : TripMultiple;
781 return ExplicitUnroll;
792 return ExplicitUnroll;
800 DEBUG(
dbgs() <<
" will not try to unroll partially because "
801 <<
"-unroll-allow-partial not given\n");
806 UP.
Count = TripCount;
815 while (UP.
Count != 0 && TripCount % UP.
Count != 0)
823 while (UP.
Count != 0 &&
828 if (PragmaEnableUnroll)
832 <<
"Unable to unroll loop as directed by unroll(enable) pragma "
833 "because unrolled size is too large.");
837 UP.
Count = TripCount;
841 if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount &&
842 UP.
Count != TripCount)
846 <<
"Unable to fully unroll loop as directed by unroll pragma because "
847 "unrolled size is too large.");
848 return ExplicitUnroll;
851 "All cases when TripCount is constant should be covered here.");
852 if (PragmaFullUnroll)
855 "CantFullUnrollAsDirectedRuntimeTripCount",
857 <<
"Unable to fully unroll loop as directed by unroll(full) pragma "
858 "because loop has a runtime trip count.");
868 if (L->
getHeader()->getParent()->getEntryCount()) {
878 UP.
Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount;
880 DEBUG(
dbgs() <<
" will not try to unroll loop with runtime trip count "
881 <<
"-unroll-runtime not given\n");
890 while (UP.
Count != 0 &&
895 unsigned OrigCount = UP.
Count;
899 while (UP.
Count != 0 && TripMultiple % UP.
Count != 0)
901 DEBUG(
dbgs() <<
"Remainder loop is restricted (that could architecture "
902 "specific or because the loop contains a convergent "
903 "instruction), so unroll count must divide the trip "
905 << TripMultiple <<
". Reducing unroll count from "
906 << OrigCount <<
" to " << UP.
Count <<
".\n");
911 "DifferentUnrollCountFromDirected",
913 <<
"Unable to unroll loop the number of times directed by "
914 "unroll_count pragma because remainder loop is restricted "
915 "(that could architecture specific or because the loop "
916 "contains a convergent instruction) and so must have an unroll "
917 "count that divides the loop trip multiple of "
918 <<
NV(
"TripMultiple", TripMultiple) <<
". Unrolling instead "
919 <<
NV(
"UnrollCount", UP.
Count) <<
" time(s).");
924 DEBUG(
dbgs() <<
" partially unrolling with count: " << UP.
Count <<
"\n");
927 return ExplicitUnroll;
933 bool PreserveLCSSA,
int OptLevel,
940 <<
"] Loop %" << L->
getHeader()->getName() <<
"\n");
945 dbgs() <<
" Not unrolling loop which is not in loop-simplify form.\n");
949 unsigned NumInlineCandidates;
950 bool NotDuplicatable;
953 L, SE, TTI, OptLevel, ProvidedThreshold, ProvidedCount,
954 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound);
959 L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC, UP.
BEInsns);
960 DEBUG(
dbgs() <<
" Loop Size = " << LoopSize <<
"\n");
961 if (NotDuplicatable) {
962 DEBUG(
dbgs() <<
" Not unrolling loop which contains non-duplicatable"
963 <<
" instructions.\n");
966 if (NumInlineCandidates != 0) {
967 DEBUG(
dbgs() <<
" Not unrolling loop with inlinable calls.\n");
972 unsigned TripCount = 0;
973 unsigned MaxTripCount = 0;
974 unsigned TripMultiple = 1;
1003 bool MaxOrZero =
false;
1022 bool UseUpperBound =
false;
1023 bool IsCountSetExplicitly =
1025 TripMultiple, LoopSize, UP, UseUpperBound);
1029 if (TripCount && UP.
Count > TripCount)
1030 UP.
Count = TripCount;
1035 TripMultiple, UP.
PeelCount, LI, &SE, &DT, &AC, &ORE,
1043 if (IsCountSetExplicitly || UP.
PeelCount)
1050 class LoopUnroll :
public LoopPass {
1057 :
LoopPass(
ID), OptLevel(OptLevel), ProvidedCount(std::move(Count)),
1058 ProvidedThreshold(
Threshold), ProvidedAllowPartial(AllowPartial),
1059 ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound) {
1076 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1077 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1078 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1080 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1081 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1086 bool PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
1088 return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, ORE, PreserveLCSSA, OptLevel,
1089 ProvidedCount, ProvidedThreshold,
1090 ProvidedAllowPartial, ProvidedRuntime,
1091 ProvidedUpperBound);
1115 int AllowPartial,
int Runtime,
1120 return new LoopUnroll(
1137 Function *
F = L.getHeader()->getParent();
1143 "cached at a higher level");
1147 Loop *ParentL = L.getParentLoop();
1159 if (!AllowPartialUnrolling)
1160 AllowPartialParam = RuntimeParam = UpperBoundParam =
false;
1163 true, OptLevel,
None,
1164 None, AllowPartialParam, RuntimeParam, UpperBoundParam);
1194 bool IsCurrentLoopValid =
false;
1201 if (SibLoop == &L) {
1202 IsCurrentLoopValid =
true;
1207 return OldLoops.
count(SibLoop) != 0;
1211 if (!IsCurrentLoopValid) {
Pass interface - Implemented by all 'passes'.
unsigned getSmallConstantTripCount(const Loop *L)
Returns the maximum trip count of the loop if it is a single-exit loop and we can compute a small max...
void push_back(const T &Elt)
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...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
unsigned getSmallConstantTripMultiple(const Loop *L)
Returns the largest constant divisor of the trip count of the loop if it is a single-exit loop and we...
DiagnosticInfoOptimizationBase::Argument NV
LLVM_NODISCARD T pop_back_val()
static cl::opt< unsigned > UnrollCount("unroll-count", cl::Hidden, cl::desc("Use this unroll count for all loops including those with ""unroll_count pragma values, for testing purposes"))
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
This is the interface for a simple mod/ref and alias analysis over globals.
bool convergent
True if this function contains a call to a convergent function.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDString * get(LLVMContext &Context, StringRef Str)
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
static bool HasUnrollEnablePragma(const Loop *L)
Implements a dense probed hash-table based set.
unsigned getNumOperands() const
Return number of MDNode operands.
The main scalar evolution driver.
static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost, unsigned MaxPercentThresholdBoost)
An immutable pass that tracks lazily created AssumptionCache objects.
static cl::opt< bool > UnrollAllowPartial("unroll-allow-partial", cl::Hidden, cl::desc("Allows loops to be partially unrolled until ""-unroll-threshold loop size is reached."))
A cache of .assume calls within a function.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
unsigned NumInlineCandidates
The number of calls to internal functions with a single caller.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, const TargetTransformInfo &TTI, AssumptionCache &AC, OptimizationRemarkEmitter &ORE, bool PreserveLCSSA, int OptLevel, Optional< unsigned > ProvidedCount, Optional< unsigned > ProvidedThreshold, Optional< bool > ProvidedAllowPartial, Optional< bool > ProvidedRuntime, Optional< bool > ProvidedUpperBound)
bool notDuplicatable
True if this function cannot be duplicated.
size_type size() const
Determine the number of elements in the SetVector.
BlockT * getHeader() const
bool UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, bool Force, bool AllowRuntime, bool AllowExpensiveTripCount, bool PreserveCondBr, bool PreserveOnlyFirst, unsigned TripMultiple, unsigned PeelCount, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA)
Unroll the given loop by Count.
static cl::opt< bool > UnrollAllowRemainder("unroll-allow-remainder", cl::Hidden, cl::desc("Allow generation of a loop remainder (extra iterations) ""when unrolling a loop."))
unsigned getSmallConstantMaxTripCount(const Loop *L)
Returns the upper bound of the loop trip count as a normal unsigned value.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static cl::opt< unsigned > UnrollPartialThreshold("unroll-partial-threshold", cl::Hidden, cl::desc("The cost threshold for partial loop unrolling"))
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static cl::opt< unsigned > UnrollMaxPercentThresholdBoost("unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden, cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied ""to the threshold when aggressively unrolling a loop due to the ""dynamic cost savings. If completely unrolling a loop will reduce ""the total runtime from X to Y, we boost the loop unroll ""threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, ""X/Y). This limit avoids excessive code bloat."))
static bool HasUnrollFullPragma(const Loop *L)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Pass * createSimpleLoopUnrollPass(int OptLevel=2)
static cl::opt< bool > UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden, cl::desc("Unroll loops with run-time trip counts"))
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
LLVM_NODISCARD bool empty() const
static MDNode * GetUnrollMetadataForLoop(const Loop *L, StringRef Name)
void visit(Iterator Start, Iterator End)
bool insert(const value_type &X)
Insert a new element into the SetVector.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
static bool isEqual(const Function &Caller, const Function &Callee)
static cl::opt< bool > UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, cl::desc("Allows loops to be peeled when the dynamic ""trip count is known to be low."))
bool empty() const
Determine if the SetVector is empty or not.
void initializeLoopUnrollPass(PassRegistry &)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
iterator_range< block_iterator > blocks() const
void verifyLoop() const
Verify loop structure.
static bool computeUnrollCount(Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, OptimizationRemarkEmitter *ORE, unsigned &TripCount, unsigned MaxTripCount, unsigned &TripMultiple, unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP, bool &UseUpperBound)
Function Alias Analysis false
initializer< Ty > init(const Ty &Val)
static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, bool &NotDuplicatable, bool &Convergent, const TargetTransformInfo &TTI, AssumptionCache *AC, unsigned BEInsns)
ApproximateLoopSize - Approximate the size of the loop.
static cl::opt< unsigned > UnrollMaxCount("unroll-max-count", cl::Hidden, cl::desc("Set the max unroll count for partial and runtime unrolling, for""testing purposes"))
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static cl::opt< unsigned > UnrollMaxUpperBound("unroll-max-upperbound", cl::init(8), cl::Hidden, cl::desc("The max of trip count upper bound that is considered in unrolling"))
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
static Optional< EstimatedUnrollCost > analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize)
Figure out if the loop is worth full unrolling.
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
void addChildLoops(ArrayRef< Loop * > NewChildLoops)
Loop passes should use this method to indicate they have added new child loops of the current loop...
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static cl::opt< unsigned > UnrollThreshold("unroll-threshold", cl::Hidden, cl::desc("The cost threshold for loop unrolling"))
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP, unsigned &TripCount)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
TargetTransformInfo & TTI
void dump() const
Support for debugging, callable in GDB: V->dump()
void addSiblingLoops(ArrayRef< Loop * > NewSibLoops)
Loop passes should use this method to indicate they have added new sibling loops to the current loop...
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
StringRef getString() const
static cl::opt< unsigned > FlatLoopTripCountThreshold("flat-loop-tripcount-threshold", cl::init(5), cl::Hidden, cl::desc("If the runtime tripcount for the loop is lower than the ""threshold, the loop is considered as flat and will be less ""aggressively unrolled."))
const MDOperand & getOperand(unsigned I) const
A SetVector that performs no allocations if smaller than a certain size.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static unsigned UnrollCountPragmaValue(const Loop *L)
LLVM_NODISCARD T pop_back_val()
static cl::opt< unsigned > PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 *1024), cl::Hidden, cl::desc("Unrolled size limit for loops with an unroll(full) or ""unroll_count pragma."))
static uint64_t getUnrolledLoopSize(unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP)
static cl::opt< unsigned > UnrollFullMaxCount("unroll-full-max-count", cl::Hidden, cl::desc("Set the max unroll count for full unrolling, for testing purposes"))
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Pass * createLoopUnrollPass(int OptLevel=2, int Threshold=-1, int Count=-1, int AllowPartial=-1, int Runtime=-1, int UpperBound=-1)
static void SetLoopAlreadyUnrolled(Loop *L)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void clear()
Completely clear the SetVector.
static bool HasUnrollDisablePragma(const Loop *L)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
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...
static cl::opt< unsigned > UnrollMaxIterationsCountToAnalyze("unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden, cl::desc("Don't allow loop unrolling to simulate more than this number of""iterations when checking full unroll profitability"))
static const unsigned NoThreshold
A magic value for use with the Threshold parameter to indicate that the loop unroll should be perform...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Represents a single loop in the control flow graph.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
static cl::opt< bool > UnrollRevisitChildLoops("unroll-revisit-child-loops", cl::Hidden, cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. ""This shouldn't typically be needed as child loops (or their ""clones) were already visited."))
iterator find(const_arg_type_t< ValueT > V)
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &EphValues)
Add information about a block to the current state.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
static bool HasRuntimeUnrollDisablePragma(const Loop *L)
static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, int OptLevel, Optional< unsigned > UserThreshold, Optional< unsigned > UserCount, Optional< bool > UserAllowPartial, Optional< bool > UserRuntime, Optional< bool > UserUpperBound)
Gather the various unrolling parameters based on the defaults, compiler flags, TTI overrides and user...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getMaxBackedgeTakenCount or z...
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
void markLoopAsDeleted(Loop &L)
Loop passes should use this method to indicate they have deleted a loop from the nest.
unsigned NumInsts
Number of instructions in the analyzed blocks.