LLVM  4.0.0
LoopPass.cpp
Go to the documentation of this file.
1 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
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 LoopPass and LPPassManager. All loop optimization
11 // and transformation passes are derived from LoopPass. LPPassManager is
12 // responsible for managing LoopPasses.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/OptBisect.h"
22 #include "llvm/IR/PassManager.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Timer.h"
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "loop-pass-manager"
29 
30 namespace {
31 
32 /// PrintLoopPass - Print a Function corresponding to a Loop.
33 ///
34 class PrintLoopPassWrapper : public LoopPass {
35  raw_ostream &OS;
36  std::string Banner;
37 
38 public:
39  static char ID;
40  PrintLoopPassWrapper() : LoopPass(ID), OS(dbgs()) {}
41  PrintLoopPassWrapper(raw_ostream &OS, const std::string &Banner)
42  : LoopPass(ID), OS(OS), Banner(Banner) {}
43 
44  void getAnalysisUsage(AnalysisUsage &AU) const override {
45  AU.setPreservesAll();
46  }
47 
48  bool runOnLoop(Loop *L, LPPassManager &) override {
49  auto BBI = find_if(L->blocks().begin(), L->blocks().end(),
50  [](BasicBlock *BB) { return BB; });
51  if (BBI != L->blocks().end() &&
52  isFunctionInPrintList((*BBI)->getParent()->getName())) {
53  printLoop(*L, OS, Banner);
54  }
55  return false;
56  }
57 };
58 
60 }
61 
62 //===----------------------------------------------------------------------===//
63 // LPPassManager
64 //
65 
66 char LPPassManager::ID = 0;
67 
70  LI = nullptr;
71  CurrentLoop = nullptr;
72 }
73 
74 // Inset loop into loop nest (LoopInfo) and loop queue (LQ).
76  // Create a new loop. LI will take ownership.
77  Loop *L = new Loop();
78 
79  // Insert into the loop nest and the loop queue.
80  if (!ParentLoop) {
81  // This is the top level loop.
82  LI->addTopLevelLoop(L);
83  LQ.push_front(L);
84  return *L;
85  }
86 
87  ParentLoop->addChildLoop(L);
88  // Insert L into the loop queue after the parent loop.
89  for (auto I = LQ.begin(), E = LQ.end(); I != E; ++I) {
90  if (*I == L->getParentLoop()) {
91  // deque does not support insert after.
92  ++I;
93  LQ.insert(I, 1, L);
94  break;
95  }
96  }
97  return *L;
98 }
99 
100 /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
101 /// all loop passes.
103  BasicBlock *To, Loop *L) {
104  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
105  LoopPass *LP = getContainedPass(Index);
106  LP->cloneBasicBlockAnalysis(From, To, L);
107  }
108 }
109 
110 /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes.
112  if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
113  for (Instruction &I : *BB) {
115  }
116  }
117  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
118  LoopPass *LP = getContainedPass(Index);
119  LP->deleteAnalysisValue(V, L);
120  }
121 }
122 
123 /// Invoke deleteAnalysisLoop hook for all passes.
125  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
126  LoopPass *LP = getContainedPass(Index);
127  LP->deleteAnalysisLoop(L);
128  }
129 }
130 
131 
132 // Recurse through all subloops and all loops into LQ.
133 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
134  LQ.push_back(L);
135  for (Loop *I : reverse(*L))
136  addLoopIntoQueue(I, LQ);
137 }
138 
139 /// Pass Manager itself does not invalidate any analysis info.
141  // LPPassManager needs LoopInfo. In the long term LoopInfo class will
142  // become part of LPPassManager.
145  Info.setPreservesAll();
146 }
147 
148 /// run - Execute all of the passes scheduled for execution. Keep track of
149 /// whether any of the passes modifies the function, and if so, return true.
151  auto &LIWP = getAnalysis<LoopInfoWrapperPass>();
152  LI = &LIWP.getLoopInfo();
153  DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
154  bool Changed = false;
155 
156  // Collect inherited analysis from Module level pass manager.
158 
159  // Populate the loop queue in reverse program order. There is no clear need to
160  // process sibling loops in either forward or reverse order. There may be some
161  // advantage in deleting uses in a later loop before optimizing the
162  // definitions in an earlier loop. If we find a clear reason to process in
163  // forward order, then a forward variant of LoopPassManager should be created.
164  //
165  // Note that LoopInfo::iterator visits loops in reverse program
166  // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
167  // reverses the order a third time by popping from the back.
168  for (Loop *L : reverse(*LI))
169  addLoopIntoQueue(L, LQ);
170 
171  if (LQ.empty()) // No loops, skip calling finalizers
172  return false;
173 
174  // Initialization
175  for (Loop *L : LQ) {
176  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
177  LoopPass *P = getContainedPass(Index);
178  Changed |= P->doInitialization(L, *this);
179  }
180  }
181 
182  // Walk Loops
183  while (!LQ.empty()) {
184  bool LoopWasDeleted = false;
185  CurrentLoop = LQ.back();
186 
187  // Run all passes on the current Loop.
188  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
189  LoopPass *P = getContainedPass(Index);
190 
192  CurrentLoop->getHeader()->getName());
193  dumpRequiredSet(P);
194 
196 
197  {
198  PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
199  TimeRegion PassTimer(getPassTimer(P));
200 
201  Changed |= P->runOnLoop(CurrentLoop, *this);
202  }
203  LoopWasDeleted = CurrentLoop->isInvalid();
204 
205  if (Changed)
207  LoopWasDeleted ? "<deleted>"
208  : CurrentLoop->getHeader()->getName());
209  dumpPreservedSet(P);
210 
211  if (LoopWasDeleted) {
212  // Notify passes that the loop is being deleted.
213  deleteSimpleAnalysisLoop(CurrentLoop);
214  } else {
215  // Manually check that this loop is still healthy. This is done
216  // instead of relying on LoopInfo::verifyLoop since LoopInfo
217  // is a function pass and it's really expensive to verify every
218  // loop in the function every time. That level of checking can be
219  // enabled with the -verify-loop-info option.
220  {
221  TimeRegion PassTimer(getPassTimer(&LIWP));
222  CurrentLoop->verifyLoop();
223  }
224  // Here we apply same reasoning as in the above case. Only difference
225  // is that LPPassManager might run passes which do not require LCSSA
226  // form (LoopPassPrinter for example). We should skip verification for
227  // such passes.
229  CurrentLoop->isRecursivelyLCSSAForm(*DT, *LI);
230 
231  // Then call the regular verifyAnalysis functions.
233 
234  F.getContext().yield();
235  }
236 
239  removeDeadPasses(P, LoopWasDeleted ? "<deleted>"
240  : CurrentLoop->getHeader()->getName(),
241  ON_LOOP_MSG);
242 
243  if (LoopWasDeleted)
244  // Do not run other passes on this loop.
245  break;
246  }
247 
248  // If the loop was deleted, release all the loop passes. This frees up
249  // some memory, and avoids trouble with the pass manager trying to call
250  // verifyAnalysis on them.
251  if (LoopWasDeleted) {
252  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
253  Pass *P = getContainedPass(Index);
254  freePass(P, "<deleted>", ON_LOOP_MSG);
255  }
256  }
257 
258  // Pop the loop from queue after running all passes.
259  LQ.pop_back();
260  }
261 
262  // Finalization
263  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
264  LoopPass *P = getContainedPass(Index);
265  Changed |= P->doFinalization();
266  }
267 
268  return Changed;
269 }
270 
271 /// Print passes managed by this manager
273  errs().indent(Offset*2) << "Loop Pass Manager\n";
274  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
275  Pass *P = getContainedPass(Index);
276  P->dumpPassStructure(Offset + 1);
277  dumpLastUses(P, Offset+1);
278  }
279 }
280 
281 
282 //===----------------------------------------------------------------------===//
283 // LoopPass
284 
286  const std::string &Banner) const {
287  return new PrintLoopPassWrapper(O, Banner);
288 }
289 
290 // Check if this pass is suitable for the current LPPassManager, if
291 // available. This pass P is not suitable for a LPPassManager if P
292 // is not preserving higher level analysis info used by other
293 // LPPassManager passes. In such case, pop LPPassManager from the
294 // stack. This will force assignPassManager() to create new
295 // LPPassManger as expected.
297 
298  // Find LPPassManager
299  while (!PMS.empty() &&
301  PMS.pop();
302 
303  // If this pass is destroying high level information that is used
304  // by other passes that are managed by LPM then do not insert
305  // this pass in current LPM. Use new LPPassManager.
306  if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
307  !PMS.top()->preserveHigherLevelAnalysis(this))
308  PMS.pop();
309 }
310 
311 /// Assign pass manager to manage this pass.
313  PassManagerType PreferredType) {
314  // Find LPPassManager
315  while (!PMS.empty() &&
317  PMS.pop();
318 
319  LPPassManager *LPPM;
321  LPPM = (LPPassManager*)PMS.top();
322  else {
323  // Create new Loop Pass Manager if it does not exist.
324  assert (!PMS.empty() && "Unable to create Loop Pass Manager");
325  PMDataManager *PMD = PMS.top();
326 
327  // [1] Create new Loop Pass Manager
328  LPPM = new LPPassManager();
329  LPPM->populateInheritedAnalysis(PMS);
330 
331  // [2] Set up new manager's top level manager
332  PMTopLevelManager *TPM = PMD->getTopLevelManager();
333  TPM->addIndirectPassManager(LPPM);
334 
335  // [3] Assign manager to manage this new manager. This may create
336  // and push new managers into PMS
337  Pass *P = LPPM->getAsPass();
338  TPM->schedulePass(P);
339 
340  // [4] Push new manager into PMS
341  PMS.push(LPPM);
342  }
343 
344  LPPM->add(this);
345 }
346 
347 bool LoopPass::skipLoop(const Loop *L) const {
348  const Function *F = L->getHeader()->getParent();
349  if (!F)
350  return false;
351  // Check the opt bisect limit.
353  if (!Context.getOptBisect().shouldRunPass(this, *L))
354  return true;
355  // Check for the OptimizeNone attribute.
356  if (F->hasFnAttribute(Attribute::OptimizeNone)) {
357  // FIXME: Report this to dbgs() only once per function.
358  DEBUG(dbgs() << "Skipping pass '" << getPassName()
359  << "' in function " << F->getName() << "\n");
360  // FIXME: Delete loop from pass manager's queue?
361  return true;
362  }
363  return false;
364 }
365 
367 INITIALIZE_PASS(LCSSAVerificationPass, "lcssa-verification", "LCSSA Verifier",
368  false, false)
369 
MachineLoop * L
PMTopLevelManager * TPM
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:81
bool preserveHigherLevelAnalysis(Pass *P)
PassManagerType
Different types of internal pass managers.
Definition: Pass.h:54
bool shouldRunPass(const Pass *P, const UnitT &U)
Checks the bisect limit to determine if the specified pass should run.
Definition: OptBisect.cpp:96
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:226
LLVMContext & Context
void dumpLastUses(Pass *P, unsigned Offset) const
virtual void dumpPassStructure(unsigned Offset=0)
Definition: Pass.cpp:59
virtual void deleteAnalysisLoop(Loop *L)
Delete analysis info associated with Loop L.
Definition: LoopPass.h:88
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
void assignPassManager(PMStack &PMS, PassManagerType PMT) override
Assign pass manager to manage this pass.
Definition: LoopPass.cpp:312
void dumpRequiredSet(const Pass *P) const
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:67
LoopT * getParentLoop() const
Definition: LoopInfo.h:103
void yield()
Calls the yield callback (if applicable).
Loop & addLoop(Loop *ParentLoop)
Definition: LoopPass.cpp:75
void dumpPassInfo(Pass *P, enum PassDebuggingString S1, enum PassDebuggingString S2, StringRef Msg)
BlockT * getHeader() const
Definition: LoopInfo.h:102
virtual PassManagerType getPassManagerType() const
PMTopLevelManager manages LastUser info and collects common APIs used by top level pass managers...
Timer * getPassTimer(Pass *)
If TimingInfo is enabled then start pass timer.
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
The TimeRegion class is used as a helper class to call the startTimer() and stopTimer() methods of th...
Definition: Timer.h:140
void schedulePass(Pass *P)
Schedule pass P for execution.
AnalysisUsage & addRequired()
void freePass(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove P.
void deleteSimpleAnalysisLoop(Loop *L)
Invoke deleteAnalysisLoop hook for all passes that implement simple analysis interface.
Definition: LoopPass.cpp:124
void verifyPreservedAnalysis(Pass *P)
verifyPreservedAnalysis – Verify analysis presreved by pass P.
bool mustPreserveAnalysisID(char &AID) const
mustPreserveAnalysisID - This method serves the same function as getAnalysisIfAvailable, but works if you just have an AnalysisID.
Definition: Pass.cpp:54
void populateInheritedAnalysis(PMStack &PMS)
PMStack - This class implements a stack data structure of PMDataManager pointers. ...
void initializeAnalysisImpl(Pass *P)
All Required analyses should be available to the pass as it runs! Here we fill in the AnalysisImpls m...
PassManagerPrettyStackEntry - This is used to print informative information about what pass is runnin...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:241
Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const override
getPrinterPass - Get a pass to print the function corresponding to a Loop.
Definition: LoopPass.cpp:285
#define F(x, y, z)
Definition: MD5.cpp:51
void add(Pass *P, bool ProcessAnalysis=true)
Add pass P into the PassVector.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Definition: LoopInfo.h:279
unsigned getNumContainedPasses() const
This header provides classes for managing per-loop analyses.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:96
bool skipLoop(const Loop *L) const
Optional passes call this function to check whether the pass should be skipped.
Definition: LoopPass.cpp:347
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:143
void verifyLoop() const
Verify loop structure.
Definition: LoopInfoImpl.h:229
virtual bool doInitialization(Loop *L, LPPassManager &LPM)
Definition: LoopPass.h:46
#define P(N)
void dumpPreservedSet(const Pass *P) const
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:48
virtual bool doFinalization()
Definition: LoopPass.h:52
void addIndirectPassManager(PMDataManager *Manager)
void getAnalysisUsage(AnalysisUsage &Info) const override
Pass Manager itself does not invalidate any analysis info.
Definition: LoopPass.cpp:140
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
Definition: LoopInfo.cpp:181
Represent the analysis usage information of a pass.
uint32_t Offset
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
static char ID
Definition: LoopPass.h:99
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:36
void deleteSimpleAnalysisValue(Value *V, Loop *L)
deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes that implement simple anal...
Definition: LoopPass.cpp:111
bool empty() const
LPPassManager.
Definition: Pass.h:59
void recordAvailableAnalysis(Pass *P)
Augment AvailableAnalysis by adding analysis made available by pass P.
void removeNotPreservedAnalysis(Pass *P)
Remove Analysis that is not preserved by the pass.
void removeDeadPasses(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove dead passes used by P.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
Definition: LoopInfo.h:629
This file declares the interface for bisecting optimizations.
bool isFunctionInPrintList(StringRef FunctionName)
isFunctionInPrintList - returns true if a function should be printed via
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
PMDataManager * top() const
void setPreservesAll()
Set by analyses that do not transform their input at all.
void dumpPassStructure(unsigned Offset) override
Print passes managed by this manager.
Definition: LoopPass.cpp:272
void preparePassManager(PMStack &PMS) override
Check if available pass managers are suitable for this pass or not.
Definition: LoopPass.cpp:296
virtual bool runOnLoop(Loop *L, LPPassManager &LPM)=0
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:226
void cloneBasicBlockSimpleAnalysis(BasicBlock *From, BasicBlock *To, Loop *L)
SimpleAnalysis - Provides simple interface to update analysis info maintained by various passes...
Definition: LoopPass.cpp:102
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:368
OptBisect & getOptBisect()
Access the object which manages optimization bisection for failure analysis.
#define I(x, y, z)
Definition: MD5.cpp:54
LoopPass * getContainedPass(unsigned N)
Definition: LoopPass.h:118
void push(PMDataManager *PM)
PMDataManager provides the common place to manage the analysis data used by pass managers.
This file defines passes to print out IR in various granularities.
virtual void cloneBasicBlockAnalysis(BasicBlock *F, BasicBlock *T, Loop *L)
SimpleAnalysis - Provides simple interface to update analysis info maintained by various passes...
Definition: LoopPass.h:80
bool isInvalid()
Return true if this loop is no longer valid.
Definition: LoopInfo.h:156
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
virtual void deleteAnalysisValue(Value *V, Loop *L)
deleteAnalysisValue - Delete analysis info associated with value V.
Definition: LoopPass.h:83
bool runOnFunction(Function &F) override
run - Execute all of the passes scheduled for execution.
Definition: LoopPass.cpp:150
static void addLoopIntoQueue(Loop *L, std::deque< Loop * > &LQ)
Definition: LoopPass.cpp:133
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:100
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:831
Pass * getAsPass() override
Definition: LoopPass.h:113
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:217
This header defines various interfaces for pass management in LLVM.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:764
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
Definition: LoopInfo.cpp:692