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