LLVM  4.0.0
LoopDeletion.cpp
Go to the documentation of this file.
1 //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Dead Loop Deletion Pass. This pass is responsible
11 // for eliminating loops with non-infinite computable trip counts that have no
12 // side effects or volatile instructions, and do not contribute to the
13 // computation of the function's return value.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/Transforms/Scalar.h"
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "loop-delete"
29 
30 STATISTIC(NumDeleted, "Number of loops deleted");
31 
32 /// isLoopDead - Determined if a loop is dead. This assumes that we've already
33 /// checked for unique exit and exiting blocks, and that the code is in LCSSA
34 /// form.
35 bool LoopDeletionPass::isLoopDead(Loop *L, ScalarEvolution &SE,
36  SmallVectorImpl<BasicBlock *> &exitingBlocks,
38  bool &Changed, BasicBlock *Preheader) {
39  BasicBlock *exitBlock = exitBlocks[0];
40 
41  // Make sure that all PHI entries coming from the loop are loop invariant.
42  // Because the code is in LCSSA form, any values used outside of the loop
43  // must pass through a PHI in the exit block, meaning that this check is
44  // sufficient to guarantee that no loop-variant values are used outside
45  // of the loop.
46  BasicBlock::iterator BI = exitBlock->begin();
47  bool AllEntriesInvariant = true;
48  bool AllOutgoingValuesSame = true;
49  while (PHINode *P = dyn_cast<PHINode>(BI)) {
50  Value *incoming = P->getIncomingValueForBlock(exitingBlocks[0]);
51 
52  // Make sure all exiting blocks produce the same incoming value for the exit
53  // block. If there are different incoming values for different exiting
54  // blocks, then it is impossible to statically determine which value should
55  // be used.
56  AllOutgoingValuesSame =
57  all_of(makeArrayRef(exitingBlocks).slice(1), [&](BasicBlock *BB) {
58  return incoming == P->getIncomingValueForBlock(BB);
59  });
60 
61  if (!AllOutgoingValuesSame)
62  break;
63 
64  if (Instruction *I = dyn_cast<Instruction>(incoming))
65  if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
66  AllEntriesInvariant = false;
67  break;
68  }
69 
70  ++BI;
71  }
72 
73  if (Changed)
75 
76  if (!AllEntriesInvariant || !AllOutgoingValuesSame)
77  return false;
78 
79  // Make sure that no instructions in the block have potential side-effects.
80  // This includes instructions that could write to memory, and loads that are
81  // marked volatile. This could be made more aggressive by using aliasing
82  // information to identify readonly and readnone calls.
83  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
84  LI != LE; ++LI) {
85  for (Instruction &I : **LI) {
86  if (I.mayHaveSideEffects())
87  return false;
88  }
89  }
90 
91  return true;
92 }
93 
94 /// Remove dead loops, by which we mean loops that do not impact the observable
95 /// behavior of the program other than finite running time. Note we do ensure
96 /// that this never remove a loop that might be infinite, as doing so could
97 /// change the halting/non-halting nature of a program. NOTE: This entire
98 /// process relies pretty heavily on LoopSimplify and LCSSA in order to make
99 /// various safety checks work.
101  LoopInfo &loopInfo) {
102  assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
103 
104  // We can only remove the loop if there is a preheader that we can
105  // branch from after removing it.
107  if (!preheader)
108  return false;
109 
110  // If LoopSimplify form is not available, stay out of trouble.
111  if (!L->hasDedicatedExits())
112  return false;
113 
114  // We can't remove loops that contain subloops. If the subloops were dead,
115  // they would already have been removed in earlier executions of this pass.
116  if (L->begin() != L->end())
117  return false;
118 
119  SmallVector<BasicBlock *, 4> exitingBlocks;
120  L->getExitingBlocks(exitingBlocks);
121 
122  SmallVector<BasicBlock *, 4> exitBlocks;
123  L->getUniqueExitBlocks(exitBlocks);
124 
125  // We require that the loop only have a single exit block. Otherwise, we'd
126  // be in the situation of needing to be able to solve statically which exit
127  // block will be branched to, or trying to preserve the branching logic in
128  // a loop invariant manner.
129  if (exitBlocks.size() != 1)
130  return false;
131 
132  // Finally, we have to check that the loop really is dead.
133  bool Changed = false;
134  if (!isLoopDead(L, SE, exitingBlocks, exitBlocks, Changed, preheader))
135  return Changed;
136 
137  // Don't remove loops for which we can't solve the trip count.
138  // They could be infinite, in which case we'd be changing program behavior.
139  const SCEV *S = SE.getMaxBackedgeTakenCount(L);
140  if (isa<SCEVCouldNotCompute>(S))
141  return Changed;
142 
143  // Now that we know the removal is safe, remove the loop by changing the
144  // branch from the preheader to go to the single exit block.
145  BasicBlock *exitBlock = exitBlocks[0];
146 
147  // Because we're deleting a large chunk of code at once, the sequence in which
148  // we remove things is very important to avoid invalidation issues. Don't
149  // mess with this unless you have good reason and know what you're doing.
150 
151  // Tell ScalarEvolution that the loop is deleted. Do this before
152  // deleting the loop so that ScalarEvolution can look at the loop
153  // to determine what it needs to clean up.
154  SE.forgetLoop(L);
155 
156  // Connect the preheader directly to the exit block.
157  TerminatorInst *TI = preheader->getTerminator();
158  TI->replaceUsesOfWith(L->getHeader(), exitBlock);
159 
160  // Rewrite phis in the exit block to get their inputs from
161  // the preheader instead of the exiting block.
162  BasicBlock *exitingBlock = exitingBlocks[0];
163  BasicBlock::iterator BI = exitBlock->begin();
164  while (PHINode *P = dyn_cast<PHINode>(BI)) {
165  int j = P->getBasicBlockIndex(exitingBlock);
166  assert(j >= 0 && "Can't find exiting block in exit block's phi node!");
167  P->setIncomingBlock(j, preheader);
168  for (unsigned i = 1; i < exitingBlocks.size(); ++i)
169  P->removeIncomingValue(exitingBlocks[i]);
170  ++BI;
171  }
172 
173  // Update the dominator tree and remove the instructions and blocks that will
174  // be deleted from the reference counting scheme.
175  SmallVector<DomTreeNode*, 8> ChildNodes;
176  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
177  LI != LE; ++LI) {
178  // Move all of the block's children to be children of the preheader, which
179  // allows us to remove the domtree entry for the block.
180  ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
181  for (DomTreeNode *ChildNode : ChildNodes) {
182  DT.changeImmediateDominator(ChildNode, DT[preheader]);
183  }
184 
185  ChildNodes.clear();
186  DT.eraseNode(*LI);
187 
188  // Remove the block from the reference counting scheme, so that we can
189  // delete it freely later.
190  (*LI)->dropAllReferences();
191  }
192 
193  // Erase the instructions and the blocks without having to worry
194  // about ordering because we already dropped the references.
195  // NOTE: This iteration is safe because erasing the block does not remove its
196  // entry from the loop's block list. We do that in the next section.
197  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
198  LI != LE; ++LI)
199  (*LI)->eraseFromParent();
200 
201  // Finally, the blocks from loopinfo. This has to happen late because
202  // otherwise our loop iterators won't work.
203 
205  blocks.insert(L->block_begin(), L->block_end());
206  for (BasicBlock *BB : blocks)
207  loopInfo.removeBlock(BB);
208 
209  // The last step is to update LoopInfo now that we've eliminated this loop.
210  loopInfo.markAsRemoved(L);
211  Changed = true;
212 
213  ++NumDeleted;
214 
215  return Changed;
216 }
217 
220  LPMUpdater &) {
221  bool Changed = runImpl(&L, AR.DT, AR.SE, AR.LI);
222  if (!Changed)
223  return PreservedAnalyses::all();
224 
226 }
227 
228 namespace {
229 class LoopDeletionLegacyPass : public LoopPass {
230 public:
231  static char ID; // Pass ID, replacement for typeid
232  LoopDeletionLegacyPass() : LoopPass(ID) {
234  }
235 
236  // Possibly eliminate loop L if it is dead.
237  bool runOnLoop(Loop *L, LPPassManager &) override;
238 
239  void getAnalysisUsage(AnalysisUsage &AU) const override {
241  }
242 };
243 }
244 
246 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
247  "Delete dead loops", false, false)
249 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
250  "Delete dead loops", false, false)
251 
252 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
253 
254 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) {
255  if (skipLoop(L))
256  return false;
257 
258  DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
259  ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
260  LoopInfo &loopInfo = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
261 
262  LoopDeletionPass Impl;
263  return Impl.runImpl(L, DT, SE, loopInfo);
264 }
MachineLoop * L
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:81
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
bool runImpl(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &loopInfo)
Remove dead loops, by which we mean loops that do not impact the observable behavior of the program o...
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Definition: LoopInfo.h:637
STATISTIC(NumFunctions,"Total number of functions")
size_t i
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass,"loop-deletion","Delete dead loops", false, false) INITIALIZE_PASS_END(LoopDeletionLegacyPass
This is the interface for a simple mod/ref and alias analysis over globals.
void initializeLoopDeletionLegacyPassPass(PassRegistry &)
The main scalar evolution driver.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:736
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
BlockT * getHeader() const
Definition: LoopInfo.h:102
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:228
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:53
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:440
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:32
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Definition: LoopInfoImpl.h:36
loop Delete dead loops
Base class for the actual dominator tree node.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:96
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:24
#define P(N)
iterator begin() const
Definition: LoopInfo.h:132
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:52
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:109
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:368
iterator end() const
Definition: LoopInfo.h:133
Represent the analysis usage information of a pass.
const SCEV * getMaxBackedgeTakenCount(const Loop *L)
Similar to getBackedgeTakenCount, except return the least SCEV value that is known never to be less t...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
void markAsRemoved(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition: LoopInfo.cpp:613
static BasicBlock * preheader(DominatorTree *DT, Loop *L)
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfo.cpp:344
loop deletion
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfo.cpp:358
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:425
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
Definition: LoopInfo.cpp:65
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
Definition: LoopInfo.cpp:174
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Pass * createLoopDeletionPass()
std::vector< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:140
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:464
block_iterator block_end() const
Definition: LoopInfo.h:142
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...
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:368
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
Definition: LoopUtils.cpp:938
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
block_iterator block_begin() const
Definition: LoopInfo.h:141
A container for analyses that lazily runs them and caches their results.
loop Delete dead false