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