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