1 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
28 #define DEBUG_TYPE "loop-pass-manager"
32 /// PrintLoopPass - Print a Function corresponding to a Loop.
34 class PrintLoopPassWrapper : public LoopPass {
40 PrintLoopPassWrapper() : LoopPass(ID), OS(dbgs()) {}
41 PrintLoopPassWrapper(raw_ostream &OS, const std::string &Banner)
42 : LoopPass(ID), OS(OS), Banner(Banner) {}
44 void getAnalysisUsage(AnalysisUsage &AU) const override {
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);
59 char PrintLoopPassWrapper::ID = 0;
62 //===----------------------------------------------------------------------===//
66 char LPPassManager::ID = 0;
68 LPPassManager::LPPassManager()
69 : FunctionPass(ID), PMDataManager() {
71 CurrentLoop = nullptr;
74 // Inset loop into loop nest (LoopInfo) and loop queue (LQ).
75 Loop &LPPassManager::addLoop(Loop *ParentLoop) {
76 // Create a new loop. LI will take ownership.
79 // Insert into the loop nest and the loop queue.
81 // This is the top level loop.
82 LI->addTopLevelLoop(L);
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.
100 /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
102 void LPPassManager::cloneBasicBlockSimpleAnalysis(BasicBlock *From,
103 BasicBlock *To, Loop *L) {
104 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
105 LoopPass *LP = getContainedPass(Index);
106 LP->cloneBasicBlockAnalysis(From, To, L);
110 /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes.
111 void LPPassManager::deleteSimpleAnalysisValue(Value *V, Loop *L) {
112 if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
113 for (Instruction &I : *BB) {
114 deleteSimpleAnalysisValue(&I, L);
117 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
118 LoopPass *LP = getContainedPass(Index);
119 LP->deleteAnalysisValue(V, L);
123 /// Invoke deleteAnalysisLoop hook for all passes.
124 void LPPassManager::deleteSimpleAnalysisLoop(Loop *L) {
125 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
126 LoopPass *LP = getContainedPass(Index);
127 LP->deleteAnalysisLoop(L);
132 // Recurse through all subloops and all loops into LQ.
133 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
135 for (Loop *I : reverse(*L))
136 addLoopIntoQueue(I, LQ);
139 /// Pass Manager itself does not invalidate any analysis info.
140 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
141 // LPPassManager needs LoopInfo. In the long term LoopInfo class will
142 // become part of LPPassManager.
143 Info.addRequired<LoopInfoWrapperPass>();
144 Info.addRequired<DominatorTreeWrapperPass>();
145 Info.setPreservesAll();
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.
150 bool LPPassManager::runOnFunction(Function &F) {
151 auto &LIWP = getAnalysis<LoopInfoWrapperPass>();
152 LI = &LIWP.getLoopInfo();
153 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
154 bool Changed = false;
156 // Collect inherited analysis from Module level pass manager.
157 populateInheritedAnalysis(TPM->activeStack);
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.
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);
171 if (LQ.empty()) // No loops, skip calling finalizers
176 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
177 LoopPass *P = getContainedPass(Index);
178 Changed |= P->doInitialization(L, *this);
183 while (!LQ.empty()) {
184 bool LoopWasDeleted = false;
185 CurrentLoop = LQ.back();
187 // Run all passes on the current Loop.
188 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
189 LoopPass *P = getContainedPass(Index);
191 dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
192 CurrentLoop->getHeader()->getName());
195 initializeAnalysisImpl(P);
198 PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
199 TimeRegion PassTimer(getPassTimer(P));
201 Changed |= P->runOnLoop(CurrentLoop, *this);
203 LoopWasDeleted = CurrentLoop->isInvalid();
206 dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
207 LoopWasDeleted ? "<deleted>"
208 : CurrentLoop->getHeader()->getName());
211 if (LoopWasDeleted) {
212 // Notify passes that the loop is being deleted.
213 deleteSimpleAnalysisLoop(CurrentLoop);
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.
221 TimeRegion PassTimer(getPassTimer(&LIWP));
222 CurrentLoop->verifyLoop();
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
228 if (mustPreserveAnalysisID(LCSSAVerificationPass::ID))
229 CurrentLoop->isRecursivelyLCSSAForm(*DT, *LI);
231 // Then call the regular verifyAnalysis functions.
232 verifyPreservedAnalysis(P);
234 F.getContext().yield();
237 removeNotPreservedAnalysis(P);
238 recordAvailableAnalysis(P);
239 removeDeadPasses(P, LoopWasDeleted ? "<deleted>"
240 : CurrentLoop->getHeader()->getName(),
244 // Do not run other passes on this loop.
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);
258 // Pop the loop from queue after running all passes.
263 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
264 LoopPass *P = getContainedPass(Index);
265 Changed |= P->doFinalization();
271 /// Print passes managed by this manager
272 void LPPassManager::dumpPassStructure(unsigned Offset) {
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);
282 //===----------------------------------------------------------------------===//
285 Pass *LoopPass::createPrinterPass(raw_ostream &O,
286 const std::string &Banner) const {
287 return new PrintLoopPassWrapper(O, Banner);
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.
296 void LoopPass::preparePassManager(PMStack &PMS) {
298 // Find LPPassManager
299 while (!PMS.empty() &&
300 PMS.top()->getPassManagerType() > PMT_LoopPassManager)
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))
311 /// Assign pass manager to manage this pass.
312 void LoopPass::assignPassManager(PMStack &PMS,
313 PassManagerType PreferredType) {
314 // Find LPPassManager
315 while (!PMS.empty() &&
316 PMS.top()->getPassManagerType() > PMT_LoopPassManager)
320 if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
321 LPPM = (LPPassManager*)PMS.top();
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();
327 // [1] Create new Loop Pass Manager
328 LPPM = new LPPassManager();
329 LPPM->populateInheritedAnalysis(PMS);
331 // [2] Set up new manager's top level manager
332 PMTopLevelManager *TPM = PMD->getTopLevelManager();
333 TPM->addIndirectPassManager(LPPM);
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);
340 // [4] Push new manager into PMS
347 bool LoopPass::skipLoop(const Loop *L) const {
348 const Function *F = L->getHeader()->getParent();
351 // Check the opt bisect limit.
352 LLVMContext &Context = F->getContext();
353 if (!Context.getOptBisect().shouldRunPass(this, *L))
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?
366 char LCSSAVerificationPass::ID = 0;
367 INITIALIZE_PASS(LCSSAVerificationPass, "lcssa-verification", "LCSSA Verifier",