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