38 #define DEBUG_TYPE "loop-unroll"
39 STATISTIC(NumPeeled,
"Number of loops peeled");
43 cl::desc(
"Max average trip count which will cause loop peeling."));
47 cl::desc(
"Force a peel count regardless of profiling information."));
91 "Non-loop Phi should not be checked for turning into invariant.");
94 auto I = IterationsToInvariance.
find(Phi);
95 if (I != IterationsToInvariance.
end())
107 else if (
PHINode *IncPhi = dyn_cast<PHINode>(Input)) {
109 if (IncPhi->getParent() != L->
getHeader())
114 IncPhi, L, BackEdge, IterationsToInvariance);
116 ToInvariance = InputToInvariance + 1u;
121 IterationsToInvariance[Phi] = ToInvariance;
128 unsigned &TripCount) {
129 assert(LoopSize > 0 &&
"Zero loop size is not allowed!");
144 if (2 * LoopSize <= UP.Threshold && UnrollPeelMaxCount > 0) {
149 unsigned DesiredPeelCount = 0;
151 assert(BackEdge &&
"Loop is not in simplified form?");
152 for (
auto BI = L->
getHeader()->begin(); isa<PHINode>(&*BI); ++BI) {
153 PHINode *Phi = cast<PHINode>(&*BI);
155 Phi, L, BackEdge, IterationsToInvariance);
157 DesiredPeelCount =
std::max(DesiredPeelCount, ToInvariance);
159 if (DesiredPeelCount > 0) {
163 DesiredPeelCount =
std::min(DesiredPeelCount, MaxPeelCount);
165 assert(DesiredPeelCount > 0 &&
"Wrong loop size estimation?");
166 DEBUG(
dbgs() <<
"Peel " << DesiredPeelCount <<
" iteration(s) to turn"
167 <<
" some Phis into invariants.\n");
182 <<
" iterations.\n");
197 DEBUG(
dbgs() <<
"Profile-based estimated trip count is " << *PeelCount
202 (LoopSize * (*PeelCount + 1) <= UP.
Threshold)) {
203 DEBUG(
dbgs() <<
"Peeling first " << *PeelCount <<
" iterations.\n");
207 DEBUG(
dbgs() <<
"Requested peel count: " << *PeelCount <<
"\n");
209 DEBUG(
dbgs() <<
"Peel cost: " << LoopSize * (*PeelCount + 1) <<
"\n");
237 unsigned IterNumber,
unsigned AvgIters,
238 uint64_t &PeeledHeaderWeight) {
244 if (PeeledHeaderWeight) {
245 uint64_t FallThruWeight =
246 PeeledHeaderWeight * ((float)(AvgIters - IterNumber) / AvgIters * 0.9);
247 uint64_t ExitWeight = PeeledHeaderWeight - FallThruWeight;
248 PeeledHeaderWeight -= ExitWeight;
250 unsigned HeaderIdx = (LatchBR->
getSuccessor(0) == Header ? 0 : 1);
253 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThruWeight)
254 : MDB.createBranchWeights(FallThruWeight, ExitWeight);
319 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
321 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
323 LatchBR->setSuccessor(1 - HeaderIdx, Exit);
336 PHINode *NewPHI = cast<PHINode>(VMap[&*
I]);
337 if (IterNumber == 0) {
342 if (LatchInst && L->
contains(LatchInst))
343 VMap[&*
I] = LVMap[LatchInst];
345 VMap[&*
I] = LatchVal;
347 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
358 if (LatchInst && L->
contains(LatchInst))
359 LatchVal = VMap[LatchVal];
360 PHI->
addIncoming(LatchVal, cast<BasicBlock>(VMap[Latch]));
365 for (
const auto &KV : VMap)
366 LVMap[KV.first] = KV.second;
447 NewPreHeader->setName(PreHeader->
getName() +
".peel.newph");
454 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
455 unsigned HeaderIdx = (LatchBR->
getSuccessor(0) == Header ? 0 : 1);
457 uint64_t TrueWeight, FalseWeight;
458 uint64_t ExitWeight = 0, CurHeaderWeight = 0;
460 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
463 CurHeaderWeight = TrueWeight + FalseWeight;
467 for (
unsigned Iter = 0; Iter < PeelCount; ++Iter) {
475 if (ExitWeight < CurHeaderWeight)
476 CurHeaderWeight -= ExitWeight;
481 NewBlocks, LoopBlocks, VMap, LVMap, DT, LI);
500 PeelCount, ExitWeight);
502 InsertTop = InsertBot;
508 NewBlocks[0]->getIterator(), F->
end());
517 if (LatchInst && L->
contains(LatchInst))
518 NewVal = LVMap[LatchInst];
528 uint64_t BackEdgeWeight = 0;
529 if (ExitWeight < CurHeaderWeight)
530 BackEdgeWeight = CurHeaderWeight - ExitWeight;
535 HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
536 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
545 simplifyLoop(ParentLoop, DT, LI, SE, AC, PreserveLCSSA);
void push_back(const T &Elt)
BasicBlock * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
STATISTIC(NumFunctions,"Total number of functions")
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
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
The main scalar evolution driver.
A cache of .assume calls within a function.
static void cloneLoopBlocks(Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, BasicBlock *Exit, SmallVectorImpl< BasicBlock * > &NewBlocks, LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, LoopInfo *LI)
Clones the body of the loop L, putting it between InsertTop and InsertBot.
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
BlockT * getHeader() const
void remapInstructionsInBlocks(const SmallVectorImpl< BasicBlock * > &Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
StringRef getName() const
Return a constant reference to the value's name.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
static unsigned calculateIterationsToInvariance(PHINode *Phi, Loop *L, BasicBlock *BackEdge, SmallDenseMap< PHINode *, unsigned > &IterationsToInvariance)
static cl::opt< unsigned > UnrollPeelMaxCount("unroll-peel-max-count", cl::init(7), cl::Hidden, cl::desc("Max average trip count which will cause loop peeling."))
static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR, unsigned IterNumber, unsigned AvgIters, uint64_t &PeeledHeaderWeight)
Update the branch weights of the latch of a peeled-off loop iteration.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void setName(const Twine &Name)
Change the name of the value.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
BasicBlock * getSuccessor(unsigned i) const
Base class for the actual dominator tree node.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
iterator find(const_arg_type_t< KeyT > Val)
initializer< Ty > init(const Ty &Val)
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
static cl::opt< unsigned > UnrollForcePeelCount("unroll-force-peel-count", cl::init(0), cl::Hidden, cl::desc("Force a peel count regardless of profiling information."))
bool peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, bool PreserveLCSSA)
Peel off the first PeelCount iterations of loop L.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
void splice(iterator where, iplist_impl &L2)
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
self_iterator getIterator()
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
bool VerifyDomInfo
Enables verification of dominator trees.
void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP, unsigned &TripCount)
void verifyDomTree() const
Verify the correctness of the domtree by re-computing it.
LLVMContext & getContext() const
All values hold a context through their type.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
static const unsigned InfiniteIterationsToInvariance
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
static bool canPeel(Loop *L)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Store the result of a depth first search within basic blocks contained by a single loop...
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
Represents a single loop in the control flow graph.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setIncomingValue(unsigned i, Value *V)
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
const BasicBlock * getParent() const
RPOIterator endRPO() const