Fix the pass manager's search order for immutable passes, and make it
[oota-llvm.git] / lib / VMCore / PassManager.cpp
1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
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 the LLVM Pass Manager infrastructure.
11 //
12 //===----------------------------------------------------------------------===//
13
14
15 #include "llvm/PassManagers.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Timer.h"
22 #include "llvm/Module.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/PassNameParser.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/Mutex.h"
28 #include <algorithm>
29 #include <cstdio>
30 #include <map>
31 using namespace llvm;
32
33 // See PassManagers.h for Pass Manager infrastructure overview.
34
35 namespace llvm {
36
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information.  Often it is useful to find out what pass is
39 // running when a crash occurs in a utility.  When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
42 //
43
44 // Different debug levels that can be enabled...
45 enum PassDebugLevel {
46   None, Arguments, Structure, Executions, Details
47 };
48
49 static cl::opt<enum PassDebugLevel>
50 PassDebugging("debug-pass", cl::Hidden,
51                   cl::desc("Print PassManager debugging information"),
52                   cl::values(
53   clEnumVal(None      , "disable debug output"),
54   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
55   clEnumVal(Structure , "print pass structure before run()"),
56   clEnumVal(Executions, "print pass name before it is executed"),
57   clEnumVal(Details   , "print pass details when it is executed"),
58                              clEnumValEnd));
59
60 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
61 PassOptionList;
62
63 // Print IR out before/after specified passes.
64 static PassOptionList
65 PrintBefore("print-before",
66             llvm::cl::desc("Print IR before specified passes"));
67
68 static PassOptionList
69 PrintAfter("print-after",
70            llvm::cl::desc("Print IR after specified passes"));
71
72 static cl::opt<bool>
73 PrintBeforeAll("print-before-all",
74                llvm::cl::desc("Print IR before each pass"),
75                cl::init(false));
76 static cl::opt<bool>
77 PrintAfterAll("print-after-all",
78               llvm::cl::desc("Print IR after each pass"),
79               cl::init(false));
80
81 /// This is a helper to determine whether to print IR before or
82 /// after a pass.
83
84 static bool ShouldPrintBeforeOrAfterPass(const void *PassID,
85                                          PassOptionList &PassesToPrint) {
86   if (const llvm::PassInfo *PI =
87       PassRegistry::getPassRegistry()->getPassInfo(PassID)) {
88     for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
89       const llvm::PassInfo *PassInf = PassesToPrint[i];
90       if (PassInf)
91         if (PassInf->getPassArgument() == PI->getPassArgument()) {
92           return true;
93         }
94     }
95   }
96   return false;
97 }
98
99
100 /// This is a utility to check whether a pass should have IR dumped
101 /// before it.
102 static bool ShouldPrintBeforePass(const void *PassID) {
103   return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
104 }
105
106 /// This is a utility to check whether a pass should have IR dumped
107 /// after it.
108 static bool ShouldPrintAfterPass(const void *PassID) {
109   return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
110 }
111
112 } // End of llvm namespace
113
114 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
115 /// or higher is specified.
116 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
117   return PassDebugging >= Executions;
118 }
119
120
121
122
123 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
124   if (V == 0 && M == 0)
125     OS << "Releasing pass '";
126   else
127     OS << "Running pass '";
128
129   OS << P->getPassName() << "'";
130
131   if (M) {
132     OS << " on module '" << M->getModuleIdentifier() << "'.\n";
133     return;
134   }
135   if (V == 0) {
136     OS << '\n';
137     return;
138   }
139
140   OS << " on ";
141   if (isa<Function>(V))
142     OS << "function";
143   else if (isa<BasicBlock>(V))
144     OS << "basic block";
145   else
146     OS << "value";
147
148   OS << " '";
149   WriteAsOperand(OS, V, /*PrintTy=*/false, M);
150   OS << "'\n";
151 }
152
153
154 namespace {
155
156 //===----------------------------------------------------------------------===//
157 // BBPassManager
158 //
159 /// BBPassManager manages BasicBlockPass. It batches all the
160 /// pass together and sequence them to process one basic block before
161 /// processing next basic block.
162 class BBPassManager : public PMDataManager, public FunctionPass {
163
164 public:
165   static char ID;
166   explicit BBPassManager(int Depth)
167     : PMDataManager(Depth), FunctionPass(ID) {}
168
169   /// Execute all of the passes scheduled for execution.  Keep track of
170   /// whether any of the passes modifies the function, and if so, return true.
171   bool runOnFunction(Function &F);
172
173   /// Pass Manager itself does not invalidate any analysis info.
174   void getAnalysisUsage(AnalysisUsage &Info) const {
175     Info.setPreservesAll();
176   }
177
178   bool doInitialization(Module &M);
179   bool doInitialization(Function &F);
180   bool doFinalization(Module &M);
181   bool doFinalization(Function &F);
182
183   virtual PMDataManager *getAsPMDataManager() { return this; }
184   virtual Pass *getAsPass() { return this; }
185
186   virtual const char *getPassName() const {
187     return "BasicBlock Pass Manager";
188   }
189
190   // Print passes managed by this manager
191   void dumpPassStructure(unsigned Offset) {
192     llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
193     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
194       BasicBlockPass *BP = getContainedPass(Index);
195       BP->dumpPassStructure(Offset + 1);
196       dumpLastUses(BP, Offset+1);
197     }
198   }
199
200   BasicBlockPass *getContainedPass(unsigned N) {
201     assert(N < PassVector.size() && "Pass number out of range!");
202     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
203     return BP;
204   }
205
206   virtual PassManagerType getPassManagerType() const {
207     return PMT_BasicBlockPassManager;
208   }
209 };
210
211 char BBPassManager::ID = 0;
212 }
213
214 namespace llvm {
215
216 //===----------------------------------------------------------------------===//
217 // FunctionPassManagerImpl
218 //
219 /// FunctionPassManagerImpl manages FPPassManagers
220 class FunctionPassManagerImpl : public Pass,
221                                 public PMDataManager,
222                                 public PMTopLevelManager {
223 private:
224   bool wasRun;
225 public:
226   static char ID;
227   explicit FunctionPassManagerImpl(int Depth) :
228     Pass(PT_PassManager, ID), PMDataManager(Depth),
229     PMTopLevelManager(new FPPassManager(1)), wasRun(false) {}
230
231   /// add - Add a pass to the queue of passes to run.  This passes ownership of
232   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
233   /// will be destroyed as well, so there is no need to delete the pass.  This
234   /// implies that all passes MUST be allocated with 'new'.
235   void add(Pass *P) {
236     schedulePass(P);
237   }
238
239   /// createPrinterPass - Get a function printer pass.
240   Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
241     return createPrintFunctionPass(Banner, &O);
242   }
243
244   // Prepare for running an on the fly pass, freeing memory if needed
245   // from a previous run.
246   void releaseMemoryOnTheFly();
247
248   /// run - Execute all of the passes scheduled for execution.  Keep track of
249   /// whether any of the passes modifies the module, and if so, return true.
250   bool run(Function &F);
251
252   /// doInitialization - Run all of the initializers for the function passes.
253   ///
254   bool doInitialization(Module &M);
255
256   /// doFinalization - Run all of the finalizers for the function passes.
257   ///
258   bool doFinalization(Module &M);
259
260
261   virtual PMDataManager *getAsPMDataManager() { return this; }
262   virtual Pass *getAsPass() { return this; }
263
264   /// Pass Manager itself does not invalidate any analysis info.
265   void getAnalysisUsage(AnalysisUsage &Info) const {
266     Info.setPreservesAll();
267   }
268
269   void addTopLevelPass(Pass *P) {
270     if (ImmutablePass *IP = P->getAsImmutablePass()) {
271       // P is a immutable pass and it will be managed by this
272       // top level manager. Set up analysis resolver to connect them.
273       AnalysisResolver *AR = new AnalysisResolver(*this);
274       P->setResolver(AR);
275       initializeAnalysisImpl(P);
276       addImmutablePass(IP);
277       recordAvailableAnalysis(IP);
278     } else {
279       P->assignPassManager(activeStack, PMT_FunctionPassManager);
280     }
281
282   }
283
284   FPPassManager *getContainedManager(unsigned N) {
285     assert(N < PassManagers.size() && "Pass number out of range!");
286     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
287     return FP;
288   }
289 };
290
291 char FunctionPassManagerImpl::ID = 0;
292
293 //===----------------------------------------------------------------------===//
294 // MPPassManager
295 //
296 /// MPPassManager manages ModulePasses and function pass managers.
297 /// It batches all Module passes and function pass managers together and
298 /// sequences them to process one module.
299 class MPPassManager : public Pass, public PMDataManager {
300 public:
301   static char ID;
302   explicit MPPassManager(int Depth) :
303     Pass(PT_PassManager, ID), PMDataManager(Depth) { }
304
305   // Delete on the fly managers.
306   virtual ~MPPassManager() {
307     for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
308            I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
309          I != E; ++I) {
310       FunctionPassManagerImpl *FPP = I->second;
311       delete FPP;
312     }
313   }
314
315   /// createPrinterPass - Get a module printer pass.
316   Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
317     return createPrintModulePass(&O, false, Banner);
318   }
319
320   /// run - Execute all of the passes scheduled for execution.  Keep track of
321   /// whether any of the passes modifies the module, and if so, return true.
322   bool runOnModule(Module &M);
323
324   /// Pass Manager itself does not invalidate any analysis info.
325   void getAnalysisUsage(AnalysisUsage &Info) const {
326     Info.setPreservesAll();
327   }
328
329   /// Add RequiredPass into list of lower level passes required by pass P.
330   /// RequiredPass is run on the fly by Pass Manager when P requests it
331   /// through getAnalysis interface.
332   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
333
334   /// Return function pass corresponding to PassInfo PI, that is
335   /// required by module pass MP. Instantiate analysis pass, by using
336   /// its runOnFunction() for function F.
337   virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
338
339   virtual const char *getPassName() const {
340     return "Module Pass Manager";
341   }
342
343   virtual PMDataManager *getAsPMDataManager() { return this; }
344   virtual Pass *getAsPass() { return this; }
345
346   // Print passes managed by this manager
347   void dumpPassStructure(unsigned Offset) {
348     llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
349     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
350       ModulePass *MP = getContainedPass(Index);
351       MP->dumpPassStructure(Offset + 1);
352       std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
353         OnTheFlyManagers.find(MP);
354       if (I != OnTheFlyManagers.end())
355         I->second->dumpPassStructure(Offset + 2);
356       dumpLastUses(MP, Offset+1);
357     }
358   }
359
360   ModulePass *getContainedPass(unsigned N) {
361     assert(N < PassVector.size() && "Pass number out of range!");
362     return static_cast<ModulePass *>(PassVector[N]);
363   }
364
365   virtual PassManagerType getPassManagerType() const {
366     return PMT_ModulePassManager;
367   }
368
369  private:
370   /// Collection of on the fly FPPassManagers. These managers manage
371   /// function passes that are required by module passes.
372   std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
373 };
374
375 char MPPassManager::ID = 0;
376 //===----------------------------------------------------------------------===//
377 // PassManagerImpl
378 //
379
380 /// PassManagerImpl manages MPPassManagers
381 class PassManagerImpl : public Pass,
382                         public PMDataManager,
383                         public PMTopLevelManager {
384
385 public:
386   static char ID;
387   explicit PassManagerImpl(int Depth) :
388     Pass(PT_PassManager, ID), PMDataManager(Depth),
389                               PMTopLevelManager(new MPPassManager(1)) {}
390
391   /// add - Add a pass to the queue of passes to run.  This passes ownership of
392   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
393   /// will be destroyed as well, so there is no need to delete the pass.  This
394   /// implies that all passes MUST be allocated with 'new'.
395   void add(Pass *P) {
396     schedulePass(P);
397   }
398
399   /// createPrinterPass - Get a module printer pass.
400   Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
401     return createPrintModulePass(&O, false, Banner);
402   }
403
404   /// run - Execute all of the passes scheduled for execution.  Keep track of
405   /// whether any of the passes modifies the module, and if so, return true.
406   bool run(Module &M);
407
408   /// Pass Manager itself does not invalidate any analysis info.
409   void getAnalysisUsage(AnalysisUsage &Info) const {
410     Info.setPreservesAll();
411   }
412
413   void addTopLevelPass(Pass *P) {
414     if (ImmutablePass *IP = P->getAsImmutablePass()) {
415       // P is a immutable pass and it will be managed by this
416       // top level manager. Set up analysis resolver to connect them.
417       AnalysisResolver *AR = new AnalysisResolver(*this);
418       P->setResolver(AR);
419       initializeAnalysisImpl(P);
420       addImmutablePass(IP);
421       recordAvailableAnalysis(IP);
422     } else {
423       P->assignPassManager(activeStack, PMT_ModulePassManager);
424     }
425   }
426
427   virtual PMDataManager *getAsPMDataManager() { return this; }
428   virtual Pass *getAsPass() { return this; }
429
430   MPPassManager *getContainedManager(unsigned N) {
431     assert(N < PassManagers.size() && "Pass number out of range!");
432     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
433     return MP;
434   }
435 };
436
437 char PassManagerImpl::ID = 0;
438 } // End of llvm namespace
439
440 namespace {
441
442 //===----------------------------------------------------------------------===//
443 /// TimingInfo Class - This class is used to calculate information about the
444 /// amount of time each pass takes to execute.  This only happens when
445 /// -time-passes is enabled on the command line.
446 ///
447
448 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
449
450 class TimingInfo {
451   DenseMap<Pass*, Timer*> TimingData;
452   TimerGroup TG;
453 public:
454   // Use 'create' member to get this.
455   TimingInfo() : TG("... Pass execution timing report ...") {}
456
457   // TimingDtor - Print out information about timing information
458   ~TimingInfo() {
459     // Delete all of the timers, which accumulate their info into the
460     // TimerGroup.
461     for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
462          E = TimingData.end(); I != E; ++I)
463       delete I->second;
464     // TimerGroup is deleted next, printing the report.
465   }
466
467   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
468   // to a non null value (if the -time-passes option is enabled) or it leaves it
469   // null.  It may be called multiple times.
470   static void createTheTimeInfo();
471
472   /// getPassTimer - Return the timer for the specified pass if it exists.
473   Timer *getPassTimer(Pass *P) {
474     if (P->getAsPMDataManager())
475       return 0;
476
477     sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
478     Timer *&T = TimingData[P];
479     if (T == 0)
480       T = new Timer(P->getPassName(), TG);
481     return T;
482   }
483 };
484
485 } // End of anon namespace
486
487 static TimingInfo *TheTimeInfo;
488
489 //===----------------------------------------------------------------------===//
490 // PMTopLevelManager implementation
491
492 /// Initialize top level manager. Create first pass manager.
493 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
494   PMDM->setTopLevelManager(this);
495   addPassManager(PMDM);
496   activeStack.push(PMDM);
497 }
498
499 /// Set pass P as the last user of the given analysis passes.
500 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
501                                     Pass *P) {
502   for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
503          E = AnalysisPasses.end(); I != E; ++I) {
504     Pass *AP = *I;
505     LastUser[AP] = P;
506
507     if (P == AP)
508       continue;
509
510     // If AP is the last user of other passes then make P last user of
511     // such passes.
512     for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
513            LUE = LastUser.end(); LUI != LUE; ++LUI) {
514       if (LUI->second == AP)
515         // DenseMap iterator is not invalidated here because
516         // this is just updating exisitng entry.
517         LastUser[LUI->first] = P;
518     }
519   }
520 }
521
522 /// Collect passes whose last user is P
523 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
524                                         Pass *P) {
525   DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
526     InversedLastUser.find(P);
527   if (DMI == InversedLastUser.end())
528     return;
529
530   SmallPtrSet<Pass *, 8> &LU = DMI->second;
531   for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
532          E = LU.end(); I != E; ++I) {
533     LastUses.push_back(*I);
534   }
535
536 }
537
538 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
539   AnalysisUsage *AnUsage = NULL;
540   DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
541   if (DMI != AnUsageMap.end())
542     AnUsage = DMI->second;
543   else {
544     AnUsage = new AnalysisUsage();
545     P->getAnalysisUsage(*AnUsage);
546     AnUsageMap[P] = AnUsage;
547   }
548   return AnUsage;
549 }
550
551 /// Schedule pass P for execution. Make sure that passes required by
552 /// P are run before P is run. Update analysis info maintained by
553 /// the manager. Remove dead passes. This is a recursive function.
554 void PMTopLevelManager::schedulePass(Pass *P) {
555
556   // TODO : Allocate function manager for this pass, other wise required set
557   // may be inserted into previous function manager
558
559   // Give pass a chance to prepare the stage.
560   P->preparePassManager(activeStack);
561
562   // If P is an analysis pass and it is available then do not
563   // generate the analysis again. Stale analysis info should not be
564   // available at this point.
565   const PassInfo *PI =
566     PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
567   if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
568     delete P;
569     return;
570   }
571
572   AnalysisUsage *AnUsage = findAnalysisUsage(P);
573
574   bool checkAnalysis = true;
575   while (checkAnalysis) {
576     checkAnalysis = false;
577
578     const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
579     for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
580            E = RequiredSet.end(); I != E; ++I) {
581
582       Pass *AnalysisPass = findAnalysisPass(*I);
583       if (!AnalysisPass) {
584         const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
585         AnalysisPass = PI->createPass();
586         if (P->getPotentialPassManagerType () ==
587             AnalysisPass->getPotentialPassManagerType())
588           // Schedule analysis pass that is managed by the same pass manager.
589           schedulePass(AnalysisPass);
590         else if (P->getPotentialPassManagerType () >
591                  AnalysisPass->getPotentialPassManagerType()) {
592           // Schedule analysis pass that is managed by a new manager.
593           schedulePass(AnalysisPass);
594           // Recheck analysis passes to ensure that required analyses that
595           // are already checked are still available.
596           checkAnalysis = true;
597         }
598         else
599           // Do not schedule this analysis. Lower level analsyis
600           // passes are run on the fly.
601           delete AnalysisPass;
602       }
603     }
604   }
605
606   // Now all required passes are available.
607   addTopLevelPass(P);
608 }
609
610 /// Find the pass that implements Analysis AID. Search immutable
611 /// passes and all pass managers. If desired pass is not found
612 /// then return NULL.
613 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
614
615   // Check pass managers
616   for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
617          E = PassManagers.end(); I != E; ++I)
618     if (Pass *P = (*I)->findAnalysisPass(AID, false))
619       return P;
620
621   // Check other pass managers
622   for (SmallVector<PMDataManager *, 8>::iterator
623          I = IndirectPassManagers.begin(),
624          E = IndirectPassManagers.end(); I != E; ++I)
625     if (Pass *P = (*I)->findAnalysisPass(AID, false))
626       return P;
627
628   // Check the immutable passes. Iterate in reverse order so that we find
629   // the most recently registered passes first.
630   for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
631        ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
632     AnalysisID PI = (*I)->getPassID();
633     if (PI == AID)
634       return *I;
635
636     // If Pass not found then check the interfaces implemented by Immutable Pass
637     const PassInfo *PassInf =
638       PassRegistry::getPassRegistry()->getPassInfo(PI);
639     const std::vector<const PassInfo*> &ImmPI =
640       PassInf->getInterfacesImplemented();
641     for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
642          EE = ImmPI.end(); II != EE; ++II) {
643       if ((*II)->getTypeInfo() == AID)
644         return *I;
645     }
646   }
647
648   return 0;
649 }
650
651 // Print passes managed by this top level manager.
652 void PMTopLevelManager::dumpPasses() const {
653
654   if (PassDebugging < Structure)
655     return;
656
657   // Print out the immutable passes
658   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
659     ImmutablePasses[i]->dumpPassStructure(0);
660   }
661
662   // Every class that derives from PMDataManager also derives from Pass
663   // (sometimes indirectly), but there's no inheritance relationship
664   // between PMDataManager and Pass, so we have to getAsPass to get
665   // from a PMDataManager* to a Pass*.
666   for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
667          E = PassManagers.end(); I != E; ++I)
668     (*I)->getAsPass()->dumpPassStructure(1);
669 }
670
671 void PMTopLevelManager::dumpArguments() const {
672
673   if (PassDebugging < Arguments)
674     return;
675
676   dbgs() << "Pass Arguments: ";
677   for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
678          E = PassManagers.end(); I != E; ++I)
679     (*I)->dumpPassArguments();
680   dbgs() << "\n";
681 }
682
683 void PMTopLevelManager::initializeAllAnalysisInfo() {
684   for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
685          E = PassManagers.end(); I != E; ++I)
686     (*I)->initializeAnalysisInfo();
687
688   // Initailize other pass managers
689   for (SmallVector<PMDataManager *, 8>::iterator
690        I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
691        I != E; ++I)
692     (*I)->initializeAnalysisInfo();
693
694   for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
695         DME = LastUser.end(); DMI != DME; ++DMI) {
696     DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
697       InversedLastUser.find(DMI->second);
698     if (InvDMI != InversedLastUser.end()) {
699       SmallPtrSet<Pass *, 8> &L = InvDMI->second;
700       L.insert(DMI->first);
701     } else {
702       SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
703       InversedLastUser[DMI->second] = L;
704     }
705   }
706 }
707
708 /// Destructor
709 PMTopLevelManager::~PMTopLevelManager() {
710   for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
711          E = PassManagers.end(); I != E; ++I)
712     delete *I;
713
714   for (SmallVector<ImmutablePass *, 8>::iterator
715          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
716     delete *I;
717
718   for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
719          DME = AnUsageMap.end(); DMI != DME; ++DMI)
720     delete DMI->second;
721 }
722
723 //===----------------------------------------------------------------------===//
724 // PMDataManager implementation
725
726 /// Augement AvailableAnalysis by adding analysis made available by pass P.
727 void PMDataManager::recordAvailableAnalysis(Pass *P) {
728   AnalysisID PI = P->getPassID();
729
730   AvailableAnalysis[PI] = P;
731
732   assert(!AvailableAnalysis.empty());
733
734   // This pass is the current implementation of all of the interfaces it
735   // implements as well.
736   const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
737   if (PInf == 0) return;
738   const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
739   for (unsigned i = 0, e = II.size(); i != e; ++i)
740     AvailableAnalysis[II[i]->getTypeInfo()] = P;
741 }
742
743 // Return true if P preserves high level analysis used by other
744 // passes managed by this manager
745 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
746   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
747   if (AnUsage->getPreservesAll())
748     return true;
749
750   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
751   for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
752          E = HigherLevelAnalysis.end(); I  != E; ++I) {
753     Pass *P1 = *I;
754     if (P1->getAsImmutablePass() == 0 &&
755         std::find(PreservedSet.begin(), PreservedSet.end(),
756                   P1->getPassID()) ==
757            PreservedSet.end())
758       return false;
759   }
760
761   return true;
762 }
763
764 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
765 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
766   // Don't do this unless assertions are enabled.
767 #ifdef NDEBUG
768   return;
769 #endif
770   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
771   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
772
773   // Verify preserved analysis
774   for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
775          E = PreservedSet.end(); I != E; ++I) {
776     AnalysisID AID = *I;
777     if (Pass *AP = findAnalysisPass(AID, true)) {
778       TimeRegion PassTimer(getPassTimer(AP));
779       AP->verifyAnalysis();
780     }
781   }
782 }
783
784 /// Remove Analysis not preserved by Pass P
785 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
786   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
787   if (AnUsage->getPreservesAll())
788     return;
789
790   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
791   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
792          E = AvailableAnalysis.end(); I != E; ) {
793     std::map<AnalysisID, Pass*>::iterator Info = I++;
794     if (Info->second->getAsImmutablePass() == 0 &&
795         std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
796         PreservedSet.end()) {
797       // Remove this analysis
798       if (PassDebugging >= Details) {
799         Pass *S = Info->second;
800         dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
801         dbgs() << S->getPassName() << "'\n";
802       }
803       AvailableAnalysis.erase(Info);
804     }
805   }
806
807   // Check inherited analysis also. If P is not preserving analysis
808   // provided by parent manager then remove it here.
809   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
810
811     if (!InheritedAnalysis[Index])
812       continue;
813
814     for (std::map<AnalysisID, Pass*>::iterator
815            I = InheritedAnalysis[Index]->begin(),
816            E = InheritedAnalysis[Index]->end(); I != E; ) {
817       std::map<AnalysisID, Pass *>::iterator Info = I++;
818       if (Info->second->getAsImmutablePass() == 0 &&
819           std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
820              PreservedSet.end()) {
821         // Remove this analysis
822         if (PassDebugging >= Details) {
823           Pass *S = Info->second;
824           dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
825           dbgs() << S->getPassName() << "'\n";
826         }
827         InheritedAnalysis[Index]->erase(Info);
828       }
829     }
830   }
831 }
832
833 /// Remove analysis passes that are not used any longer
834 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
835                                      enum PassDebuggingString DBG_STR) {
836
837   SmallVector<Pass *, 12> DeadPasses;
838
839   // If this is a on the fly manager then it does not have TPM.
840   if (!TPM)
841     return;
842
843   TPM->collectLastUses(DeadPasses, P);
844
845   if (PassDebugging >= Details && !DeadPasses.empty()) {
846     dbgs() << " -*- '" <<  P->getPassName();
847     dbgs() << "' is the last user of following pass instances.";
848     dbgs() << " Free these instances\n";
849   }
850
851   for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
852          E = DeadPasses.end(); I != E; ++I)
853     freePass(*I, Msg, DBG_STR);
854 }
855
856 void PMDataManager::freePass(Pass *P, StringRef Msg,
857                              enum PassDebuggingString DBG_STR) {
858   dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
859
860   {
861     // If the pass crashes releasing memory, remember this.
862     PassManagerPrettyStackEntry X(P);
863     TimeRegion PassTimer(getPassTimer(P));
864
865     P->releaseMemory();
866   }
867
868   AnalysisID PI = P->getPassID();
869   if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
870     // Remove the pass itself (if it is not already removed).
871     AvailableAnalysis.erase(PI);
872
873     // Remove all interfaces this pass implements, for which it is also
874     // listed as the available implementation.
875     const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
876     for (unsigned i = 0, e = II.size(); i != e; ++i) {
877       std::map<AnalysisID, Pass*>::iterator Pos =
878         AvailableAnalysis.find(II[i]->getTypeInfo());
879       if (Pos != AvailableAnalysis.end() && Pos->second == P)
880         AvailableAnalysis.erase(Pos);
881     }
882   }
883 }
884
885 /// Add pass P into the PassVector. Update
886 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
887 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
888   // This manager is going to manage pass P. Set up analysis resolver
889   // to connect them.
890   AnalysisResolver *AR = new AnalysisResolver(*this);
891   P->setResolver(AR);
892
893   // If a FunctionPass F is the last user of ModulePass info M
894   // then the F's manager, not F, records itself as a last user of M.
895   SmallVector<Pass *, 12> TransferLastUses;
896
897   if (!ProcessAnalysis) {
898     // Add pass
899     PassVector.push_back(P);
900     return;
901   }
902
903   // At the moment, this pass is the last user of all required passes.
904   SmallVector<Pass *, 12> LastUses;
905   SmallVector<Pass *, 8> RequiredPasses;
906   SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
907
908   unsigned PDepth = this->getDepth();
909
910   collectRequiredAnalysis(RequiredPasses,
911                           ReqAnalysisNotAvailable, P);
912   for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
913          E = RequiredPasses.end(); I != E; ++I) {
914     Pass *PRequired = *I;
915     unsigned RDepth = 0;
916
917     assert(PRequired->getResolver() && "Analysis Resolver is not set");
918     PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
919     RDepth = DM.getDepth();
920
921     if (PDepth == RDepth)
922       LastUses.push_back(PRequired);
923     else if (PDepth > RDepth) {
924       // Let the parent claim responsibility of last use
925       TransferLastUses.push_back(PRequired);
926       // Keep track of higher level analysis used by this manager.
927       HigherLevelAnalysis.push_back(PRequired);
928     } else
929       llvm_unreachable("Unable to accomodate Required Pass");
930   }
931
932   // Set P as P's last user until someone starts using P.
933   // However, if P is a Pass Manager then it does not need
934   // to record its last user.
935   if (P->getAsPMDataManager() == 0)
936     LastUses.push_back(P);
937   TPM->setLastUser(LastUses, P);
938
939   if (!TransferLastUses.empty()) {
940     Pass *My_PM = getAsPass();
941     TPM->setLastUser(TransferLastUses, My_PM);
942     TransferLastUses.clear();
943   }
944
945   // Now, take care of required analyses that are not available.
946   for (SmallVector<AnalysisID, 8>::iterator
947          I = ReqAnalysisNotAvailable.begin(),
948          E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
949     const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
950     Pass *AnalysisPass = PI->createPass();
951     this->addLowerLevelRequiredPass(P, AnalysisPass);
952   }
953
954   // Take a note of analysis required and made available by this pass.
955   // Remove the analysis not preserved by this pass
956   removeNotPreservedAnalysis(P);
957   recordAvailableAnalysis(P);
958
959   // Add pass
960   PassVector.push_back(P);
961 }
962
963
964 /// Populate RP with analysis pass that are required by
965 /// pass P and are available. Populate RP_NotAvail with analysis
966 /// pass that are required by pass P but are not available.
967 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
968                                        SmallVector<AnalysisID, 8> &RP_NotAvail,
969                                             Pass *P) {
970   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
971   const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
972   for (AnalysisUsage::VectorType::const_iterator
973          I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
974     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
975       RP.push_back(AnalysisPass);
976     else
977       RP_NotAvail.push_back(*I);
978   }
979
980   const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
981   for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
982          E = IDs.end(); I != E; ++I) {
983     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
984       RP.push_back(AnalysisPass);
985     else
986       RP_NotAvail.push_back(*I);
987   }
988 }
989
990 // All Required analyses should be available to the pass as it runs!  Here
991 // we fill in the AnalysisImpls member of the pass so that it can
992 // successfully use the getAnalysis() method to retrieve the
993 // implementations it needs.
994 //
995 void PMDataManager::initializeAnalysisImpl(Pass *P) {
996   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
997
998   for (AnalysisUsage::VectorType::const_iterator
999          I = AnUsage->getRequiredSet().begin(),
1000          E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1001     Pass *Impl = findAnalysisPass(*I, true);
1002     if (Impl == 0)
1003       // This may be analysis pass that is initialized on the fly.
1004       // If that is not the case then it will raise an assert when it is used.
1005       continue;
1006     AnalysisResolver *AR = P->getResolver();
1007     assert(AR && "Analysis Resolver is not set");
1008     AR->addAnalysisImplsPair(*I, Impl);
1009   }
1010 }
1011
1012 /// Find the pass that implements Analysis AID. If desired pass is not found
1013 /// then return NULL.
1014 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1015
1016   // Check if AvailableAnalysis map has one entry.
1017   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
1018
1019   if (I != AvailableAnalysis.end())
1020     return I->second;
1021
1022   // Search Parents through TopLevelManager
1023   if (SearchParent)
1024     return TPM->findAnalysisPass(AID);
1025
1026   return NULL;
1027 }
1028
1029 // Print list of passes that are last used by P.
1030 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1031
1032   SmallVector<Pass *, 12> LUses;
1033
1034   // If this is a on the fly manager then it does not have TPM.
1035   if (!TPM)
1036     return;
1037
1038   TPM->collectLastUses(LUses, P);
1039
1040   for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1041          E = LUses.end(); I != E; ++I) {
1042     llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1043     (*I)->dumpPassStructure(0);
1044   }
1045 }
1046
1047 void PMDataManager::dumpPassArguments() const {
1048   for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1049         E = PassVector.end(); I != E; ++I) {
1050     if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1051       PMD->dumpPassArguments();
1052     else
1053       if (const PassInfo *PI =
1054             PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1055         if (!PI->isAnalysisGroup())
1056           dbgs() << " -" << PI->getPassArgument();
1057   }
1058 }
1059
1060 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1061                                  enum PassDebuggingString S2,
1062                                  StringRef Msg) {
1063   if (PassDebugging < Executions)
1064     return;
1065   dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1066   switch (S1) {
1067   case EXECUTION_MSG:
1068     dbgs() << "Executing Pass '" << P->getPassName();
1069     break;
1070   case MODIFICATION_MSG:
1071     dbgs() << "Made Modification '" << P->getPassName();
1072     break;
1073   case FREEING_MSG:
1074     dbgs() << " Freeing Pass '" << P->getPassName();
1075     break;
1076   default:
1077     break;
1078   }
1079   switch (S2) {
1080   case ON_BASICBLOCK_MSG:
1081     dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1082     break;
1083   case ON_FUNCTION_MSG:
1084     dbgs() << "' on Function '" << Msg << "'...\n";
1085     break;
1086   case ON_MODULE_MSG:
1087     dbgs() << "' on Module '"  << Msg << "'...\n";
1088     break;
1089   case ON_LOOP_MSG:
1090     dbgs() << "' on Loop '" << Msg << "'...\n";
1091     break;
1092   case ON_CG_MSG:
1093     dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1094     break;
1095   default:
1096     break;
1097   }
1098 }
1099
1100 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1101   if (PassDebugging < Details)
1102     return;
1103
1104   AnalysisUsage analysisUsage;
1105   P->getAnalysisUsage(analysisUsage);
1106   dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1107 }
1108
1109 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1110   if (PassDebugging < Details)
1111     return;
1112
1113   AnalysisUsage analysisUsage;
1114   P->getAnalysisUsage(analysisUsage);
1115   dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1116 }
1117
1118 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1119                                    const AnalysisUsage::VectorType &Set) const {
1120   assert(PassDebugging >= Details);
1121   if (Set.empty())
1122     return;
1123   dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1124   for (unsigned i = 0; i != Set.size(); ++i) {
1125     if (i) dbgs() << ',';
1126     const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1127     dbgs() << ' ' << PInf->getPassName();
1128   }
1129   dbgs() << '\n';
1130 }
1131
1132 /// Add RequiredPass into list of lower level passes required by pass P.
1133 /// RequiredPass is run on the fly by Pass Manager when P requests it
1134 /// through getAnalysis interface.
1135 /// This should be handled by specific pass manager.
1136 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1137   if (TPM) {
1138     TPM->dumpArguments();
1139     TPM->dumpPasses();
1140   }
1141
1142   // Module Level pass may required Function Level analysis info
1143   // (e.g. dominator info). Pass manager uses on the fly function pass manager
1144   // to provide this on demand. In that case, in Pass manager terminology,
1145   // module level pass is requiring lower level analysis info managed by
1146   // lower level pass manager.
1147
1148   // When Pass manager is not able to order required analysis info, Pass manager
1149   // checks whether any lower level manager will be able to provide this
1150   // analysis info on demand or not.
1151 #ifndef NDEBUG
1152   dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1153   dbgs() << "' required by '" << P->getPassName() << "'\n";
1154 #endif
1155   llvm_unreachable("Unable to schedule pass");
1156 }
1157
1158 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1159   assert(0 && "Unable to find on the fly pass");
1160   return NULL;
1161 }
1162
1163 // Destructor
1164 PMDataManager::~PMDataManager() {
1165   for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1166          E = PassVector.end(); I != E; ++I)
1167     delete *I;
1168 }
1169
1170 //===----------------------------------------------------------------------===//
1171 // NOTE: Is this the right place to define this method ?
1172 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1173 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1174   return PM.findAnalysisPass(ID, dir);
1175 }
1176
1177 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1178                                      Function &F) {
1179   return PM.getOnTheFlyPass(P, AnalysisPI, F);
1180 }
1181
1182 //===----------------------------------------------------------------------===//
1183 // BBPassManager implementation
1184
1185 /// Execute all of the passes scheduled for execution by invoking
1186 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies
1187 /// the function, and if so, return true.
1188 bool BBPassManager::runOnFunction(Function &F) {
1189   if (F.isDeclaration())
1190     return false;
1191
1192   bool Changed = doInitialization(F);
1193
1194   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1195     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1196       BasicBlockPass *BP = getContainedPass(Index);
1197       bool LocalChanged = false;
1198
1199       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1200       dumpRequiredSet(BP);
1201
1202       initializeAnalysisImpl(BP);
1203
1204       {
1205         // If the pass crashes, remember this.
1206         PassManagerPrettyStackEntry X(BP, *I);
1207         TimeRegion PassTimer(getPassTimer(BP));
1208
1209         LocalChanged |= BP->runOnBasicBlock(*I);
1210       }
1211
1212       Changed |= LocalChanged;
1213       if (LocalChanged)
1214         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1215                      I->getName());
1216       dumpPreservedSet(BP);
1217
1218       verifyPreservedAnalysis(BP);
1219       removeNotPreservedAnalysis(BP);
1220       recordAvailableAnalysis(BP);
1221       removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1222     }
1223
1224   return doFinalization(F) || Changed;
1225 }
1226
1227 // Implement doInitialization and doFinalization
1228 bool BBPassManager::doInitialization(Module &M) {
1229   bool Changed = false;
1230
1231   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1232     Changed |= getContainedPass(Index)->doInitialization(M);
1233
1234   return Changed;
1235 }
1236
1237 bool BBPassManager::doFinalization(Module &M) {
1238   bool Changed = false;
1239
1240   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1241     Changed |= getContainedPass(Index)->doFinalization(M);
1242
1243   return Changed;
1244 }
1245
1246 bool BBPassManager::doInitialization(Function &F) {
1247   bool Changed = false;
1248
1249   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1250     BasicBlockPass *BP = getContainedPass(Index);
1251     Changed |= BP->doInitialization(F);
1252   }
1253
1254   return Changed;
1255 }
1256
1257 bool BBPassManager::doFinalization(Function &F) {
1258   bool Changed = false;
1259
1260   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1261     BasicBlockPass *BP = getContainedPass(Index);
1262     Changed |= BP->doFinalization(F);
1263   }
1264
1265   return Changed;
1266 }
1267
1268
1269 //===----------------------------------------------------------------------===//
1270 // FunctionPassManager implementation
1271
1272 /// Create new Function pass manager
1273 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1274   FPM = new FunctionPassManagerImpl(0);
1275   // FPM is the top level manager.
1276   FPM->setTopLevelManager(FPM);
1277
1278   AnalysisResolver *AR = new AnalysisResolver(*FPM);
1279   FPM->setResolver(AR);
1280 }
1281
1282 FunctionPassManager::~FunctionPassManager() {
1283   delete FPM;
1284 }
1285
1286 /// addImpl - Add a pass to the queue of passes to run, without
1287 /// checking whether to add a printer pass.
1288 void FunctionPassManager::addImpl(Pass *P) {
1289   FPM->add(P);
1290 }
1291
1292 /// add - Add a pass to the queue of passes to run.  This passes
1293 /// ownership of the Pass to the PassManager.  When the
1294 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1295 /// there is no need to delete the pass. (TODO delete passes.)
1296 /// This implies that all passes MUST be allocated with 'new'.
1297 void FunctionPassManager::add(Pass *P) {
1298   // If this is a not a function pass, don't add a printer for it.
1299   const void *PassID = P->getPassID();
1300   if (P->getPassKind() == PT_Function)
1301     if (ShouldPrintBeforePass(PassID))
1302       addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1303                                    + P->getPassName() + " ***"));
1304
1305   addImpl(P);
1306
1307   if (P->getPassKind() == PT_Function)
1308     if (ShouldPrintAfterPass(PassID))
1309       addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1310                                    + P->getPassName() + " ***"));
1311 }
1312
1313 /// run - Execute all of the passes scheduled for execution.  Keep
1314 /// track of whether any of the passes modifies the function, and if
1315 /// so, return true.
1316 ///
1317 bool FunctionPassManager::run(Function &F) {
1318   if (F.isMaterializable()) {
1319     std::string errstr;
1320     if (F.Materialize(&errstr))
1321       report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1322   }
1323   return FPM->run(F);
1324 }
1325
1326
1327 /// doInitialization - Run all of the initializers for the function passes.
1328 ///
1329 bool FunctionPassManager::doInitialization() {
1330   return FPM->doInitialization(*M);
1331 }
1332
1333 /// doFinalization - Run all of the finalizers for the function passes.
1334 ///
1335 bool FunctionPassManager::doFinalization() {
1336   return FPM->doFinalization(*M);
1337 }
1338
1339 //===----------------------------------------------------------------------===//
1340 // FunctionPassManagerImpl implementation
1341 //
1342 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1343   bool Changed = false;
1344
1345   dumpArguments();
1346   dumpPasses();
1347
1348   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1349     Changed |= getContainedManager(Index)->doInitialization(M);
1350
1351   return Changed;
1352 }
1353
1354 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1355   bool Changed = false;
1356
1357   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1358     Changed |= getContainedManager(Index)->doFinalization(M);
1359
1360   return Changed;
1361 }
1362
1363 /// cleanup - After running all passes, clean up pass manager cache.
1364 void FPPassManager::cleanup() {
1365  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1366     FunctionPass *FP = getContainedPass(Index);
1367     AnalysisResolver *AR = FP->getResolver();
1368     assert(AR && "Analysis Resolver is not set");
1369     AR->clearAnalysisImpls();
1370  }
1371 }
1372
1373 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1374   if (!wasRun)
1375     return;
1376   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1377     FPPassManager *FPPM = getContainedManager(Index);
1378     for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1379       FPPM->getContainedPass(Index)->releaseMemory();
1380     }
1381   }
1382   wasRun = false;
1383 }
1384
1385 // Execute all the passes managed by this top level manager.
1386 // Return true if any function is modified by a pass.
1387 bool FunctionPassManagerImpl::run(Function &F) {
1388   bool Changed = false;
1389   TimingInfo::createTheTimeInfo();
1390
1391   initializeAllAnalysisInfo();
1392   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1393     Changed |= getContainedManager(Index)->runOnFunction(F);
1394
1395   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1396     getContainedManager(Index)->cleanup();
1397
1398   wasRun = true;
1399   return Changed;
1400 }
1401
1402 //===----------------------------------------------------------------------===//
1403 // FPPassManager implementation
1404
1405 char FPPassManager::ID = 0;
1406 /// Print passes managed by this manager
1407 void FPPassManager::dumpPassStructure(unsigned Offset) {
1408   llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1409   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1410     FunctionPass *FP = getContainedPass(Index);
1411     FP->dumpPassStructure(Offset + 1);
1412     dumpLastUses(FP, Offset+1);
1413   }
1414 }
1415
1416
1417 /// Execute all of the passes scheduled for execution by invoking
1418 /// runOnFunction method.  Keep track of whether any of the passes modifies
1419 /// the function, and if so, return true.
1420 bool FPPassManager::runOnFunction(Function &F) {
1421   if (F.isDeclaration())
1422     return false;
1423
1424   bool Changed = false;
1425
1426   // Collect inherited analysis from Module level pass manager.
1427   populateInheritedAnalysis(TPM->activeStack);
1428
1429   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1430     FunctionPass *FP = getContainedPass(Index);
1431     bool LocalChanged = false;
1432
1433     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1434     dumpRequiredSet(FP);
1435
1436     initializeAnalysisImpl(FP);
1437
1438     {
1439       PassManagerPrettyStackEntry X(FP, F);
1440       TimeRegion PassTimer(getPassTimer(FP));
1441
1442       LocalChanged |= FP->runOnFunction(F);
1443     }
1444
1445     Changed |= LocalChanged;
1446     if (LocalChanged)
1447       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1448     dumpPreservedSet(FP);
1449
1450     verifyPreservedAnalysis(FP);
1451     removeNotPreservedAnalysis(FP);
1452     recordAvailableAnalysis(FP);
1453     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1454   }
1455   return Changed;
1456 }
1457
1458 bool FPPassManager::runOnModule(Module &M) {
1459   bool Changed = doInitialization(M);
1460
1461   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1462     runOnFunction(*I);
1463
1464   return doFinalization(M) || Changed;
1465 }
1466
1467 bool FPPassManager::doInitialization(Module &M) {
1468   bool Changed = false;
1469
1470   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1471     Changed |= getContainedPass(Index)->doInitialization(M);
1472
1473   return Changed;
1474 }
1475
1476 bool FPPassManager::doFinalization(Module &M) {
1477   bool Changed = false;
1478
1479   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1480     Changed |= getContainedPass(Index)->doFinalization(M);
1481
1482   return Changed;
1483 }
1484
1485 //===----------------------------------------------------------------------===//
1486 // MPPassManager implementation
1487
1488 /// Execute all of the passes scheduled for execution by invoking
1489 /// runOnModule method.  Keep track of whether any of the passes modifies
1490 /// the module, and if so, return true.
1491 bool
1492 MPPassManager::runOnModule(Module &M) {
1493   bool Changed = false;
1494
1495   // Initialize on-the-fly passes
1496   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1497        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1498        I != E; ++I) {
1499     FunctionPassManagerImpl *FPP = I->second;
1500     Changed |= FPP->doInitialization(M);
1501   }
1502
1503   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1504     ModulePass *MP = getContainedPass(Index);
1505     bool LocalChanged = false;
1506
1507     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1508     dumpRequiredSet(MP);
1509
1510     initializeAnalysisImpl(MP);
1511
1512     {
1513       PassManagerPrettyStackEntry X(MP, M);
1514       TimeRegion PassTimer(getPassTimer(MP));
1515
1516       LocalChanged |= MP->runOnModule(M);
1517     }
1518
1519     Changed |= LocalChanged;
1520     if (LocalChanged)
1521       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1522                    M.getModuleIdentifier());
1523     dumpPreservedSet(MP);
1524
1525     verifyPreservedAnalysis(MP);
1526     removeNotPreservedAnalysis(MP);
1527     recordAvailableAnalysis(MP);
1528     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1529   }
1530
1531   // Finalize on-the-fly passes
1532   for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1533        I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1534        I != E; ++I) {
1535     FunctionPassManagerImpl *FPP = I->second;
1536     // We don't know when is the last time an on-the-fly pass is run,
1537     // so we need to releaseMemory / finalize here
1538     FPP->releaseMemoryOnTheFly();
1539     Changed |= FPP->doFinalization(M);
1540   }
1541   return Changed;
1542 }
1543
1544 /// Add RequiredPass into list of lower level passes required by pass P.
1545 /// RequiredPass is run on the fly by Pass Manager when P requests it
1546 /// through getAnalysis interface.
1547 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1548   assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1549          "Unable to handle Pass that requires lower level Analysis pass");
1550   assert((P->getPotentialPassManagerType() <
1551           RequiredPass->getPotentialPassManagerType()) &&
1552          "Unable to handle Pass that requires lower level Analysis pass");
1553
1554   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1555   if (!FPP) {
1556     FPP = new FunctionPassManagerImpl(0);
1557     // FPP is the top level manager.
1558     FPP->setTopLevelManager(FPP);
1559
1560     OnTheFlyManagers[P] = FPP;
1561   }
1562   FPP->add(RequiredPass);
1563
1564   // Register P as the last user of RequiredPass.
1565   SmallVector<Pass *, 12> LU;
1566   LU.push_back(RequiredPass);
1567   FPP->setLastUser(LU,  P);
1568 }
1569
1570 /// Return function pass corresponding to PassInfo PI, that is
1571 /// required by module pass MP. Instantiate analysis pass, by using
1572 /// its runOnFunction() for function F.
1573 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1574   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1575   assert(FPP && "Unable to find on the fly pass");
1576
1577   FPP->releaseMemoryOnTheFly();
1578   FPP->run(F);
1579   return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1580 }
1581
1582
1583 //===----------------------------------------------------------------------===//
1584 // PassManagerImpl implementation
1585 //
1586 /// run - Execute all of the passes scheduled for execution.  Keep track of
1587 /// whether any of the passes modifies the module, and if so, return true.
1588 bool PassManagerImpl::run(Module &M) {
1589   bool Changed = false;
1590   TimingInfo::createTheTimeInfo();
1591
1592   dumpArguments();
1593   dumpPasses();
1594
1595   initializeAllAnalysisInfo();
1596   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1597     Changed |= getContainedManager(Index)->runOnModule(M);
1598   return Changed;
1599 }
1600
1601 //===----------------------------------------------------------------------===//
1602 // PassManager implementation
1603
1604 /// Create new pass manager
1605 PassManager::PassManager() {
1606   PM = new PassManagerImpl(0);
1607   // PM is the top level manager
1608   PM->setTopLevelManager(PM);
1609 }
1610
1611 PassManager::~PassManager() {
1612   delete PM;
1613 }
1614
1615 /// addImpl - Add a pass to the queue of passes to run, without
1616 /// checking whether to add a printer pass.
1617 void PassManager::addImpl(Pass *P) {
1618   PM->add(P);
1619 }
1620
1621 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1622 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1623 /// will be destroyed as well, so there is no need to delete the pass.  This
1624 /// implies that all passes MUST be allocated with 'new'.
1625 void PassManager::add(Pass *P) {
1626   const void* PassID = P->getPassID();
1627   if (ShouldPrintBeforePass(PassID))
1628     addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1629                                  + P->getPassName() + " ***"));
1630
1631   addImpl(P);
1632
1633   if (ShouldPrintAfterPass(PassID))
1634     addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1635                                  + P->getPassName() + " ***"));
1636 }
1637
1638 /// run - Execute all of the passes scheduled for execution.  Keep track of
1639 /// whether any of the passes modifies the module, and if so, return true.
1640 bool PassManager::run(Module &M) {
1641   return PM->run(M);
1642 }
1643
1644 //===----------------------------------------------------------------------===//
1645 // TimingInfo Class - This class is used to calculate information about the
1646 // amount of time each pass takes to execute.  This only happens with
1647 // -time-passes is enabled on the command line.
1648 //
1649 bool llvm::TimePassesIsEnabled = false;
1650 static cl::opt<bool,true>
1651 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1652             cl::desc("Time each pass, printing elapsed time for each on exit"));
1653
1654 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1655 // a non null value (if the -time-passes option is enabled) or it leaves it
1656 // null.  It may be called multiple times.
1657 void TimingInfo::createTheTimeInfo() {
1658   if (!TimePassesIsEnabled || TheTimeInfo) return;
1659
1660   // Constructed the first time this is called, iff -time-passes is enabled.
1661   // This guarantees that the object will be constructed before static globals,
1662   // thus it will be destroyed before them.
1663   static ManagedStatic<TimingInfo> TTI;
1664   TheTimeInfo = &*TTI;
1665 }
1666
1667 /// If TimingInfo is enabled then start pass timer.
1668 Timer *llvm::getPassTimer(Pass *P) {
1669   if (TheTimeInfo)
1670     return TheTimeInfo->getPassTimer(P);
1671   return 0;
1672 }
1673
1674 //===----------------------------------------------------------------------===//
1675 // PMStack implementation
1676 //
1677
1678 // Pop Pass Manager from the stack and clear its analysis info.
1679 void PMStack::pop() {
1680
1681   PMDataManager *Top = this->top();
1682   Top->initializeAnalysisInfo();
1683
1684   S.pop_back();
1685 }
1686
1687 // Push PM on the stack and set its top level manager.
1688 void PMStack::push(PMDataManager *PM) {
1689   assert(PM && "Unable to push. Pass Manager expected");
1690
1691   if (!this->empty()) {
1692     PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1693
1694     assert(TPM && "Unable to find top level manager");
1695     TPM->addIndirectPassManager(PM);
1696     PM->setTopLevelManager(TPM);
1697   }
1698
1699   S.push_back(PM);
1700 }
1701
1702 // Dump content of the pass manager stack.
1703 void PMStack::dump() const {
1704   for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1705          E = S.end(); I != E; ++I)
1706     printf("%s ", (*I)->getAsPass()->getPassName());
1707
1708   if (!S.empty())
1709     printf("\n");
1710 }
1711
1712 /// Find appropriate Module Pass Manager in the PM Stack and
1713 /// add self into that manager.
1714 void ModulePass::assignPassManager(PMStack &PMS,
1715                                    PassManagerType PreferredType) {
1716   // Find Module Pass Manager
1717   while (!PMS.empty()) {
1718     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1719     if (TopPMType == PreferredType)
1720       break; // We found desired pass manager
1721     else if (TopPMType > PMT_ModulePassManager)
1722       PMS.pop();    // Pop children pass managers
1723     else
1724       break;
1725   }
1726   assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1727   PMS.top()->add(this);
1728 }
1729
1730 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1731 /// in the PM Stack and add self into that manager.
1732 void FunctionPass::assignPassManager(PMStack &PMS,
1733                                      PassManagerType PreferredType) {
1734
1735   // Find Module Pass Manager
1736   while (!PMS.empty()) {
1737     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1738       PMS.pop();
1739     else
1740       break;
1741   }
1742
1743   // Create new Function Pass Manager if needed.
1744   FPPassManager *FPP;
1745   if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1746     FPP = (FPPassManager *)PMS.top();
1747   } else {
1748     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1749     PMDataManager *PMD = PMS.top();
1750
1751     // [1] Create new Function Pass Manager
1752     FPP = new FPPassManager(PMD->getDepth() + 1);
1753     FPP->populateInheritedAnalysis(PMS);
1754
1755     // [2] Set up new manager's top level manager
1756     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1757     TPM->addIndirectPassManager(FPP);
1758
1759     // [3] Assign manager to manage this new manager. This may create
1760     // and push new managers into PMS
1761     FPP->assignPassManager(PMS, PMD->getPassManagerType());
1762
1763     // [4] Push new manager into PMS
1764     PMS.push(FPP);
1765   }
1766
1767   // Assign FPP as the manager of this pass.
1768   FPP->add(this);
1769 }
1770
1771 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1772 /// in the PM Stack and add self into that manager.
1773 void BasicBlockPass::assignPassManager(PMStack &PMS,
1774                                        PassManagerType PreferredType) {
1775   BBPassManager *BBP;
1776
1777   // Basic Pass Manager is a leaf pass manager. It does not handle
1778   // any other pass manager.
1779   if (!PMS.empty() &&
1780       PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1781     BBP = (BBPassManager *)PMS.top();
1782   } else {
1783     // If leaf manager is not Basic Block Pass manager then create new
1784     // basic Block Pass manager.
1785     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1786     PMDataManager *PMD = PMS.top();
1787
1788     // [1] Create new Basic Block Manager
1789     BBP = new BBPassManager(PMD->getDepth() + 1);
1790
1791     // [2] Set up new manager's top level manager
1792     // Basic Block Pass Manager does not live by itself
1793     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1794     TPM->addIndirectPassManager(BBP);
1795
1796     // [3] Assign manager to manage this new manager. This may create
1797     // and push new managers into PMS
1798     BBP->assignPassManager(PMS, PreferredType);
1799
1800     // [4] Push new manager into PMS
1801     PMS.push(BBP);
1802   }
1803
1804   // Assign BBP as the manager of this pass.
1805   BBP->add(this);
1806 }
1807
1808 PassManagerBase::~PassManagerBase() {}