LLVM API Documentation

LoopPass.cpp
Go to the documentation of this file.
00001 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements LoopPass and LPPassManager. All loop optimization
00011 // and transformation passes are derived from LoopPass. LPPassManager is
00012 // responsible for managing LoopPasses.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Analysis/LoopPass.h"
00017 #include "llvm/IR/IRPrintingPasses.h"
00018 #include "llvm/IR/LLVMContext.h"
00019 #include "llvm/Support/Debug.h"
00020 #include "llvm/Support/Timer.h"
00021 using namespace llvm;
00022 
00023 #define DEBUG_TYPE "loop-pass-manager"
00024 
00025 namespace {
00026 
00027 /// PrintLoopPass - Print a Function corresponding to a Loop.
00028 ///
00029 class PrintLoopPass : public LoopPass {
00030 private:
00031   std::string Banner;
00032   raw_ostream &Out;       // raw_ostream to print on.
00033 
00034 public:
00035   static char ID;
00036   PrintLoopPass(const std::string &B, raw_ostream &o)
00037       : LoopPass(ID), Banner(B), Out(o) {}
00038 
00039   void getAnalysisUsage(AnalysisUsage &AU) const override {
00040     AU.setPreservesAll();
00041   }
00042 
00043   bool runOnLoop(Loop *L, LPPassManager &) override {
00044     Out << Banner;
00045     for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
00046          b != be;
00047          ++b) {
00048       if (*b)
00049         (*b)->print(Out);
00050       else
00051         Out << "Printing <null> block";
00052     }
00053     return false;
00054   }
00055 };
00056 
00057 char PrintLoopPass::ID = 0;
00058 }
00059 
00060 //===----------------------------------------------------------------------===//
00061 // LPPassManager
00062 //
00063 
00064 char LPPassManager::ID = 0;
00065 
00066 LPPassManager::LPPassManager()
00067   : FunctionPass(ID), PMDataManager() {
00068   skipThisLoop = false;
00069   redoThisLoop = false;
00070   LI = nullptr;
00071   CurrentLoop = nullptr;
00072 }
00073 
00074 /// Delete loop from the loop queue and loop hierarchy (LoopInfo).
00075 void LPPassManager::deleteLoopFromQueue(Loop *L) {
00076 
00077   LI->updateUnloop(L);
00078 
00079   // Notify passes that the loop is being deleted.
00080   deleteSimpleAnalysisLoop(L);
00081 
00082   // If L is current loop then skip rest of the passes and let
00083   // runOnFunction remove L from LQ. Otherwise, remove L from LQ now
00084   // and continue applying other passes on CurrentLoop.
00085   if (CurrentLoop == L)
00086     skipThisLoop = true;
00087 
00088   delete L;
00089 
00090   if (skipThisLoop)
00091     return;
00092 
00093   for (std::deque<Loop *>::iterator I = LQ.begin(),
00094          E = LQ.end(); I != E; ++I) {
00095     if (*I == L) {
00096       LQ.erase(I);
00097       break;
00098     }
00099   }
00100 }
00101 
00102 // Inset loop into loop nest (LoopInfo) and loop queue (LQ).
00103 void LPPassManager::insertLoop(Loop *L, Loop *ParentLoop) {
00104 
00105   assert (CurrentLoop != L && "Cannot insert CurrentLoop");
00106 
00107   // Insert into loop nest
00108   if (ParentLoop)
00109     ParentLoop->addChildLoop(L);
00110   else
00111     LI->addTopLevelLoop(L);
00112 
00113   insertLoopIntoQueue(L);
00114 }
00115 
00116 void LPPassManager::insertLoopIntoQueue(Loop *L) {
00117   // Insert L into loop queue
00118   if (L == CurrentLoop)
00119     redoLoop(L);
00120   else if (!L->getParentLoop())
00121     // This is top level loop.
00122     LQ.push_front(L);
00123   else {
00124     // Insert L after the parent loop.
00125     for (std::deque<Loop *>::iterator I = LQ.begin(),
00126            E = LQ.end(); I != E; ++I) {
00127       if (*I == L->getParentLoop()) {
00128         // deque does not support insert after.
00129         ++I;
00130         LQ.insert(I, 1, L);
00131         break;
00132       }
00133     }
00134   }
00135 }
00136 
00137 // Reoptimize this loop. LPPassManager will re-insert this loop into the
00138 // queue. This allows LoopPass to change loop nest for the loop. This
00139 // utility may send LPPassManager into infinite loops so use caution.
00140 void LPPassManager::redoLoop(Loop *L) {
00141   assert (CurrentLoop == L && "Can redo only CurrentLoop");
00142   redoThisLoop = true;
00143 }
00144 
00145 /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
00146 /// all loop passes.
00147 void LPPassManager::cloneBasicBlockSimpleAnalysis(BasicBlock *From,
00148                                                   BasicBlock *To, Loop *L) {
00149   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00150     LoopPass *LP = getContainedPass(Index);
00151     LP->cloneBasicBlockAnalysis(From, To, L);
00152   }
00153 }
00154 
00155 /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes.
00156 void LPPassManager::deleteSimpleAnalysisValue(Value *V, Loop *L) {
00157   if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
00158     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;
00159          ++BI) {
00160       Instruction &I = *BI;
00161       deleteSimpleAnalysisValue(&I, L);
00162     }
00163   }
00164   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00165     LoopPass *LP = getContainedPass(Index);
00166     LP->deleteAnalysisValue(V, L);
00167   }
00168 }
00169 
00170 /// Invoke deleteAnalysisLoop hook for all passes.
00171 void LPPassManager::deleteSimpleAnalysisLoop(Loop *L) {
00172   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00173     LoopPass *LP = getContainedPass(Index);
00174     LP->deleteAnalysisLoop(L);
00175   }
00176 }
00177 
00178 
00179 // Recurse through all subloops and all loops  into LQ.
00180 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
00181   LQ.push_back(L);
00182   for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I)
00183     addLoopIntoQueue(*I, LQ);
00184 }
00185 
00186 /// Pass Manager itself does not invalidate any analysis info.
00187 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
00188   // LPPassManager needs LoopInfo. In the long term LoopInfo class will
00189   // become part of LPPassManager.
00190   Info.addRequired<LoopInfoWrapperPass>();
00191   Info.setPreservesAll();
00192 }
00193 
00194 /// run - Execute all of the passes scheduled for execution.  Keep track of
00195 /// whether any of the passes modifies the function, and if so, return true.
00196 bool LPPassManager::runOnFunction(Function &F) {
00197   auto &LIWP = getAnalysis<LoopInfoWrapperPass>();
00198   LI = &LIWP.getLoopInfo();
00199   bool Changed = false;
00200 
00201   // Collect inherited analysis from Module level pass manager.
00202   populateInheritedAnalysis(TPM->activeStack);
00203 
00204   // Populate the loop queue in reverse program order. There is no clear need to
00205   // process sibling loops in either forward or reverse order. There may be some
00206   // advantage in deleting uses in a later loop before optimizing the
00207   // definitions in an earlier loop. If we find a clear reason to process in
00208   // forward order, then a forward variant of LoopPassManager should be created.
00209   //
00210   // Note that LoopInfo::iterator visits loops in reverse program
00211   // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
00212   // reverses the order a third time by popping from the back.
00213   for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
00214     addLoopIntoQueue(*I, LQ);
00215 
00216   if (LQ.empty()) // No loops, skip calling finalizers
00217     return false;
00218 
00219   // Initialization
00220   for (std::deque<Loop *>::const_iterator I = LQ.begin(), E = LQ.end();
00221        I != E; ++I) {
00222     Loop *L = *I;
00223     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00224       LoopPass *P = getContainedPass(Index);
00225       Changed |= P->doInitialization(L, *this);
00226     }
00227   }
00228 
00229   // Walk Loops
00230   while (!LQ.empty()) {
00231 
00232     CurrentLoop  = LQ.back();
00233     skipThisLoop = false;
00234     redoThisLoop = false;
00235 
00236     // Run all passes on the current Loop.
00237     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00238       LoopPass *P = getContainedPass(Index);
00239 
00240       dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
00241                    CurrentLoop->getHeader()->getName());
00242       dumpRequiredSet(P);
00243 
00244       initializeAnalysisImpl(P);
00245 
00246       {
00247         PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
00248         TimeRegion PassTimer(getPassTimer(P));
00249 
00250         Changed |= P->runOnLoop(CurrentLoop, *this);
00251       }
00252 
00253       if (Changed)
00254         dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
00255                      skipThisLoop ? "<deleted>" :
00256                                     CurrentLoop->getHeader()->getName());
00257       dumpPreservedSet(P);
00258 
00259       if (!skipThisLoop) {
00260         // Manually check that this loop is still healthy. This is done
00261         // instead of relying on LoopInfo::verifyLoop since LoopInfo
00262         // is a function pass and it's really expensive to verify every
00263         // loop in the function every time. That level of checking can be
00264         // enabled with the -verify-loop-info option.
00265         {
00266           TimeRegion PassTimer(getPassTimer(&LIWP));
00267           CurrentLoop->verifyLoop();
00268         }
00269 
00270         // Then call the regular verifyAnalysis functions.
00271         verifyPreservedAnalysis(P);
00272 
00273         F.getContext().yield();
00274       }
00275 
00276       removeNotPreservedAnalysis(P);
00277       recordAvailableAnalysis(P);
00278       removeDeadPasses(P,
00279                        skipThisLoop ? "<deleted>" :
00280                                       CurrentLoop->getHeader()->getName(),
00281                        ON_LOOP_MSG);
00282 
00283       if (skipThisLoop)
00284         // Do not run other passes on this loop.
00285         break;
00286     }
00287 
00288     // If the loop was deleted, release all the loop passes. This frees up
00289     // some memory, and avoids trouble with the pass manager trying to call
00290     // verifyAnalysis on them.
00291     if (skipThisLoop)
00292       for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00293         Pass *P = getContainedPass(Index);
00294         freePass(P, "<deleted>", ON_LOOP_MSG);
00295       }
00296 
00297     // Pop the loop from queue after running all passes.
00298     LQ.pop_back();
00299 
00300     if (redoThisLoop)
00301       LQ.push_back(CurrentLoop);
00302   }
00303 
00304   // Finalization
00305   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00306     LoopPass *P = getContainedPass(Index);
00307     Changed |= P->doFinalization();
00308   }
00309 
00310   return Changed;
00311 }
00312 
00313 /// Print passes managed by this manager
00314 void LPPassManager::dumpPassStructure(unsigned Offset) {
00315   errs().indent(Offset*2) << "Loop Pass Manager\n";
00316   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
00317     Pass *P = getContainedPass(Index);
00318     P->dumpPassStructure(Offset + 1);
00319     dumpLastUses(P, Offset+1);
00320   }
00321 }
00322 
00323 
00324 //===----------------------------------------------------------------------===//
00325 // LoopPass
00326 
00327 Pass *LoopPass::createPrinterPass(raw_ostream &O,
00328                                   const std::string &Banner) const {
00329   return new PrintLoopPass(Banner, O);
00330 }
00331 
00332 // Check if this pass is suitable for the current LPPassManager, if
00333 // available. This pass P is not suitable for a LPPassManager if P
00334 // is not preserving higher level analysis info used by other
00335 // LPPassManager passes. In such case, pop LPPassManager from the
00336 // stack. This will force assignPassManager() to create new
00337 // LPPassManger as expected.
00338 void LoopPass::preparePassManager(PMStack &PMS) {
00339 
00340   // Find LPPassManager
00341   while (!PMS.empty() &&
00342          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
00343     PMS.pop();
00344 
00345   // If this pass is destroying high level information that is used
00346   // by other passes that are managed by LPM then do not insert
00347   // this pass in current LPM. Use new LPPassManager.
00348   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
00349       !PMS.top()->preserveHigherLevelAnalysis(this))
00350     PMS.pop();
00351 }
00352 
00353 /// Assign pass manager to manage this pass.
00354 void LoopPass::assignPassManager(PMStack &PMS,
00355                                  PassManagerType PreferredType) {
00356   // Find LPPassManager
00357   while (!PMS.empty() &&
00358          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
00359     PMS.pop();
00360 
00361   LPPassManager *LPPM;
00362   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
00363     LPPM = (LPPassManager*)PMS.top();
00364   else {
00365     // Create new Loop Pass Manager if it does not exist.
00366     assert (!PMS.empty() && "Unable to create Loop Pass Manager");
00367     PMDataManager *PMD = PMS.top();
00368 
00369     // [1] Create new Loop Pass Manager
00370     LPPM = new LPPassManager();
00371     LPPM->populateInheritedAnalysis(PMS);
00372 
00373     // [2] Set up new manager's top level manager
00374     PMTopLevelManager *TPM = PMD->getTopLevelManager();
00375     TPM->addIndirectPassManager(LPPM);
00376 
00377     // [3] Assign manager to manage this new manager. This may create
00378     // and push new managers into PMS
00379     Pass *P = LPPM->getAsPass();
00380     TPM->schedulePass(P);
00381 
00382     // [4] Push new manager into PMS
00383     PMS.push(LPPM);
00384   }
00385 
00386   LPPM->add(this);
00387 }
00388 
00389 // Containing function has Attribute::OptimizeNone and transformation
00390 // passes should skip it.
00391 bool LoopPass::skipOptnoneFunction(const Loop *L) const {
00392   const Function *F = L->getHeader()->getParent();
00393   if (F && F->hasFnAttribute(Attribute::OptimizeNone)) {
00394     // FIXME: Report this to dbgs() only once per function.
00395     DEBUG(dbgs() << "Skipping pass '" << getPassName()
00396           << "' in function " << F->getName() << "\n");
00397     // FIXME: Delete loop from pass manager's queue?
00398     return true;
00399   }
00400   return false;
00401 }