1 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements LoopPass and LPPassManager. All loop optimization
10 // and transformation passes are derived from LoopPass. LPPassManager is
11 // responsible for managing LoopPasses.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/LoopPass.h"
16 #include "llvm/Analysis/LoopAnalysisManager.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/IRPrintingPasses.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/OptBisect.h"
22 #include "llvm/IR/PassManager.h"
23 #include "llvm/IR/PassTimingInfo.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/TimeProfiler.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "loop-pass-manager"
33 
34 namespace {
35 
36 /// PrintLoopPass - Print a Function corresponding to a Loop.
37 ///
38 class PrintLoopPassWrapper : public LoopPass {
39   raw_ostream &OS;
40   std::string Banner;
41 
42 public:
43   static char ID;
44   PrintLoopPassWrapper() : LoopPass(ID), OS(dbgs()) {}
45   PrintLoopPassWrapper(raw_ostream &OS, const std::string &Banner)
46       : LoopPass(ID), OS(OS), Banner(Banner) {}
47 
48   void getAnalysisUsage(AnalysisUsage &AU) const override {
49     AU.setPreservesAll();
50   }
51 
52   bool runOnLoop(Loop *L, LPPassManager &) override {
53     auto BBI = llvm::find_if(L->blocks(), [](BasicBlock *BB) { return BB; });
54     if (BBI != L->blocks().end() &&
55         isFunctionInPrintList((*BBI)->getParent()->getName())) {
56       printLoop(*L, OS, Banner);
57     }
58     return false;
59   }
60 
61   StringRef getPassName() const override { return "Print Loop IR"; }
62 };
63 
64 char PrintLoopPassWrapper::ID = 0;
65 }
66 
67 //===----------------------------------------------------------------------===//
68 // LPPassManager
69 //
70 
71 char LPPassManager::ID = 0;
72 
73 LPPassManager::LPPassManager()
74   : FunctionPass(ID), PMDataManager() {
75   LI = nullptr;
76   CurrentLoop = nullptr;
77 }
78 
79 // Insert loop into loop nest (LoopInfo) and loop queue (LQ).
80 void LPPassManager::addLoop(Loop &L) {
81   if (!L.getParentLoop()) {
82     // This is the top level loop.
83     LQ.push_front(&L);
84     return;
85   }
86 
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       return;
94     }
95   }
96 }
97 
98 // Recurse through all subloops and all loops  into LQ.
99 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
100   LQ.push_back(L);
101   for (Loop *I : reverse(*L))
102     addLoopIntoQueue(I, LQ);
103 }
104 
105 /// Pass Manager itself does not invalidate any analysis info.
106 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
107   // LPPassManager needs LoopInfo. In the long term LoopInfo class will
108   // become part of LPPassManager.
109   Info.addRequired<LoopInfoWrapperPass>();
110   Info.addRequired<DominatorTreeWrapperPass>();
111   Info.setPreservesAll();
112 }
113 
114 void LPPassManager::markLoopAsDeleted(Loop &L) {
115   assert((&L == CurrentLoop || CurrentLoop->contains(&L)) &&
116          "Must not delete loop outside the current loop tree!");
117   // If this loop appears elsewhere within the queue, we also need to remove it
118   // there. However, we have to be careful to not remove the back of the queue
119   // as that is assumed to match the current loop.
120   assert(LQ.back() == CurrentLoop && "Loop queue back isn't the current loop!");
121   LQ.erase(std::remove(LQ.begin(), LQ.end(), &L), LQ.end());
122 
123   if (&L == CurrentLoop) {
124     CurrentLoopDeleted = true;
125     // Add this loop back onto the back of the queue to preserve our invariants.
126     LQ.push_back(&L);
127   }
128 }
129 
130 /// run - Execute all of the passes scheduled for execution.  Keep track of
131 /// whether any of the passes modifies the function, and if so, return true.
132 bool LPPassManager::runOnFunction(Function &F) {
133   auto &LIWP = getAnalysis<LoopInfoWrapperPass>();
134   LI = &LIWP.getLoopInfo();
135   Module &M = *F.getParent();
136 #if 0
137   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
138 #endif
139   bool Changed = false;
140 
141   // Collect inherited analysis from Module level pass manager.
142   populateInheritedAnalysis(TPM->activeStack);
143 
144   // Populate the loop queue in reverse program order. There is no clear need to
145   // process sibling loops in either forward or reverse order. There may be some
146   // advantage in deleting uses in a later loop before optimizing the
147   // definitions in an earlier loop. If we find a clear reason to process in
148   // forward order, then a forward variant of LoopPassManager should be created.
149   //
150   // Note that LoopInfo::iterator visits loops in reverse program
151   // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
152   // reverses the order a third time by popping from the back.
153   for (Loop *L : reverse(*LI))
154     addLoopIntoQueue(L, LQ);
155 
156   if (LQ.empty()) // No loops, skip calling finalizers
157     return false;
158 
159   // Initialization
160   for (Loop *L : LQ) {
161     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
162       LoopPass *P = getContainedPass(Index);
163       Changed |= P->doInitialization(L, *this);
164     }
165   }
166 
167   // Walk Loops
168   unsigned InstrCount, FunctionSize = 0;
169   StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
170   bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
171   // Collect the initial size of the module and the function we're looking at.
172   if (EmitICRemark) {
173     InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
174     FunctionSize = F.getInstructionCount();
175   }
176   while (!LQ.empty()) {
177     CurrentLoopDeleted = false;
178     CurrentLoop = LQ.back();
179 
180     // Run all passes on the current Loop.
181     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
182       LoopPass *P = getContainedPass(Index);
183 
184       llvm::TimeTraceScope LoopPassScope("RunLoopPass", P->getPassName());
185 
186       dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
187                    CurrentLoop->getHeader()->getName());
188       dumpRequiredSet(P);
189 
190       initializeAnalysisImpl(P);
191 
192       bool LocalChanged = false;
193       {
194         PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
195         TimeRegion PassTimer(getPassTimer(P));
196         LocalChanged = P->runOnLoop(CurrentLoop, *this);
197         Changed |= LocalChanged;
198         if (EmitICRemark) {
199           unsigned NewSize = F.getInstructionCount();
200           // Update the size of the function, emit a remark, and update the
201           // size of the module.
202           if (NewSize != FunctionSize) {
203             int64_t Delta = static_cast<int64_t>(NewSize) -
204                             static_cast<int64_t>(FunctionSize);
205             emitInstrCountChangedRemark(P, M, Delta, InstrCount,
206                                         FunctionToInstrCount, &F);
207             InstrCount = static_cast<int64_t>(InstrCount) + Delta;
208             FunctionSize = NewSize;
209           }
210         }
211       }
212 
213       if (LocalChanged)
214         dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
215                      CurrentLoopDeleted ? "<deleted loop>"
216                                         : CurrentLoop->getName());
217       dumpPreservedSet(P);
218 
219       if (!CurrentLoopDeleted) {
220         // Manually check that this loop is still healthy. This is done
221         // instead of relying on LoopInfo::verifyLoop since LoopInfo
222         // is a function pass and it's really expensive to verify every
223         // loop in the function every time. That level of checking can be
224         // enabled with the -verify-loop-info option.
225         {
226           TimeRegion PassTimer(getPassTimer(&LIWP));
227           CurrentLoop->verifyLoop();
228         }
229         // Here we apply same reasoning as in the above case. Only difference
230         // is that LPPassManager might run passes which do not require LCSSA
231         // form (LoopPassPrinter for example). We should skip verification for
232         // such passes.
233         // FIXME: Loop-sink currently break LCSSA. Fix it and reenable the
234         // verification!
235 #if 0
236         if (mustPreserveAnalysisID(LCSSAVerificationPass::ID))
237           assert(CurrentLoop->isRecursivelyLCSSAForm(*DT, *LI));
238 #endif
239 
240         // Then call the regular verifyAnalysis functions.
241         verifyPreservedAnalysis(P);
242 
243         F.getContext().yield();
244       }
245 
246       removeNotPreservedAnalysis(P);
247       recordAvailableAnalysis(P);
248       removeDeadPasses(P,
249                        CurrentLoopDeleted ? "<deleted>"
250                                           : CurrentLoop->getHeader()->getName(),
251                        ON_LOOP_MSG);
252 
253       if (CurrentLoopDeleted)
254         // Do not run other passes on this loop.
255         break;
256     }
257 
258     // If the loop was deleted, release all the loop passes. This frees up
259     // some memory, and avoids trouble with the pass manager trying to call
260     // verifyAnalysis on them.
261     if (CurrentLoopDeleted) {
262       for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
263         Pass *P = getContainedPass(Index);
264         freePass(P, "<deleted>", ON_LOOP_MSG);
265       }
266     }
267 
268     // Pop the loop from queue after running all passes.
269     LQ.pop_back();
270   }
271 
272   // Finalization
273   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
274     LoopPass *P = getContainedPass(Index);
275     Changed |= P->doFinalization();
276   }
277 
278   return Changed;
279 }
280 
281 /// Print passes managed by this manager
282 void LPPassManager::dumpPassStructure(unsigned Offset) {
283   errs().indent(Offset*2) << "Loop Pass Manager\n";
284   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
285     Pass *P = getContainedPass(Index);
286     P->dumpPassStructure(Offset + 1);
287     dumpLastUses(P, Offset+1);
288   }
289 }
290 
291 
292 //===----------------------------------------------------------------------===//
293 // LoopPass
294 
295 Pass *LoopPass::createPrinterPass(raw_ostream &O,
296                                   const std::string &Banner) const {
297   return new PrintLoopPassWrapper(O, Banner);
298 }
299 
300 // Check if this pass is suitable for the current LPPassManager, if
301 // available. This pass P is not suitable for a LPPassManager if P
302 // is not preserving higher level analysis info used by other
303 // LPPassManager passes. In such case, pop LPPassManager from the
304 // stack. This will force assignPassManager() to create new
305 // LPPassManger as expected.
306 void LoopPass::preparePassManager(PMStack &PMS) {
307 
308   // Find LPPassManager
309   while (!PMS.empty() &&
310          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
311     PMS.pop();
312 
313   // If this pass is destroying high level information that is used
314   // by other passes that are managed by LPM then do not insert
315   // this pass in current LPM. Use new LPPassManager.
316   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
317       !PMS.top()->preserveHigherLevelAnalysis(this))
318     PMS.pop();
319 }
320 
321 /// Assign pass manager to manage this pass.
322 void LoopPass::assignPassManager(PMStack &PMS,
323                                  PassManagerType PreferredType) {
324   // Find LPPassManager
325   while (!PMS.empty() &&
326          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
327     PMS.pop();
328 
329   LPPassManager *LPPM;
330   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
331     LPPM = (LPPassManager*)PMS.top();
332   else {
333     // Create new Loop Pass Manager if it does not exist.
334     assert (!PMS.empty() && "Unable to create Loop Pass Manager");
335     PMDataManager *PMD = PMS.top();
336 
337     // [1] Create new Loop Pass Manager
338     LPPM = new LPPassManager();
339     LPPM->populateInheritedAnalysis(PMS);
340 
341     // [2] Set up new manager's top level manager
342     PMTopLevelManager *TPM = PMD->getTopLevelManager();
343     TPM->addIndirectPassManager(LPPM);
344 
345     // [3] Assign manager to manage this new manager. This may create
346     // and push new managers into PMS
347     Pass *P = LPPM->getAsPass();
348     TPM->schedulePass(P);
349 
350     // [4] Push new manager into PMS
351     PMS.push(LPPM);
352   }
353 
354   LPPM->add(this);
355 }
356 
357 static std::string getDescription(const Loop &L) {
358   return "loop";
359 }
360 
361 bool LoopPass::skipLoop(const Loop *L) const {
362   const Function *F = L->getHeader()->getParent();
363   if (!F)
364     return false;
365   // Check the opt bisect limit.
366   OptPassGate &Gate = F->getContext().getOptPassGate();
367   if (Gate.isEnabled() && !Gate.shouldRunPass(this, getDescription(*L)))
368     return true;
369   // Check for the OptimizeNone attribute.
370   if (F->hasOptNone()) {
371     // FIXME: Report this to dbgs() only once per function.
372     LLVM_DEBUG(dbgs() << "Skipping pass '" << getPassName() << "' in function "
373                       << F->getName() << "\n");
374     // FIXME: Delete loop from pass manager's queue?
375     return true;
376   }
377   return false;
378 }
379 
380 LCSSAVerificationPass::LCSSAVerificationPass() : FunctionPass(ID) {
381   initializeLCSSAVerificationPassPass(*PassRegistry::getPassRegistry());
382 }
383 
384 char LCSSAVerificationPass::ID = 0;
385 INITIALIZE_PASS(LCSSAVerificationPass, "lcssa-verification", "LCSSA Verifier",
386                 false, false)
387