Avoid constructing std::strings unless pass debugging is ON.
[oota-llvm.git] / lib / VMCore / PassManager.cpp
1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source 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/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include <algorithm>
23 #include <vector>
24 #include <map>
25
26 // See PassManagers.h for Pass Manager infrastructure overview.
27
28 namespace llvm {
29
30 //===----------------------------------------------------------------------===//
31 // Pass debugging information.  Often it is useful to find out what pass is
32 // running when a crash occurs in a utility.  When this library is compiled with
33 // debugging on, a command line option (--debug-pass) is enabled that causes the
34 // pass name to be printed before it executes.
35 //
36
37 // Different debug levels that can be enabled...
38 enum PassDebugLevel {
39   None, Arguments, Structure, Executions, Details
40 };
41
42 static cl::opt<enum PassDebugLevel>
43 PassDebugging("debug-pass", cl::Hidden,
44                   cl::desc("Print PassManager debugging information"),
45                   cl::values(
46   clEnumVal(None      , "disable debug output"),
47   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
48   clEnumVal(Structure , "print pass structure before run()"),
49   clEnumVal(Executions, "print pass name before it is executed"),
50   clEnumVal(Details   , "print pass details when it is executed"),
51                              clEnumValEnd));
52 } // End of llvm namespace
53
54 namespace {
55
56 //===----------------------------------------------------------------------===//
57 // BBPassManager
58 //
59 /// BBPassManager manages BasicBlockPass. It batches all the
60 /// pass together and sequence them to process one basic block before
61 /// processing next basic block.
62 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager, 
63                                         public FunctionPass {
64
65 public:
66   BBPassManager(int Depth) : PMDataManager(Depth) { }
67
68   /// Execute all of the passes scheduled for execution.  Keep track of
69   /// whether any of the passes modifies the function, and if so, return true.
70   bool runOnFunction(Function &F);
71
72   /// Pass Manager itself does not invalidate any analysis info.
73   void getAnalysisUsage(AnalysisUsage &Info) const {
74     Info.setPreservesAll();
75   }
76
77   bool doInitialization(Module &M);
78   bool doInitialization(Function &F);
79   bool doFinalization(Module &M);
80   bool doFinalization(Function &F);
81
82   virtual const char *getPassName() const {
83     return "BasicBlock Pass  Manager";
84   }
85
86   // Print passes managed by this manager
87   void dumpPassStructure(unsigned Offset) {
88     llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
89     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
90       BasicBlockPass *BP = getContainedPass(Index);
91       BP->dumpPassStructure(Offset + 1);
92       dumpLastUses(BP, Offset+1);
93     }
94   }
95
96   BasicBlockPass *getContainedPass(unsigned N) {
97     assert ( N < PassVector.size() && "Pass number out of range!");
98     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
99     return BP;
100   }
101
102   virtual PassManagerType getPassManagerType() const { 
103     return PMT_BasicBlockPassManager; 
104   }
105 };
106
107 }
108
109 namespace llvm {
110
111 //===----------------------------------------------------------------------===//
112 // FunctionPassManagerImpl
113 //
114 /// FunctionPassManagerImpl manages FPPassManagers
115 class FunctionPassManagerImpl : public Pass,
116                                 public PMDataManager,
117                                 public PMTopLevelManager {
118 public:
119
120   FunctionPassManagerImpl(int Depth) : PMDataManager(Depth),
121                                        PMTopLevelManager(TLM_Function) { }
122
123   /// add - Add a pass to the queue of passes to run.  This passes ownership of
124   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
125   /// will be destroyed as well, so there is no need to delete the pass.  This
126   /// implies that all passes MUST be allocated with 'new'.
127   void add(Pass *P) {
128     schedulePass(P);
129   }
130  
131   /// run - Execute all of the passes scheduled for execution.  Keep track of
132   /// whether any of the passes modifies the module, and if so, return true.
133   bool run(Function &F);
134
135   /// doInitialization - Run all of the initializers for the function passes.
136   ///
137   bool doInitialization(Module &M);
138   
139   /// doFinalization - Run all of the initializers for the function passes.
140   ///
141   bool doFinalization(Module &M);
142
143   /// Pass Manager itself does not invalidate any analysis info.
144   void getAnalysisUsage(AnalysisUsage &Info) const {
145     Info.setPreservesAll();
146   }
147
148   inline void addTopLevelPass(Pass *P) {
149
150     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
151       
152       // P is a immutable pass and it will be managed by this
153       // top level manager. Set up analysis resolver to connect them.
154       AnalysisResolver *AR = new AnalysisResolver(*this);
155       P->setResolver(AR);
156       initializeAnalysisImpl(P);
157       addImmutablePass(IP);
158       recordAvailableAnalysis(IP);
159     } else {
160       P->assignPassManager(activeStack);
161       activeStack.handleLastUserOverflow();
162     }
163
164   }
165
166   FPPassManager *getContainedManager(unsigned N) {
167     assert ( N < PassManagers.size() && "Pass number out of range!");
168     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
169     return FP;
170   }
171
172 };
173
174 //===----------------------------------------------------------------------===//
175 // MPPassManager
176 //
177 /// MPPassManager manages ModulePasses and function pass managers.
178 /// It batches all Module passes  passes and function pass managers together and
179 /// sequence them to process one module.
180 class MPPassManager : public Pass, public PMDataManager {
181  
182 public:
183   MPPassManager(int Depth) : PMDataManager(Depth) { }
184   
185   /// run - Execute all of the passes scheduled for execution.  Keep track of
186   /// whether any of the passes modifies the module, and if so, return true.
187   bool runOnModule(Module &M);
188
189   /// Pass Manager itself does not invalidate any analysis info.
190   void getAnalysisUsage(AnalysisUsage &Info) const {
191     Info.setPreservesAll();
192   }
193
194   virtual const char *getPassName() const {
195     return "Module Pass Manager";
196   }
197
198   // Print passes managed by this manager
199   void dumpPassStructure(unsigned Offset) {
200     llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
201     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
202       ModulePass *MP = getContainedPass(Index);
203       MP->dumpPassStructure(Offset + 1);
204       dumpLastUses(MP, Offset+1);
205     }
206   }
207
208   ModulePass *getContainedPass(unsigned N) {
209     assert ( N < PassVector.size() && "Pass number out of range!");
210     ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
211     return MP;
212   }
213
214   virtual PassManagerType getPassManagerType() const { 
215     return PMT_ModulePassManager; 
216   }
217 };
218
219 //===----------------------------------------------------------------------===//
220 // PassManagerImpl
221 //
222 /// PassManagerImpl manages MPPassManagers
223 class PassManagerImpl : public Pass,
224                         public PMDataManager,
225                         public PMTopLevelManager {
226
227 public:
228
229   PassManagerImpl(int Depth) : PMDataManager(Depth),
230                                PMTopLevelManager(TLM_Pass) { }
231
232   /// add - Add a pass to the queue of passes to run.  This passes ownership of
233   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
234   /// will be destroyed as well, so there is no need to delete the pass.  This
235   /// implies that all passes MUST be allocated with 'new'.
236   void add(Pass *P) {
237     schedulePass(P);
238   }
239  
240   /// run - Execute all of the passes scheduled for execution.  Keep track of
241   /// whether any of the passes modifies the module, and if so, return true.
242   bool run(Module &M);
243
244   /// Pass Manager itself does not invalidate any analysis info.
245   void getAnalysisUsage(AnalysisUsage &Info) const {
246     Info.setPreservesAll();
247   }
248
249   inline void addTopLevelPass(Pass *P) {
250
251     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
252       
253       // P is a immutable pass and it will be managed by this
254       // top level manager. Set up analysis resolver to connect them.
255       AnalysisResolver *AR = new AnalysisResolver(*this);
256       P->setResolver(AR);
257       initializeAnalysisImpl(P);
258       addImmutablePass(IP);
259       recordAvailableAnalysis(IP);
260     } else {
261       P->assignPassManager(activeStack);
262       activeStack.handleLastUserOverflow();
263     }
264
265   }
266
267   MPPassManager *getContainedManager(unsigned N) {
268     assert ( N < PassManagers.size() && "Pass number out of range!");
269     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
270     return MP;
271   }
272
273 };
274
275 } // End of llvm namespace
276
277 namespace {
278
279 //===----------------------------------------------------------------------===//
280 // TimingInfo Class - This class is used to calculate information about the
281 // amount of time each pass takes to execute.  This only happens when
282 // -time-passes is enabled on the command line.
283 //
284
285 class VISIBILITY_HIDDEN TimingInfo {
286   std::map<Pass*, Timer> TimingData;
287   TimerGroup TG;
288
289 public:
290   // Use 'create' member to get this.
291   TimingInfo() : TG("... Pass execution timing report ...") {}
292   
293   // TimingDtor - Print out information about timing information
294   ~TimingInfo() {
295     // Delete all of the timers...
296     TimingData.clear();
297     // TimerGroup is deleted next, printing the report.
298   }
299
300   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
301   // to a non null value (if the -time-passes option is enabled) or it leaves it
302   // null.  It may be called multiple times.
303   static void createTheTimeInfo();
304
305   void passStarted(Pass *P) {
306
307     if (dynamic_cast<PMDataManager *>(P)) 
308       return;
309
310     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
311     if (I == TimingData.end())
312       I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
313     I->second.startTimer();
314   }
315   void passEnded(Pass *P) {
316
317     if (dynamic_cast<PMDataManager *>(P)) 
318       return;
319
320     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
321     assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
322     I->second.stopTimer();
323   }
324 };
325
326 static TimingInfo *TheTimeInfo;
327
328 } // End of anon namespace
329
330 //===----------------------------------------------------------------------===//
331 // PMTopLevelManager implementation
332
333 /// Initialize top level manager. Create first pass manager.
334 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
335
336   if (t == TLM_Pass) {
337     MPPassManager *MPP = new MPPassManager(1);
338     MPP->setTopLevelManager(this);
339     addPassManager(MPP);
340     activeStack.push(MPP);
341   } 
342   else if (t == TLM_Function) {
343     FPPassManager *FPP = new FPPassManager(1);
344     FPP->setTopLevelManager(this);
345     addPassManager(FPP);
346     activeStack.push(FPP);
347   } 
348 }
349
350 /// Set pass P as the last user of the given analysis passes.
351 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses, 
352                                     Pass *P) {
353
354   for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
355          E = AnalysisPasses.end(); I != E; ++I) {
356     Pass *AP = *I;
357     LastUser[AP] = P;
358     // If AP is the last user of other passes then make P last user of
359     // such passes.
360     for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
361            LUE = LastUser.end(); LUI != LUE; ++LUI) {
362       if (LUI->second == AP)
363         LastUser[LUI->first] = P;
364     }
365   }
366 }
367
368 /// Collect passes whose last user is P
369 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
370                                             Pass *P) {
371    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
372           LUE = LastUser.end(); LUI != LUE; ++LUI)
373       if (LUI->second == P)
374         LastUses.push_back(LUI->first);
375 }
376
377 /// Schedule pass P for execution. Make sure that passes required by
378 /// P are run before P is run. Update analysis info maintained by
379 /// the manager. Remove dead passes. This is a recursive function.
380 void PMTopLevelManager::schedulePass(Pass *P) {
381
382   // TODO : Allocate function manager for this pass, other wise required set
383   // may be inserted into previous function manager
384
385   // If this Analysis is already requested by one of the previous pass
386   // and it is still available then do not insert new pass in the queue again.
387   if (findAnalysisPass(P->getPassInfo()))
388       return;
389
390   AnalysisUsage AnUsage;
391   P->getAnalysisUsage(AnUsage);
392   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
393   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
394          E = RequiredSet.end(); I != E; ++I) {
395
396     Pass *AnalysisPass = findAnalysisPass(*I);
397     if (!AnalysisPass) {
398       // Schedule this analysis run first.
399       AnalysisPass = (*I)->createPass();
400       schedulePass(AnalysisPass);
401     }
402   }
403
404   // Now all required passes are available.
405   addTopLevelPass(P);
406 }
407
408 /// Find the pass that implements Analysis AID. Search immutable
409 /// passes and all pass managers. If desired pass is not found
410 /// then return NULL.
411 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
412
413   Pass *P = NULL;
414   // Check pass managers
415   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
416          E = PassManagers.end(); P == NULL && I != E; ++I) {
417     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
418     assert(PMD && "This is not a PassManager");
419     P = PMD->findAnalysisPass(AID, false);
420   }
421
422   // Check other pass managers
423   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
424          E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
425     P = (*I)->findAnalysisPass(AID, false);
426
427   for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
428          E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
429     const PassInfo *PI = (*I)->getPassInfo();
430     if (PI == AID)
431       P = *I;
432
433     // If Pass not found then check the interfaces implemented by Immutable Pass
434     if (!P) {
435       const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
436       if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
437         P = *I;
438     }
439   }
440
441   return P;
442 }
443
444 // Print passes managed by this top level manager.
445 void PMTopLevelManager::dumpPasses() const {
446
447   if (PassDebugging < Structure)
448     return;
449
450   // Print out the immutable passes
451   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
452     ImmutablePasses[i]->dumpPassStructure(0);
453   }
454   
455   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
456          E = PassManagers.end(); I != E; ++I)
457     (*I)->dumpPassStructure(1);
458 }
459
460 void PMTopLevelManager::dumpArguments() const {
461
462   if (PassDebugging < Arguments)
463     return;
464
465   cerr << "Pass Arguments: ";
466   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
467          E = PassManagers.end(); I != E; ++I) {
468     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
469     assert(PMD && "This is not a PassManager");
470     PMD->dumpPassArguments();
471   }
472   cerr << "\n";
473 }
474
475 void PMTopLevelManager::initializeAllAnalysisInfo() {
476   
477   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
478          E = PassManagers.end(); I != E; ++I) {
479     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
480     assert(PMD && "This is not a PassManager");
481     PMD->initializeAnalysisInfo();
482   }
483   
484   // Initailize other pass managers
485   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
486          E = IndirectPassManagers.end(); I != E; ++I)
487     (*I)->initializeAnalysisInfo();
488 }
489
490 /// Destructor
491 PMTopLevelManager::~PMTopLevelManager() {
492   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
493          E = PassManagers.end(); I != E; ++I)
494     delete *I;
495   
496   for (std::vector<ImmutablePass *>::iterator
497          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
498     delete *I;
499   
500   PassManagers.clear();
501 }
502
503 //===----------------------------------------------------------------------===//
504 // PMDataManager implementation
505
506 /// Return true IFF pass P's required analysis set does not required new
507 /// manager.
508 bool PMDataManager::manageablePass(Pass *P) {
509
510   // TODO 
511   // If this pass is not preserving information that is required by a
512   // pass maintained by higher level pass manager then do not insert
513   // this pass into current manager. Use new manager. For example,
514   // For example, If FunctionPass F is not preserving ModulePass Info M1
515   // that is used by another ModulePass M2 then do not insert F in
516   // current function pass manager.
517   return true;
518 }
519
520 /// Augement AvailableAnalysis by adding analysis made available by pass P.
521 void PMDataManager::recordAvailableAnalysis(Pass *P) {
522                                                 
523   if (const PassInfo *PI = P->getPassInfo()) {
524     AvailableAnalysis[PI] = P;
525
526     //This pass is the current implementation of all of the interfaces it
527     //implements as well.
528     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
529     for (unsigned i = 0, e = II.size(); i != e; ++i)
530       AvailableAnalysis[II[i]] = P;
531   }
532 }
533
534 /// Remove Analyss not preserved by Pass P
535 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
536   AnalysisUsage AnUsage;
537   P->getAnalysisUsage(AnUsage);
538
539   if (AnUsage.getPreservesAll())
540     return;
541
542   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
543   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
544          E = AvailableAnalysis.end(); I != E; ) {
545     std::map<AnalysisID, Pass*>::iterator Info = I++;
546     if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
547         PreservedSet.end()) {
548       // Remove this analysis
549       if (!dynamic_cast<ImmutablePass*>(Info->second))
550         AvailableAnalysis.erase(Info);
551     }
552   }
553 }
554
555 /// Remove analysis passes that are not used any longer
556 void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
557                                      enum PassDebuggingString DBG_STR) {
558
559   std::vector<Pass *> DeadPasses;
560   TPM->collectLastUses(DeadPasses, P);
561
562   for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
563          E = DeadPasses.end(); I != E; ++I) {
564
565     dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
566
567     if (TheTimeInfo) TheTimeInfo->passStarted(*I);
568     (*I)->releaseMemory();
569     if (TheTimeInfo) TheTimeInfo->passEnded(*I);
570
571     std::map<AnalysisID, Pass*>::iterator Pos = 
572       AvailableAnalysis.find((*I)->getPassInfo());
573     
574     // It is possible that pass is already removed from the AvailableAnalysis
575     if (Pos != AvailableAnalysis.end())
576       AvailableAnalysis.erase(Pos);
577   }
578 }
579
580 /// Add pass P into the PassVector. Update 
581 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
582 void PMDataManager::add(Pass *P, 
583                         bool ProcessAnalysis) {
584
585   // This manager is going to manage pass P. Set up analysis resolver
586   // to connect them.
587   AnalysisResolver *AR = new AnalysisResolver(*this);
588   P->setResolver(AR);
589
590   if (ProcessAnalysis) {
591
592     // At the moment, this pass is the last user of all required passes.
593     std::vector<Pass *> LastUses;
594     std::vector<Pass *> RequiredPasses;
595     unsigned PDepth = this->getDepth();
596
597     collectRequiredAnalysisPasses(RequiredPasses, P);
598     for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
599            E = RequiredPasses.end(); I != E; ++I) {
600       Pass *PRequired = *I;
601       unsigned RDepth = 0;
602
603       PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
604       RDepth = DM.getDepth();
605
606       if (PDepth == RDepth)
607         LastUses.push_back(PRequired);
608       else if (PDepth >  RDepth) {
609         // Let the parent claim responsibility of last use
610         TransferLastUses.push_back(PRequired);
611       } else {
612         // Note : This feature is not yet implemented
613         assert (0 && 
614                 "Unable to handle Pass that requires lower level Analysis pass");
615       }
616     }
617
618     // Set P as P's last user until someone starts using P.
619     // However, if P is a Pass Manager then it does not need
620     // to record its last user.
621     if (!dynamic_cast<PMDataManager *>(P))
622       LastUses.push_back(P);
623     TPM->setLastUser(LastUses, P);
624
625     // Take a note of analysis required and made available by this pass.
626     // Remove the analysis not preserved by this pass
627     removeNotPreservedAnalysis(P);
628     recordAvailableAnalysis(P);
629   }
630
631   // Add pass
632   PassVector.push_back(P);
633 }
634
635 /// Populate RequiredPasses with the analysis pass that are required by
636 /// pass P.
637 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
638                                                   Pass *P) {
639   AnalysisUsage AnUsage;
640   P->getAnalysisUsage(AnUsage);
641   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
642   for (std::vector<AnalysisID>::const_iterator 
643          I = RequiredSet.begin(), E = RequiredSet.end();
644        I != E; ++I) {
645     Pass *AnalysisPass = findAnalysisPass(*I, true);
646     assert (AnalysisPass && "Analysis pass is not available");
647     RP.push_back(AnalysisPass);
648   }
649
650   const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
651   for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
652          E = IDs.end(); I != E; ++I) {
653     Pass *AnalysisPass = findAnalysisPass(*I, true);
654     assert (AnalysisPass && "Analysis pass is not available");
655     RP.push_back(AnalysisPass);
656   }
657 }
658
659 // All Required analyses should be available to the pass as it runs!  Here
660 // we fill in the AnalysisImpls member of the pass so that it can
661 // successfully use the getAnalysis() method to retrieve the
662 // implementations it needs.
663 //
664 void PMDataManager::initializeAnalysisImpl(Pass *P) {
665   AnalysisUsage AnUsage;
666   P->getAnalysisUsage(AnUsage);
667  
668   for (std::vector<const PassInfo *>::const_iterator
669          I = AnUsage.getRequiredSet().begin(),
670          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
671     Pass *Impl = findAnalysisPass(*I, true);
672     if (Impl == 0)
673       assert(0 && "Analysis used but not available!");
674     AnalysisResolver *AR = P->getResolver();
675     AR->addAnalysisImplsPair(*I, Impl);
676   }
677 }
678
679 /// Find the pass that implements Analysis AID. If desired pass is not found
680 /// then return NULL.
681 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
682
683   // Check if AvailableAnalysis map has one entry.
684   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
685
686   if (I != AvailableAnalysis.end())
687     return I->second;
688
689   // Search Parents through TopLevelManager
690   if (SearchParent)
691     return TPM->findAnalysisPass(AID);
692   
693   return NULL;
694 }
695
696 // Print list of passes that are last used by P.
697 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
698
699   std::vector<Pass *> LUses;
700   
701   assert (TPM && "Top Level Manager is missing");
702   TPM->collectLastUses(LUses, P);
703   
704   for (std::vector<Pass *>::iterator I = LUses.begin(),
705          E = LUses.end(); I != E; ++I) {
706     llvm::cerr << "--" << std::string(Offset*2, ' ');
707     (*I)->dumpPassStructure(0);
708   }
709 }
710
711 void PMDataManager::dumpPassArguments() const {
712   for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
713         E = PassVector.end(); I != E; ++I) {
714     if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
715       PMD->dumpPassArguments();
716     else
717       if (const PassInfo *PI = (*I)->getPassInfo())
718         if (!PI->isAnalysisGroup())
719           cerr << " -" << PI->getPassArgument();
720   }
721 }
722
723 void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
724                                   enum PassDebuggingString S2,
725                                   std::string Msg) {
726   if (PassDebugging < Executions)
727     return;
728   cerr << (void*)this << std::string(getDepth()*2+1, ' ');
729   switch (S1) {
730   case EXECUTION_MSG:
731     cerr << "Executing Pass '" << P->getPassName();
732     break;
733   case MODIFICATION_MSG:
734     cerr << "' Made Modification '" << P->getPassName();
735     break;
736   case FREEING_MSG:
737     cerr << " Freeing Pass '" << P->getPassName();
738     break;
739   default:
740     break;
741   }
742   switch (S2) {
743   case ON_BASICBLOCK_MSG:
744     cerr << "' on BasicBlock '" << Msg << "...\n";
745     break;
746   case ON_FUNCTION_MSG:
747     cerr << "' on Function '" << Msg << "...\n";
748     break;
749   case ON_MODULE_MSG:
750     cerr << "' on Module '"  << Msg << "...\n";
751     break;
752   case ON_LOOP_MSG:
753     cerr << "' on Loop " << Msg << "...\n";
754     break;
755   case ON_CG_MSG:
756     cerr << "' on Call Graph " << Msg << "...\n";
757     break;
758   default:
759     break;
760   }
761 }
762
763 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
764                                         const std::vector<AnalysisID> &Set) 
765   const {
766   if (PassDebugging >= Details && !Set.empty()) {
767     cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
768       for (unsigned i = 0; i != Set.size(); ++i) {
769         if (i) cerr << ",";
770         cerr << " " << Set[i]->getPassName();
771       }
772       cerr << "\n";
773   }
774 }
775
776 // Destructor
777 PMDataManager::~PMDataManager() {
778   
779   for (std::vector<Pass *>::iterator I = PassVector.begin(),
780          E = PassVector.end(); I != E; ++I)
781     delete *I;
782   
783   PassVector.clear();
784 }
785
786 //===----------------------------------------------------------------------===//
787 // NOTE: Is this the right place to define this method ?
788 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
789 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
790   return PM.findAnalysisPass(ID, dir);
791 }
792
793 //===----------------------------------------------------------------------===//
794 // BBPassManager implementation
795
796 /// Execute all of the passes scheduled for execution by invoking 
797 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
798 /// the function, and if so, return true.
799 bool
800 BBPassManager::runOnFunction(Function &F) {
801
802   if (F.isDeclaration())
803     return false;
804
805   bool Changed = doInitialization(F);
806
807   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
808     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
809       BasicBlockPass *BP = getContainedPass(Index);
810       AnalysisUsage AnUsage;
811       BP->getAnalysisUsage(AnUsage);
812
813       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
814       dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
815
816       initializeAnalysisImpl(BP);
817
818       if (TheTimeInfo) TheTimeInfo->passStarted(BP);
819       Changed |= BP->runOnBasicBlock(*I);
820       if (TheTimeInfo) TheTimeInfo->passEnded(BP);
821
822       if (Changed) 
823         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
824       dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
825
826       removeNotPreservedAnalysis(BP);
827       recordAvailableAnalysis(BP);
828       removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
829                        
830     }
831   return Changed |= doFinalization(F);
832 }
833
834 // Implement doInitialization and doFinalization
835 inline bool BBPassManager::doInitialization(Module &M) {
836   bool Changed = false;
837
838   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
839     BasicBlockPass *BP = getContainedPass(Index);
840     Changed |= BP->doInitialization(M);
841   }
842
843   return Changed;
844 }
845
846 inline bool BBPassManager::doFinalization(Module &M) {
847   bool Changed = false;
848
849   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
850     BasicBlockPass *BP = getContainedPass(Index);
851     Changed |= BP->doFinalization(M);
852   }
853
854   return Changed;
855 }
856
857 inline bool BBPassManager::doInitialization(Function &F) {
858   bool Changed = false;
859
860   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
861     BasicBlockPass *BP = getContainedPass(Index);
862     Changed |= BP->doInitialization(F);
863   }
864
865   return Changed;
866 }
867
868 inline bool BBPassManager::doFinalization(Function &F) {
869   bool Changed = false;
870
871   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
872     BasicBlockPass *BP = getContainedPass(Index);
873     Changed |= BP->doFinalization(F);
874   }
875
876   return Changed;
877 }
878
879
880 //===----------------------------------------------------------------------===//
881 // FunctionPassManager implementation
882
883 /// Create new Function pass manager
884 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
885   FPM = new FunctionPassManagerImpl(0);
886   // FPM is the top level manager.
887   FPM->setTopLevelManager(FPM);
888
889   PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
890   AnalysisResolver *AR = new AnalysisResolver(*PMD);
891   FPM->setResolver(AR);
892   
893   MP = P;
894 }
895
896 FunctionPassManager::~FunctionPassManager() {
897   delete FPM;
898 }
899
900 /// add - Add a pass to the queue of passes to run.  This passes
901 /// ownership of the Pass to the PassManager.  When the
902 /// PassManager_X is destroyed, the pass will be destroyed as well, so
903 /// there is no need to delete the pass. (TODO delete passes.)
904 /// This implies that all passes MUST be allocated with 'new'.
905 void FunctionPassManager::add(Pass *P) { 
906   FPM->add(P);
907 }
908
909 /// run - Execute all of the passes scheduled for execution.  Keep
910 /// track of whether any of the passes modifies the function, and if
911 /// so, return true.
912 ///
913 bool FunctionPassManager::run(Function &F) {
914   std::string errstr;
915   if (MP->materializeFunction(&F, &errstr)) {
916     cerr << "Error reading bytecode file: " << errstr << "\n";
917     abort();
918   }
919   return FPM->run(F);
920 }
921
922
923 /// doInitialization - Run all of the initializers for the function passes.
924 ///
925 bool FunctionPassManager::doInitialization() {
926   return FPM->doInitialization(*MP->getModule());
927 }
928
929 /// doFinalization - Run all of the initializers for the function passes.
930 ///
931 bool FunctionPassManager::doFinalization() {
932   return FPM->doFinalization(*MP->getModule());
933 }
934
935 //===----------------------------------------------------------------------===//
936 // FunctionPassManagerImpl implementation
937 //
938 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
939   bool Changed = false;
940
941   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
942     FPPassManager *FP = getContainedManager(Index);
943     Changed |= FP->doInitialization(M);
944   }
945
946   return Changed;
947 }
948
949 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
950   bool Changed = false;
951
952   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
953     FPPassManager *FP = getContainedManager(Index);
954     Changed |= FP->doFinalization(M);
955   }
956
957   return Changed;
958 }
959
960 // Execute all the passes managed by this top level manager.
961 // Return true if any function is modified by a pass.
962 bool FunctionPassManagerImpl::run(Function &F) {
963
964   bool Changed = false;
965
966   TimingInfo::createTheTimeInfo();
967
968   dumpArguments();
969   dumpPasses();
970
971   initializeAllAnalysisInfo();
972   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
973     FPPassManager *FP = getContainedManager(Index);
974     Changed |= FP->runOnFunction(F);
975   }
976   return Changed;
977 }
978
979 //===----------------------------------------------------------------------===//
980 // FPPassManager implementation
981
982 /// Print passes managed by this manager
983 void FPPassManager::dumpPassStructure(unsigned Offset) {
984   llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
985   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
986     FunctionPass *FP = getContainedPass(Index);
987     FP->dumpPassStructure(Offset + 1);
988     dumpLastUses(FP, Offset+1);
989   }
990 }
991
992
993 /// Execute all of the passes scheduled for execution by invoking 
994 /// runOnFunction method.  Keep track of whether any of the passes modifies 
995 /// the function, and if so, return true.
996 bool FPPassManager::runOnFunction(Function &F) {
997
998   bool Changed = false;
999
1000   if (F.isDeclaration())
1001     return false;
1002
1003   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1004     FunctionPass *FP = getContainedPass(Index);
1005
1006     AnalysisUsage AnUsage;
1007     FP->getAnalysisUsage(AnUsage);
1008
1009     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1010     dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1011
1012     initializeAnalysisImpl(FP);
1013
1014     if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1015     Changed |= FP->runOnFunction(F);
1016     if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1017
1018     if (Changed) 
1019       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1020     dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1021
1022     removeNotPreservedAnalysis(FP);
1023     recordAvailableAnalysis(FP);
1024     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1025   }
1026   return Changed;
1027 }
1028
1029 bool FPPassManager::runOnModule(Module &M) {
1030
1031   bool Changed = doInitialization(M);
1032
1033   for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1034     this->runOnFunction(*I);
1035
1036   return Changed |= doFinalization(M);
1037 }
1038
1039 inline bool FPPassManager::doInitialization(Module &M) {
1040   bool Changed = false;
1041
1042   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1043     FunctionPass *FP = getContainedPass(Index);
1044     Changed |= FP->doInitialization(M);
1045   }
1046
1047   return Changed;
1048 }
1049
1050 inline bool FPPassManager::doFinalization(Module &M) {
1051   bool Changed = false;
1052
1053   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1054     FunctionPass *FP = getContainedPass(Index);
1055     Changed |= FP->doFinalization(M);
1056   }
1057
1058   return Changed;
1059 }
1060
1061 //===----------------------------------------------------------------------===//
1062 // MPPassManager implementation
1063
1064 /// Execute all of the passes scheduled for execution by invoking 
1065 /// runOnModule method.  Keep track of whether any of the passes modifies 
1066 /// the module, and if so, return true.
1067 bool
1068 MPPassManager::runOnModule(Module &M) {
1069   bool Changed = false;
1070
1071   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1072     ModulePass *MP = getContainedPass(Index);
1073
1074     AnalysisUsage AnUsage;
1075     MP->getAnalysisUsage(AnUsage);
1076
1077     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1078     dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1079
1080     initializeAnalysisImpl(MP);
1081
1082     if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1083     Changed |= MP->runOnModule(M);
1084     if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1085
1086     if (Changed) 
1087       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1088                    M.getModuleIdentifier());
1089     dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1090       
1091     removeNotPreservedAnalysis(MP);
1092     recordAvailableAnalysis(MP);
1093     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1094   }
1095   return Changed;
1096 }
1097
1098 //===----------------------------------------------------------------------===//
1099 // PassManagerImpl implementation
1100 //
1101 /// run - Execute all of the passes scheduled for execution.  Keep track of
1102 /// whether any of the passes modifies the module, and if so, return true.
1103 bool PassManagerImpl::run(Module &M) {
1104
1105   bool Changed = false;
1106
1107   TimingInfo::createTheTimeInfo();
1108
1109   dumpArguments();
1110   dumpPasses();
1111
1112   initializeAllAnalysisInfo();
1113   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1114     MPPassManager *MP = getContainedManager(Index);
1115     Changed |= MP->runOnModule(M);
1116   }
1117   return Changed;
1118 }
1119
1120 //===----------------------------------------------------------------------===//
1121 // PassManager implementation
1122
1123 /// Create new pass manager
1124 PassManager::PassManager() {
1125   PM = new PassManagerImpl(0);
1126   // PM is the top level manager
1127   PM->setTopLevelManager(PM);
1128 }
1129
1130 PassManager::~PassManager() {
1131   delete PM;
1132 }
1133
1134 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1135 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1136 /// will be destroyed as well, so there is no need to delete the pass.  This
1137 /// implies that all passes MUST be allocated with 'new'.
1138 void 
1139 PassManager::add(Pass *P) {
1140   PM->add(P);
1141 }
1142
1143 /// run - Execute all of the passes scheduled for execution.  Keep track of
1144 /// whether any of the passes modifies the module, and if so, return true.
1145 bool
1146 PassManager::run(Module &M) {
1147   return PM->run(M);
1148 }
1149
1150 //===----------------------------------------------------------------------===//
1151 // TimingInfo Class - This class is used to calculate information about the
1152 // amount of time each pass takes to execute.  This only happens with
1153 // -time-passes is enabled on the command line.
1154 //
1155 bool llvm::TimePassesIsEnabled = false;
1156 static cl::opt<bool,true>
1157 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1158             cl::desc("Time each pass, printing elapsed time for each on exit"));
1159
1160 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1161 // a non null value (if the -time-passes option is enabled) or it leaves it
1162 // null.  It may be called multiple times.
1163 void TimingInfo::createTheTimeInfo() {
1164   if (!TimePassesIsEnabled || TheTimeInfo) return;
1165
1166   // Constructed the first time this is called, iff -time-passes is enabled.
1167   // This guarantees that the object will be constructed before static globals,
1168   // thus it will be destroyed before them.
1169   static ManagedStatic<TimingInfo> TTI;
1170   TheTimeInfo = &*TTI;
1171 }
1172
1173 /// If TimingInfo is enabled then start pass timer.
1174 void StartPassTimer(Pass *P) {
1175   if (TheTimeInfo) 
1176     TheTimeInfo->passStarted(P);
1177 }
1178
1179 /// If TimingInfo is enabled then stop pass timer.
1180 void StopPassTimer(Pass *P) {
1181   if (TheTimeInfo) 
1182     TheTimeInfo->passEnded(P);
1183 }
1184
1185 //===----------------------------------------------------------------------===//
1186 // PMStack implementation
1187 //
1188
1189 // Pop Pass Manager from the stack and clear its analysis info.
1190 void PMStack::pop() {
1191
1192   PMDataManager *Top = this->top();
1193   Top->initializeAnalysisInfo();
1194
1195   S.pop_back();
1196 }
1197
1198 // Push PM on the stack and set its top level manager.
1199 void PMStack::push(Pass *P) {
1200
1201   PMDataManager *Top = NULL;
1202   PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1203   assert (PM && "Unable to push. Pass Manager expected");
1204
1205   if (this->empty()) {
1206     Top = PM;
1207   } 
1208   else {
1209     Top = this->top();
1210     PMTopLevelManager *TPM = Top->getTopLevelManager();
1211
1212     assert (TPM && "Unable to find top level manager");
1213     TPM->addIndirectPassManager(PM);
1214     PM->setTopLevelManager(TPM);
1215   }
1216
1217   AnalysisResolver *AR = new AnalysisResolver(*Top);
1218   P->setResolver(AR);
1219
1220   S.push_back(PM);
1221 }
1222
1223 // Dump content of the pass manager stack.
1224 void PMStack::dump() {
1225   for(std::deque<PMDataManager *>::iterator I = S.begin(),
1226         E = S.end(); I != E; ++I) {
1227     Pass *P = dynamic_cast<Pass *>(*I);
1228     printf ("%s ", P->getPassName());
1229   }
1230   if (!S.empty())
1231     printf ("\n");
1232 }
1233
1234 // Walk Pass Manager stack and set LastUse markers if any
1235 // manager is transfering this priviledge to its parent manager
1236 void PMStack::handleLastUserOverflow() {
1237
1238   for(PMStack::iterator I = this->begin(), E = this->end(); I != E;) {
1239
1240     PMDataManager *Child = *I++;
1241     if (I != E) {
1242       PMDataManager *Parent = *I++;
1243       PMTopLevelManager *TPM = Parent->getTopLevelManager();
1244       std::vector<Pass *> &TLU = Child->getTransferredLastUses();
1245       if (!TLU.empty()) {
1246         Pass *P = dynamic_cast<Pass *>(Parent);
1247         TPM->setLastUser(TLU, P);
1248         TLU.clear();
1249       }
1250     }
1251   }
1252 }
1253
1254 /// Find appropriate Module Pass Manager in the PM Stack and
1255 /// add self into that manager. 
1256 void ModulePass::assignPassManager(PMStack &PMS, 
1257                                    PassManagerType PreferredType) {
1258
1259   // Find Module Pass Manager
1260   while(!PMS.empty()) {
1261     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1262     if (TopPMType == PreferredType)
1263       break; // We found desired pass manager
1264     else if (TopPMType > PMT_ModulePassManager)
1265       PMS.pop();    // Pop children pass managers
1266     else
1267       break;
1268   }
1269
1270   PMS.top()->add(this);
1271 }
1272
1273 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1274 /// in the PM Stack and add self into that manager. 
1275 void FunctionPass::assignPassManager(PMStack &PMS,
1276                                      PassManagerType PreferredType) {
1277
1278   // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1279   while(!PMS.empty()) {
1280     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1281       PMS.pop();
1282     else
1283       break; 
1284   }
1285   FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1286
1287   // Create new Function Pass Manager
1288   if (!FPP) {
1289     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1290     PMDataManager *PMD = PMS.top();
1291
1292     // [1] Create new Function Pass Manager
1293     FPP = new FPPassManager(PMD->getDepth() + 1);
1294
1295     // [2] Set up new manager's top level manager
1296     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1297     TPM->addIndirectPassManager(FPP);
1298
1299     // [3] Assign manager to manage this new manager. This may create
1300     // and push new managers into PMS
1301     Pass *P = dynamic_cast<Pass *>(FPP);
1302
1303     // If Call Graph Pass Manager is active then use it to manage
1304     // this new Function Pass manager.
1305     if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1306       P->assignPassManager(PMS, PMT_CallGraphPassManager);
1307     else
1308       P->assignPassManager(PMS);
1309
1310     // [4] Push new manager into PMS
1311     PMS.push(FPP);
1312   }
1313
1314   // Assign FPP as the manager of this pass.
1315   FPP->add(this);
1316 }
1317
1318 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1319 /// in the PM Stack and add self into that manager. 
1320 void BasicBlockPass::assignPassManager(PMStack &PMS,
1321                                        PassManagerType PreferredType) {
1322
1323   BBPassManager *BBP = NULL;
1324
1325   // Basic Pass Manager is a leaf pass manager. It does not handle
1326   // any other pass manager.
1327   if (!PMS.empty()) {
1328     BBP = dynamic_cast<BBPassManager *>(PMS.top());
1329   }
1330
1331   // If leaf manager is not Basic Block Pass manager then create new
1332   // basic Block Pass manager.
1333
1334   if (!BBP) {
1335     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1336     PMDataManager *PMD = PMS.top();
1337
1338     // [1] Create new Basic Block Manager
1339     BBP = new BBPassManager(PMD->getDepth() + 1);
1340
1341     // [2] Set up new manager's top level manager
1342     // Basic Block Pass Manager does not live by itself
1343     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1344     TPM->addIndirectPassManager(BBP);
1345
1346     // [3] Assign manager to manage this new manager. This may create
1347     // and push new managers into PMS
1348     Pass *P = dynamic_cast<Pass *>(BBP);
1349     P->assignPassManager(PMS);
1350
1351     // [4] Push new manager into PMS
1352     PMS.push(BBP);
1353   }
1354
1355   // Assign BBP as the manager of this pass.
1356   BBP->add(this);
1357 }
1358
1359