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"
17 #include "llvm/Analysis/LoopAnalysisManager.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/IRPrintingPasses.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"
25 #include "llvm/Support/raw_ostream.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   StringRef getPassName() const override { return "Print Loop IR"; }
59 };
60 
61 char PrintLoopPassWrapper::ID = 0;
62 }
63 
64 //===----------------------------------------------------------------------===//
65 // LPPassManager
66 //
67 
68 char LPPassManager::ID = 0;
69 
70 LPPassManager::LPPassManager()
71   : FunctionPass(ID), PMDataManager() {
72   LI = nullptr;
73   CurrentLoop = nullptr;
74 }
75 
76 // Inset loop into loop nest (LoopInfo) and loop queue (LQ).
77 Loop &LPPassManager::addLoop(Loop *ParentLoop) {
78   // Create a new loop. LI will take ownership.
79   Loop *L = new Loop();
80 
81   // Insert into the loop nest and the loop queue.
82   if (!ParentLoop) {
83     // This is the top level loop.
84     LI->addTopLevelLoop(L);
85     LQ.push_front(L);
86     return *L;
87   }
88 
89   ParentLoop->addChildLoop(L);
90   // Insert L into the loop queue after the parent loop.
91   for (auto I = LQ.begin(), E = LQ.end(); I != E; ++I) {
92     if (*I == L->getParentLoop()) {
93       // deque does not support insert after.
94       ++I;
95       LQ.insert(I, 1, L);
96       break;
97     }
98   }
99   return *L;
100 }
101 
102 /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
103 /// all loop passes.
104 void LPPassManager::cloneBasicBlockSimpleAnalysis(BasicBlock *From,
105                                                   BasicBlock *To, Loop *L) {
106   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
107     LoopPass *LP = getContainedPass(Index);
108     LP->cloneBasicBlockAnalysis(From, To, L);
109   }
110 }
111 
112 /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes.
113 void LPPassManager::deleteSimpleAnalysisValue(Value *V, Loop *L) {
114   if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
115     for (Instruction &I : *BB) {
116       deleteSimpleAnalysisValue(&I, L);
117     }
118   }
119   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
120     LoopPass *LP = getContainedPass(Index);
121     LP->deleteAnalysisValue(V, L);
122   }
123 }
124 
125 /// Invoke deleteAnalysisLoop hook for all passes.
126 void LPPassManager::deleteSimpleAnalysisLoop(Loop *L) {
127   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
128     LoopPass *LP = getContainedPass(Index);
129     LP->deleteAnalysisLoop(L);
130   }
131 }
132 
133 
134 // Recurse through all subloops and all loops  into LQ.
135 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
136   LQ.push_back(L);
137   for (Loop *I : reverse(*L))
138     addLoopIntoQueue(I, LQ);
139 }
140 
141 /// Pass Manager itself does not invalidate any analysis info.
142 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
143   // LPPassManager needs LoopInfo. In the long term LoopInfo class will
144   // become part of LPPassManager.
145   Info.addRequired<LoopInfoWrapperPass>();
146   Info.addRequired<DominatorTreeWrapperPass>();
147   Info.setPreservesAll();
148 }
149 
150 /// run - Execute all of the passes scheduled for execution.  Keep track of
151 /// whether any of the passes modifies the function, and if so, return true.
152 bool LPPassManager::runOnFunction(Function &F) {
153   auto &LIWP = getAnalysis<LoopInfoWrapperPass>();
154   LI = &LIWP.getLoopInfo();
155   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
156   bool Changed = false;
157 
158   // Collect inherited analysis from Module level pass manager.
159   populateInheritedAnalysis(TPM->activeStack);
160 
161   // Populate the loop queue in reverse program order. There is no clear need to
162   // process sibling loops in either forward or reverse order. There may be some
163   // advantage in deleting uses in a later loop before optimizing the
164   // definitions in an earlier loop. If we find a clear reason to process in
165   // forward order, then a forward variant of LoopPassManager should be created.
166   //
167   // Note that LoopInfo::iterator visits loops in reverse program
168   // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
169   // reverses the order a third time by popping from the back.
170   for (Loop *L : reverse(*LI))
171     addLoopIntoQueue(L, LQ);
172 
173   if (LQ.empty()) // No loops, skip calling finalizers
174     return false;
175 
176   // Initialization
177   for (Loop *L : LQ) {
178     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
179       LoopPass *P = getContainedPass(Index);
180       Changed |= P->doInitialization(L, *this);
181     }
182   }
183 
184   // Walk Loops
185   while (!LQ.empty()) {
186     bool LoopWasDeleted = false;
187     CurrentLoop = LQ.back();
188 
189     // Run all passes on the current Loop.
190     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191       LoopPass *P = getContainedPass(Index);
192 
193       dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
194                    CurrentLoop->getHeader()->getName());
195       dumpRequiredSet(P);
196 
197       initializeAnalysisImpl(P);
198 
199       {
200         PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
201         TimeRegion PassTimer(getPassTimer(P));
202 
203         Changed |= P->runOnLoop(CurrentLoop, *this);
204       }
205       LoopWasDeleted = CurrentLoop->isInvalid();
206 
207       if (Changed)
208         dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
209                      LoopWasDeleted ? "<deleted>"
210                                     : CurrentLoop->getHeader()->getName());
211       dumpPreservedSet(P);
212 
213       if (LoopWasDeleted) {
214         // Notify passes that the loop is being deleted.
215         deleteSimpleAnalysisLoop(CurrentLoop);
216       } else {
217         // Manually check that this loop is still healthy. This is done
218         // instead of relying on LoopInfo::verifyLoop since LoopInfo
219         // is a function pass and it's really expensive to verify every
220         // loop in the function every time. That level of checking can be
221         // enabled with the -verify-loop-info option.
222         {
223           TimeRegion PassTimer(getPassTimer(&LIWP));
224           CurrentLoop->verifyLoop();
225         }
226         // Here we apply same reasoning as in the above case. Only difference
227         // is that LPPassManager might run passes which do not require LCSSA
228         // form (LoopPassPrinter for example). We should skip verification for
229         // such passes.
230         if (mustPreserveAnalysisID(LCSSAVerificationPass::ID))
231           CurrentLoop->isRecursivelyLCSSAForm(*DT, *LI);
232 
233         // Then call the regular verifyAnalysis functions.
234         verifyPreservedAnalysis(P);
235 
236         F.getContext().yield();
237       }
238 
239       removeNotPreservedAnalysis(P);
240       recordAvailableAnalysis(P);
241       removeDeadPasses(P, LoopWasDeleted ? "<deleted>"
242                                          : CurrentLoop->getHeader()->getName(),
243                        ON_LOOP_MSG);
244 
245       if (LoopWasDeleted)
246         // Do not run other passes on this loop.
247         break;
248     }
249 
250     // If the loop was deleted, release all the loop passes. This frees up
251     // some memory, and avoids trouble with the pass manager trying to call
252     // verifyAnalysis on them.
253     if (LoopWasDeleted) {
254       for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
255         Pass *P = getContainedPass(Index);
256         freePass(P, "<deleted>", ON_LOOP_MSG);
257       }
258     }
259 
260     // Pop the loop from queue after running all passes.
261     LQ.pop_back();
262   }
263 
264   // Finalization
265   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
266     LoopPass *P = getContainedPass(Index);
267     Changed |= P->doFinalization();
268   }
269 
270   return Changed;
271 }
272 
273 /// Print passes managed by this manager
274 void LPPassManager::dumpPassStructure(unsigned Offset) {
275   errs().indent(Offset*2) << "Loop Pass Manager\n";
276   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
277     Pass *P = getContainedPass(Index);
278     P->dumpPassStructure(Offset + 1);
279     dumpLastUses(P, Offset+1);
280   }
281 }
282 
283 
284 //===----------------------------------------------------------------------===//
285 // LoopPass
286 
287 Pass *LoopPass::createPrinterPass(raw_ostream &O,
288                                   const std::string &Banner) const {
289   return new PrintLoopPassWrapper(O, Banner);
290 }
291 
292 // Check if this pass is suitable for the current LPPassManager, if
293 // available. This pass P is not suitable for a LPPassManager if P
294 // is not preserving higher level analysis info used by other
295 // LPPassManager passes. In such case, pop LPPassManager from the
296 // stack. This will force assignPassManager() to create new
297 // LPPassManger as expected.
298 void LoopPass::preparePassManager(PMStack &PMS) {
299 
300   // Find LPPassManager
301   while (!PMS.empty() &&
302          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
303     PMS.pop();
304 
305   // If this pass is destroying high level information that is used
306   // by other passes that are managed by LPM then do not insert
307   // this pass in current LPM. Use new LPPassManager.
308   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
309       !PMS.top()->preserveHigherLevelAnalysis(this))
310     PMS.pop();
311 }
312 
313 /// Assign pass manager to manage this pass.
314 void LoopPass::assignPassManager(PMStack &PMS,
315                                  PassManagerType PreferredType) {
316   // Find LPPassManager
317   while (!PMS.empty() &&
318          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
319     PMS.pop();
320 
321   LPPassManager *LPPM;
322   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
323     LPPM = (LPPassManager*)PMS.top();
324   else {
325     // Create new Loop Pass Manager if it does not exist.
326     assert (!PMS.empty() && "Unable to create Loop Pass Manager");
327     PMDataManager *PMD = PMS.top();
328 
329     // [1] Create new Loop Pass Manager
330     LPPM = new LPPassManager();
331     LPPM->populateInheritedAnalysis(PMS);
332 
333     // [2] Set up new manager's top level manager
334     PMTopLevelManager *TPM = PMD->getTopLevelManager();
335     TPM->addIndirectPassManager(LPPM);
336 
337     // [3] Assign manager to manage this new manager. This may create
338     // and push new managers into PMS
339     Pass *P = LPPM->getAsPass();
340     TPM->schedulePass(P);
341 
342     // [4] Push new manager into PMS
343     PMS.push(LPPM);
344   }
345 
346   LPPM->add(this);
347 }
348 
349 bool LoopPass::skipLoop(const Loop *L) const {
350   const Function *F = L->getHeader()->getParent();
351   if (!F)
352     return false;
353   // Check the opt bisect limit.
354   LLVMContext &Context = F->getContext();
355   if (!Context.getOptBisect().shouldRunPass(this, *L))
356     return true;
357   // Check for the OptimizeNone attribute.
358   if (F->hasFnAttribute(Attribute::OptimizeNone)) {
359     // FIXME: Report this to dbgs() only once per function.
360     DEBUG(dbgs() << "Skipping pass '" << getPassName()
361           << "' in function " << F->getName() << "\n");
362     // FIXME: Delete loop from pass manager's queue?
363     return true;
364   }
365   return false;
366 }
367 
368 char LCSSAVerificationPass::ID = 0;
369 INITIALIZE_PASS(LCSSAVerificationPass, "lcssa-verification", "LCSSA Verifier",
370                 false, false)
371 
372