Use BranchProbability instead of floating points in IfConverter.
[llvm/stm8.git] / lib / VMCore / PassManager.cpp
blob5cf2905733acdee2e90312f5e80794bd7f114685
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.
12 //===----------------------------------------------------------------------===//
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 <cstdio>
32 #include <map>
33 using namespace llvm;
35 // See PassManagers.h for Pass Manager infrastructure overview.
37 namespace llvm {
39 //===----------------------------------------------------------------------===//
40 // Pass debugging information. Often it is useful to find out what pass is
41 // running when a crash occurs in a utility. When this library is compiled with
42 // debugging on, a command line option (--debug-pass) is enabled that causes the
43 // pass name to be printed before it executes.
46 // Different debug levels that can be enabled...
47 enum PassDebugLevel {
48 None, Arguments, Structure, Executions, Details
51 static cl::opt<enum PassDebugLevel>
52 PassDebugging("debug-pass", cl::Hidden,
53 cl::desc("Print PassManager debugging information"),
54 cl::values(
55 clEnumVal(None , "disable debug output"),
56 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
57 clEnumVal(Structure , "print pass structure before run()"),
58 clEnumVal(Executions, "print pass name before it is executed"),
59 clEnumVal(Details , "print pass details when it is executed"),
60 clEnumValEnd));
62 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
63 PassOptionList;
65 // Print IR out before/after specified passes.
66 static PassOptionList
67 PrintBefore("print-before",
68 llvm::cl::desc("Print IR before specified passes"),
69 cl::Hidden);
71 static PassOptionList
72 PrintAfter("print-after",
73 llvm::cl::desc("Print IR after specified passes"),
74 cl::Hidden);
76 static cl::opt<bool>
77 PrintBeforeAll("print-before-all",
78 llvm::cl::desc("Print IR before each pass"),
79 cl::init(false));
80 static cl::opt<bool>
81 PrintAfterAll("print-after-all",
82 llvm::cl::desc("Print IR after each pass"),
83 cl::init(false));
85 /// This is a helper to determine whether to print IR before or
86 /// after a pass.
88 static bool ShouldPrintBeforeOrAfterPass(const void *PassID,
89 PassOptionList &PassesToPrint) {
90 if (const llvm::PassInfo *PI =
91 PassRegistry::getPassRegistry()->getPassInfo(PassID)) {
92 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
93 const llvm::PassInfo *PassInf = PassesToPrint[i];
94 if (PassInf)
95 if (PassInf->getPassArgument() == PI->getPassArgument()) {
96 return true;
100 return false;
104 /// This is a utility to check whether a pass should have IR dumped
105 /// before it.
106 static bool ShouldPrintBeforePass(const void *PassID) {
107 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
110 /// This is a utility to check whether a pass should have IR dumped
111 /// after it.
112 static bool ShouldPrintAfterPass(const void *PassID) {
113 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
116 } // End of llvm namespace
118 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
119 /// or higher is specified.
120 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
121 return PassDebugging >= Executions;
127 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
128 if (V == 0 && M == 0)
129 OS << "Releasing pass '";
130 else
131 OS << "Running pass '";
133 OS << P->getPassName() << "'";
135 if (M) {
136 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
137 return;
139 if (V == 0) {
140 OS << '\n';
141 return;
144 OS << " on ";
145 if (isa<Function>(V))
146 OS << "function";
147 else if (isa<BasicBlock>(V))
148 OS << "basic block";
149 else
150 OS << "value";
152 OS << " '";
153 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
154 OS << "'\n";
158 namespace {
160 //===----------------------------------------------------------------------===//
161 // BBPassManager
163 /// BBPassManager manages BasicBlockPass. It batches all the
164 /// pass together and sequence them to process one basic block before
165 /// processing next basic block.
166 class BBPassManager : public PMDataManager, public FunctionPass {
168 public:
169 static char ID;
170 explicit BBPassManager(int Depth)
171 : PMDataManager(Depth), FunctionPass(ID) {}
173 /// Execute all of the passes scheduled for execution. Keep track of
174 /// whether any of the passes modifies the function, and if so, return true.
175 bool runOnFunction(Function &F);
177 /// Pass Manager itself does not invalidate any analysis info.
178 void getAnalysisUsage(AnalysisUsage &Info) const {
179 Info.setPreservesAll();
182 bool doInitialization(Module &M);
183 bool doInitialization(Function &F);
184 bool doFinalization(Module &M);
185 bool doFinalization(Function &F);
187 virtual PMDataManager *getAsPMDataManager() { return this; }
188 virtual Pass *getAsPass() { return this; }
190 virtual const char *getPassName() const {
191 return "BasicBlock Pass Manager";
194 // Print passes managed by this manager
195 void dumpPassStructure(unsigned Offset) {
196 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
197 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
198 BasicBlockPass *BP = getContainedPass(Index);
199 BP->dumpPassStructure(Offset + 1);
200 dumpLastUses(BP, Offset+1);
204 BasicBlockPass *getContainedPass(unsigned N) {
205 assert(N < PassVector.size() && "Pass number out of range!");
206 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
207 return BP;
210 virtual PassManagerType getPassManagerType() const {
211 return PMT_BasicBlockPassManager;
215 char BBPassManager::ID = 0;
218 namespace llvm {
220 //===----------------------------------------------------------------------===//
221 // FunctionPassManagerImpl
223 /// FunctionPassManagerImpl manages FPPassManagers
224 class FunctionPassManagerImpl : public Pass,
225 public PMDataManager,
226 public PMTopLevelManager {
227 private:
228 bool wasRun;
229 public:
230 static char ID;
231 explicit FunctionPassManagerImpl(int Depth) :
232 Pass(PT_PassManager, ID), PMDataManager(Depth),
233 PMTopLevelManager(new FPPassManager(1)), wasRun(false) {}
235 /// add - Add a pass to the queue of passes to run. This passes ownership of
236 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
237 /// will be destroyed as well, so there is no need to delete the pass. This
238 /// implies that all passes MUST be allocated with 'new'.
239 void add(Pass *P) {
240 schedulePass(P);
243 /// createPrinterPass - Get a function printer pass.
244 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
245 return createPrintFunctionPass(Banner, &O);
248 // Prepare for running an on the fly pass, freeing memory if needed
249 // from a previous run.
250 void releaseMemoryOnTheFly();
252 /// run - Execute all of the passes scheduled for execution. Keep track of
253 /// whether any of the passes modifies the module, and if so, return true.
254 bool run(Function &F);
256 /// doInitialization - Run all of the initializers for the function passes.
258 bool doInitialization(Module &M);
260 /// doFinalization - Run all of the finalizers for the function passes.
262 bool doFinalization(Module &M);
265 virtual PMDataManager *getAsPMDataManager() { return this; }
266 virtual Pass *getAsPass() { return this; }
268 /// Pass Manager itself does not invalidate any analysis info.
269 void getAnalysisUsage(AnalysisUsage &Info) const {
270 Info.setPreservesAll();
273 void addTopLevelPass(Pass *P) {
274 if (ImmutablePass *IP = P->getAsImmutablePass()) {
275 // P is a immutable pass and it will be managed by this
276 // top level manager. Set up analysis resolver to connect them.
277 AnalysisResolver *AR = new AnalysisResolver(*this);
278 P->setResolver(AR);
279 initializeAnalysisImpl(P);
280 addImmutablePass(IP);
281 recordAvailableAnalysis(IP);
282 } else {
283 P->assignPassManager(activeStack, PMT_FunctionPassManager);
288 FPPassManager *getContainedManager(unsigned N) {
289 assert(N < PassManagers.size() && "Pass number out of range!");
290 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
291 return FP;
295 char FunctionPassManagerImpl::ID = 0;
297 //===----------------------------------------------------------------------===//
298 // MPPassManager
300 /// MPPassManager manages ModulePasses and function pass managers.
301 /// It batches all Module passes and function pass managers together and
302 /// sequences them to process one module.
303 class MPPassManager : public Pass, public PMDataManager {
304 public:
305 static char ID;
306 explicit MPPassManager(int Depth) :
307 Pass(PT_PassManager, ID), PMDataManager(Depth) { }
309 // Delete on the fly managers.
310 virtual ~MPPassManager() {
311 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
312 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
313 I != E; ++I) {
314 FunctionPassManagerImpl *FPP = I->second;
315 delete FPP;
319 /// createPrinterPass - Get a module printer pass.
320 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
321 return createPrintModulePass(&O, false, Banner);
324 /// run - Execute all of the passes scheduled for execution. Keep track of
325 /// whether any of the passes modifies the module, and if so, return true.
326 bool runOnModule(Module &M);
328 /// Pass Manager itself does not invalidate any analysis info.
329 void getAnalysisUsage(AnalysisUsage &Info) const {
330 Info.setPreservesAll();
333 /// Add RequiredPass into list of lower level passes required by pass P.
334 /// RequiredPass is run on the fly by Pass Manager when P requests it
335 /// through getAnalysis interface.
336 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
338 /// Return function pass corresponding to PassInfo PI, that is
339 /// required by module pass MP. Instantiate analysis pass, by using
340 /// its runOnFunction() for function F.
341 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
343 virtual const char *getPassName() const {
344 return "Module Pass Manager";
347 virtual PMDataManager *getAsPMDataManager() { return this; }
348 virtual Pass *getAsPass() { return this; }
350 // Print passes managed by this manager
351 void dumpPassStructure(unsigned Offset) {
352 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
353 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
354 ModulePass *MP = getContainedPass(Index);
355 MP->dumpPassStructure(Offset + 1);
356 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
357 OnTheFlyManagers.find(MP);
358 if (I != OnTheFlyManagers.end())
359 I->second->dumpPassStructure(Offset + 2);
360 dumpLastUses(MP, Offset+1);
364 ModulePass *getContainedPass(unsigned N) {
365 assert(N < PassVector.size() && "Pass number out of range!");
366 return static_cast<ModulePass *>(PassVector[N]);
369 virtual PassManagerType getPassManagerType() const {
370 return PMT_ModulePassManager;
373 private:
374 /// Collection of on the fly FPPassManagers. These managers manage
375 /// function passes that are required by module passes.
376 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
379 char MPPassManager::ID = 0;
380 //===----------------------------------------------------------------------===//
381 // PassManagerImpl
384 /// PassManagerImpl manages MPPassManagers
385 class PassManagerImpl : public Pass,
386 public PMDataManager,
387 public PMTopLevelManager {
389 public:
390 static char ID;
391 explicit PassManagerImpl(int Depth) :
392 Pass(PT_PassManager, ID), PMDataManager(Depth),
393 PMTopLevelManager(new MPPassManager(1)) {}
395 /// add - Add a pass to the queue of passes to run. This passes ownership of
396 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
397 /// will be destroyed as well, so there is no need to delete the pass. This
398 /// implies that all passes MUST be allocated with 'new'.
399 void add(Pass *P) {
400 schedulePass(P);
403 /// createPrinterPass - Get a module printer pass.
404 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
405 return createPrintModulePass(&O, false, Banner);
408 /// run - Execute all of the passes scheduled for execution. Keep track of
409 /// whether any of the passes modifies the module, and if so, return true.
410 bool run(Module &M);
412 /// Pass Manager itself does not invalidate any analysis info.
413 void getAnalysisUsage(AnalysisUsage &Info) const {
414 Info.setPreservesAll();
417 void addTopLevelPass(Pass *P) {
418 if (ImmutablePass *IP = P->getAsImmutablePass()) {
419 // P is a immutable pass and it will be managed by this
420 // top level manager. Set up analysis resolver to connect them.
421 AnalysisResolver *AR = new AnalysisResolver(*this);
422 P->setResolver(AR);
423 initializeAnalysisImpl(P);
424 addImmutablePass(IP);
425 recordAvailableAnalysis(IP);
426 } else {
427 P->assignPassManager(activeStack, PMT_ModulePassManager);
431 virtual PMDataManager *getAsPMDataManager() { return this; }
432 virtual Pass *getAsPass() { return this; }
434 MPPassManager *getContainedManager(unsigned N) {
435 assert(N < PassManagers.size() && "Pass number out of range!");
436 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
437 return MP;
441 char PassManagerImpl::ID = 0;
442 } // End of llvm namespace
444 namespace {
446 //===----------------------------------------------------------------------===//
447 // DebugInfoProbe
449 static DebugInfoProbeInfo *TheDebugProbe;
450 static void createDebugInfoProbe() {
451 if (TheDebugProbe) return;
453 // Constructed the first time this is called. This guarantees that the
454 // object will be constructed, if -enable-debug-info-probe is set,
455 // before static globals, thus it will be destroyed before them.
456 static ManagedStatic<DebugInfoProbeInfo> DIP;
457 TheDebugProbe = &*DIP;
460 //===----------------------------------------------------------------------===//
461 /// TimingInfo Class - This class is used to calculate information about the
462 /// amount of time each pass takes to execute. This only happens when
463 /// -time-passes is enabled on the command line.
466 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
468 class TimingInfo {
469 DenseMap<Pass*, Timer*> TimingData;
470 TimerGroup TG;
471 public:
472 // Use 'create' member to get this.
473 TimingInfo() : TG("... Pass execution timing report ...") {}
475 // TimingDtor - Print out information about timing information
476 ~TimingInfo() {
477 // Delete all of the timers, which accumulate their info into the
478 // TimerGroup.
479 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
480 E = TimingData.end(); I != E; ++I)
481 delete I->second;
482 // TimerGroup is deleted next, printing the report.
485 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
486 // to a non null value (if the -time-passes option is enabled) or it leaves it
487 // null. It may be called multiple times.
488 static void createTheTimeInfo();
490 /// getPassTimer - Return the timer for the specified pass if it exists.
491 Timer *getPassTimer(Pass *P) {
492 if (P->getAsPMDataManager())
493 return 0;
495 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
496 Timer *&T = TimingData[P];
497 if (T == 0)
498 T = new Timer(P->getPassName(), TG);
499 return T;
503 } // End of anon namespace
505 static TimingInfo *TheTimeInfo;
507 //===----------------------------------------------------------------------===//
508 // PMTopLevelManager implementation
510 /// Initialize top level manager. Create first pass manager.
511 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
512 PMDM->setTopLevelManager(this);
513 addPassManager(PMDM);
514 activeStack.push(PMDM);
517 /// Set pass P as the last user of the given analysis passes.
518 void
519 PMTopLevelManager::setLastUser(const SmallVectorImpl<Pass *> &AnalysisPasses,
520 Pass *P) {
521 unsigned PDepth = 0;
522 if (P->getResolver())
523 PDepth = P->getResolver()->getPMDataManager().getDepth();
525 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
526 E = AnalysisPasses.end(); I != E; ++I) {
527 Pass *AP = *I;
528 LastUser[AP] = P;
530 if (P == AP)
531 continue;
533 // Update the last users of passes that are required transitive by AP.
534 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
535 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
536 SmallVector<Pass *, 12> LastUses;
537 SmallVector<Pass *, 12> LastPMUses;
538 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
539 E = IDs.end(); I != E; ++I) {
540 Pass *AnalysisPass = findAnalysisPass(*I);
541 assert(AnalysisPass && "Expected analysis pass to exist.");
542 AnalysisResolver *AR = AnalysisPass->getResolver();
543 assert(AR && "Expected analysis resolver to exist.");
544 unsigned APDepth = AR->getPMDataManager().getDepth();
546 if (PDepth == APDepth)
547 LastUses.push_back(AnalysisPass);
548 else if (PDepth > APDepth)
549 LastPMUses.push_back(AnalysisPass);
552 setLastUser(LastUses, P);
554 // If this pass has a corresponding pass manager, push higher level
555 // analysis to this pass manager.
556 if (P->getResolver())
557 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
560 // If AP is the last user of other passes then make P last user of
561 // such passes.
562 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
563 LUE = LastUser.end(); LUI != LUE; ++LUI) {
564 if (LUI->second == AP)
565 // DenseMap iterator is not invalidated here because
566 // this is just updating existing entries.
567 LastUser[LUI->first] = P;
572 /// Collect passes whose last user is P
573 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
574 Pass *P) {
575 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
576 InversedLastUser.find(P);
577 if (DMI == InversedLastUser.end())
578 return;
580 SmallPtrSet<Pass *, 8> &LU = DMI->second;
581 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
582 E = LU.end(); I != E; ++I) {
583 LastUses.push_back(*I);
588 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
589 AnalysisUsage *AnUsage = NULL;
590 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
591 if (DMI != AnUsageMap.end())
592 AnUsage = DMI->second;
593 else {
594 AnUsage = new AnalysisUsage();
595 P->getAnalysisUsage(*AnUsage);
596 AnUsageMap[P] = AnUsage;
598 return AnUsage;
601 /// Schedule pass P for execution. Make sure that passes required by
602 /// P are run before P is run. Update analysis info maintained by
603 /// the manager. Remove dead passes. This is a recursive function.
604 void PMTopLevelManager::schedulePass(Pass *P) {
606 // TODO : Allocate function manager for this pass, other wise required set
607 // may be inserted into previous function manager
609 // Give pass a chance to prepare the stage.
610 P->preparePassManager(activeStack);
612 // If P is an analysis pass and it is available then do not
613 // generate the analysis again. Stale analysis info should not be
614 // available at this point.
615 const PassInfo *PI =
616 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
617 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
618 delete P;
619 return;
622 AnalysisUsage *AnUsage = findAnalysisUsage(P);
624 bool checkAnalysis = true;
625 while (checkAnalysis) {
626 checkAnalysis = false;
628 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
629 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
630 E = RequiredSet.end(); I != E; ++I) {
632 Pass *AnalysisPass = findAnalysisPass(*I);
633 if (!AnalysisPass) {
634 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
635 assert(PI && "Expected required passes to be initialized");
636 AnalysisPass = PI->createPass();
637 if (P->getPotentialPassManagerType () ==
638 AnalysisPass->getPotentialPassManagerType())
639 // Schedule analysis pass that is managed by the same pass manager.
640 schedulePass(AnalysisPass);
641 else if (P->getPotentialPassManagerType () >
642 AnalysisPass->getPotentialPassManagerType()) {
643 // Schedule analysis pass that is managed by a new manager.
644 schedulePass(AnalysisPass);
645 // Recheck analysis passes to ensure that required analyses that
646 // are already checked are still available.
647 checkAnalysis = true;
649 else
650 // Do not schedule this analysis. Lower level analsyis
651 // passes are run on the fly.
652 delete AnalysisPass;
657 // Now all required passes are available.
658 addTopLevelPass(P);
661 /// Find the pass that implements Analysis AID. Search immutable
662 /// passes and all pass managers. If desired pass is not found
663 /// then return NULL.
664 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
666 // Check pass managers
667 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
668 E = PassManagers.end(); I != E; ++I)
669 if (Pass *P = (*I)->findAnalysisPass(AID, false))
670 return P;
672 // Check other pass managers
673 for (SmallVectorImpl<PMDataManager *>::iterator
674 I = IndirectPassManagers.begin(),
675 E = IndirectPassManagers.end(); I != E; ++I)
676 if (Pass *P = (*I)->findAnalysisPass(AID, false))
677 return P;
679 // Check the immutable passes. Iterate in reverse order so that we find
680 // the most recently registered passes first.
681 for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
682 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
683 AnalysisID PI = (*I)->getPassID();
684 if (PI == AID)
685 return *I;
687 // If Pass not found then check the interfaces implemented by Immutable Pass
688 const PassInfo *PassInf =
689 PassRegistry::getPassRegistry()->getPassInfo(PI);
690 assert(PassInf && "Expected all immutable passes to be initialized");
691 const std::vector<const PassInfo*> &ImmPI =
692 PassInf->getInterfacesImplemented();
693 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
694 EE = ImmPI.end(); II != EE; ++II) {
695 if ((*II)->getTypeInfo() == AID)
696 return *I;
700 return 0;
703 // Print passes managed by this top level manager.
704 void PMTopLevelManager::dumpPasses() const {
706 if (PassDebugging < Structure)
707 return;
709 // Print out the immutable passes
710 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
711 ImmutablePasses[i]->dumpPassStructure(0);
714 // Every class that derives from PMDataManager also derives from Pass
715 // (sometimes indirectly), but there's no inheritance relationship
716 // between PMDataManager and Pass, so we have to getAsPass to get
717 // from a PMDataManager* to a Pass*.
718 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
719 E = PassManagers.end(); I != E; ++I)
720 (*I)->getAsPass()->dumpPassStructure(1);
723 void PMTopLevelManager::dumpArguments() const {
725 if (PassDebugging < Arguments)
726 return;
728 dbgs() << "Pass Arguments: ";
729 for (SmallVector<ImmutablePass *, 8>::const_iterator I =
730 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
731 if (const PassInfo *PI =
732 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
733 assert(PI && "Expected all immutable passes to be initialized");
734 if (!PI->isAnalysisGroup())
735 dbgs() << " -" << PI->getPassArgument();
737 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
738 E = PassManagers.end(); I != E; ++I)
739 (*I)->dumpPassArguments();
740 dbgs() << "\n";
743 void PMTopLevelManager::initializeAllAnalysisInfo() {
744 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
745 E = PassManagers.end(); I != E; ++I)
746 (*I)->initializeAnalysisInfo();
748 // Initailize other pass managers
749 for (SmallVectorImpl<PMDataManager *>::iterator
750 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
751 I != E; ++I)
752 (*I)->initializeAnalysisInfo();
754 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
755 DME = LastUser.end(); DMI != DME; ++DMI) {
756 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
757 InversedLastUser.find(DMI->second);
758 if (InvDMI != InversedLastUser.end()) {
759 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
760 L.insert(DMI->first);
761 } else {
762 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
763 InversedLastUser[DMI->second] = L;
768 /// Destructor
769 PMTopLevelManager::~PMTopLevelManager() {
770 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
771 E = PassManagers.end(); I != E; ++I)
772 delete *I;
774 for (SmallVectorImpl<ImmutablePass *>::iterator
775 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
776 delete *I;
778 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
779 DME = AnUsageMap.end(); DMI != DME; ++DMI)
780 delete DMI->second;
783 //===----------------------------------------------------------------------===//
784 // PMDataManager implementation
786 /// Augement AvailableAnalysis by adding analysis made available by pass P.
787 void PMDataManager::recordAvailableAnalysis(Pass *P) {
788 AnalysisID PI = P->getPassID();
790 AvailableAnalysis[PI] = P;
792 assert(!AvailableAnalysis.empty());
794 // This pass is the current implementation of all of the interfaces it
795 // implements as well.
796 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
797 if (PInf == 0) return;
798 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
799 for (unsigned i = 0, e = II.size(); i != e; ++i)
800 AvailableAnalysis[II[i]->getTypeInfo()] = P;
803 // Return true if P preserves high level analysis used by other
804 // passes managed by this manager
805 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
806 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
807 if (AnUsage->getPreservesAll())
808 return true;
810 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
811 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
812 E = HigherLevelAnalysis.end(); I != E; ++I) {
813 Pass *P1 = *I;
814 if (P1->getAsImmutablePass() == 0 &&
815 std::find(PreservedSet.begin(), PreservedSet.end(),
816 P1->getPassID()) ==
817 PreservedSet.end())
818 return false;
821 return true;
824 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
825 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
826 // Don't do this unless assertions are enabled.
827 #ifdef NDEBUG
828 return;
829 #endif
830 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
831 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
833 // Verify preserved analysis
834 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
835 E = PreservedSet.end(); I != E; ++I) {
836 AnalysisID AID = *I;
837 if (Pass *AP = findAnalysisPass(AID, true)) {
838 TimeRegion PassTimer(getPassTimer(AP));
839 AP->verifyAnalysis();
844 /// Remove Analysis not preserved by Pass P
845 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
846 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
847 if (AnUsage->getPreservesAll())
848 return;
850 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
851 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
852 E = AvailableAnalysis.end(); I != E; ) {
853 std::map<AnalysisID, Pass*>::iterator Info = I++;
854 if (Info->second->getAsImmutablePass() == 0 &&
855 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
856 PreservedSet.end()) {
857 // Remove this analysis
858 if (PassDebugging >= Details) {
859 Pass *S = Info->second;
860 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
861 dbgs() << S->getPassName() << "'\n";
863 AvailableAnalysis.erase(Info);
867 // Check inherited analysis also. If P is not preserving analysis
868 // provided by parent manager then remove it here.
869 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
871 if (!InheritedAnalysis[Index])
872 continue;
874 for (std::map<AnalysisID, Pass*>::iterator
875 I = InheritedAnalysis[Index]->begin(),
876 E = InheritedAnalysis[Index]->end(); I != E; ) {
877 std::map<AnalysisID, Pass *>::iterator Info = I++;
878 if (Info->second->getAsImmutablePass() == 0 &&
879 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
880 PreservedSet.end()) {
881 // Remove this analysis
882 if (PassDebugging >= Details) {
883 Pass *S = Info->second;
884 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
885 dbgs() << S->getPassName() << "'\n";
887 InheritedAnalysis[Index]->erase(Info);
893 /// Remove analysis passes that are not used any longer
894 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
895 enum PassDebuggingString DBG_STR) {
897 SmallVector<Pass *, 12> DeadPasses;
899 // If this is a on the fly manager then it does not have TPM.
900 if (!TPM)
901 return;
903 TPM->collectLastUses(DeadPasses, P);
905 if (PassDebugging >= Details && !DeadPasses.empty()) {
906 dbgs() << " -*- '" << P->getPassName();
907 dbgs() << "' is the last user of following pass instances.";
908 dbgs() << " Free these instances\n";
911 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
912 E = DeadPasses.end(); I != E; ++I)
913 freePass(*I, Msg, DBG_STR);
916 void PMDataManager::freePass(Pass *P, StringRef Msg,
917 enum PassDebuggingString DBG_STR) {
918 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
921 // If the pass crashes releasing memory, remember this.
922 PassManagerPrettyStackEntry X(P);
923 TimeRegion PassTimer(getPassTimer(P));
925 P->releaseMemory();
928 AnalysisID PI = P->getPassID();
929 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
930 // Remove the pass itself (if it is not already removed).
931 AvailableAnalysis.erase(PI);
933 // Remove all interfaces this pass implements, for which it is also
934 // listed as the available implementation.
935 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
936 for (unsigned i = 0, e = II.size(); i != e; ++i) {
937 std::map<AnalysisID, Pass*>::iterator Pos =
938 AvailableAnalysis.find(II[i]->getTypeInfo());
939 if (Pos != AvailableAnalysis.end() && Pos->second == P)
940 AvailableAnalysis.erase(Pos);
945 /// Add pass P into the PassVector. Update
946 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
947 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
948 // This manager is going to manage pass P. Set up analysis resolver
949 // to connect them.
950 AnalysisResolver *AR = new AnalysisResolver(*this);
951 P->setResolver(AR);
953 // If a FunctionPass F is the last user of ModulePass info M
954 // then the F's manager, not F, records itself as a last user of M.
955 SmallVector<Pass *, 12> TransferLastUses;
957 if (!ProcessAnalysis) {
958 // Add pass
959 PassVector.push_back(P);
960 return;
963 // At the moment, this pass is the last user of all required passes.
964 SmallVector<Pass *, 12> LastUses;
965 SmallVector<Pass *, 8> RequiredPasses;
966 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
968 unsigned PDepth = this->getDepth();
970 collectRequiredAnalysis(RequiredPasses,
971 ReqAnalysisNotAvailable, P);
972 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
973 E = RequiredPasses.end(); I != E; ++I) {
974 Pass *PRequired = *I;
975 unsigned RDepth = 0;
977 assert(PRequired->getResolver() && "Analysis Resolver is not set");
978 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
979 RDepth = DM.getDepth();
981 if (PDepth == RDepth)
982 LastUses.push_back(PRequired);
983 else if (PDepth > RDepth) {
984 // Let the parent claim responsibility of last use
985 TransferLastUses.push_back(PRequired);
986 // Keep track of higher level analysis used by this manager.
987 HigherLevelAnalysis.push_back(PRequired);
988 } else
989 llvm_unreachable("Unable to accommodate Required Pass");
992 // Set P as P's last user until someone starts using P.
993 // However, if P is a Pass Manager then it does not need
994 // to record its last user.
995 if (P->getAsPMDataManager() == 0)
996 LastUses.push_back(P);
997 TPM->setLastUser(LastUses, P);
999 if (!TransferLastUses.empty()) {
1000 Pass *My_PM = getAsPass();
1001 TPM->setLastUser(TransferLastUses, My_PM);
1002 TransferLastUses.clear();
1005 // Now, take care of required analyses that are not available.
1006 for (SmallVectorImpl<AnalysisID>::iterator
1007 I = ReqAnalysisNotAvailable.begin(),
1008 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1009 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1010 Pass *AnalysisPass = PI->createPass();
1011 this->addLowerLevelRequiredPass(P, AnalysisPass);
1014 // Take a note of analysis required and made available by this pass.
1015 // Remove the analysis not preserved by this pass
1016 removeNotPreservedAnalysis(P);
1017 recordAvailableAnalysis(P);
1019 // Add pass
1020 PassVector.push_back(P);
1024 /// Populate RP with analysis pass that are required by
1025 /// pass P and are available. Populate RP_NotAvail with analysis
1026 /// pass that are required by pass P but are not available.
1027 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1028 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1029 Pass *P) {
1030 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1031 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1032 for (AnalysisUsage::VectorType::const_iterator
1033 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1034 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1035 RP.push_back(AnalysisPass);
1036 else
1037 RP_NotAvail.push_back(*I);
1040 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1041 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1042 E = IDs.end(); I != E; ++I) {
1043 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1044 RP.push_back(AnalysisPass);
1045 else
1046 RP_NotAvail.push_back(*I);
1050 // All Required analyses should be available to the pass as it runs! Here
1051 // we fill in the AnalysisImpls member of the pass so that it can
1052 // successfully use the getAnalysis() method to retrieve the
1053 // implementations it needs.
1055 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1056 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1058 for (AnalysisUsage::VectorType::const_iterator
1059 I = AnUsage->getRequiredSet().begin(),
1060 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1061 Pass *Impl = findAnalysisPass(*I, true);
1062 if (Impl == 0)
1063 // This may be analysis pass that is initialized on the fly.
1064 // If that is not the case then it will raise an assert when it is used.
1065 continue;
1066 AnalysisResolver *AR = P->getResolver();
1067 assert(AR && "Analysis Resolver is not set");
1068 AR->addAnalysisImplsPair(*I, Impl);
1072 /// Find the pass that implements Analysis AID. If desired pass is not found
1073 /// then return NULL.
1074 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1076 // Check if AvailableAnalysis map has one entry.
1077 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1079 if (I != AvailableAnalysis.end())
1080 return I->second;
1082 // Search Parents through TopLevelManager
1083 if (SearchParent)
1084 return TPM->findAnalysisPass(AID);
1086 return NULL;
1089 // Print list of passes that are last used by P.
1090 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1092 SmallVector<Pass *, 12> LUses;
1094 // If this is a on the fly manager then it does not have TPM.
1095 if (!TPM)
1096 return;
1098 TPM->collectLastUses(LUses, P);
1100 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1101 E = LUses.end(); I != E; ++I) {
1102 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1103 (*I)->dumpPassStructure(0);
1107 void PMDataManager::dumpPassArguments() const {
1108 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1109 E = PassVector.end(); I != E; ++I) {
1110 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1111 PMD->dumpPassArguments();
1112 else
1113 if (const PassInfo *PI =
1114 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1115 if (!PI->isAnalysisGroup())
1116 dbgs() << " -" << PI->getPassArgument();
1120 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1121 enum PassDebuggingString S2,
1122 StringRef Msg) {
1123 if (PassDebugging < Executions)
1124 return;
1125 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1126 switch (S1) {
1127 case EXECUTION_MSG:
1128 dbgs() << "Executing Pass '" << P->getPassName();
1129 break;
1130 case MODIFICATION_MSG:
1131 dbgs() << "Made Modification '" << P->getPassName();
1132 break;
1133 case FREEING_MSG:
1134 dbgs() << " Freeing Pass '" << P->getPassName();
1135 break;
1136 default:
1137 break;
1139 switch (S2) {
1140 case ON_BASICBLOCK_MSG:
1141 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1142 break;
1143 case ON_FUNCTION_MSG:
1144 dbgs() << "' on Function '" << Msg << "'...\n";
1145 break;
1146 case ON_MODULE_MSG:
1147 dbgs() << "' on Module '" << Msg << "'...\n";
1148 break;
1149 case ON_REGION_MSG:
1150 dbgs() << "' on Region '" << Msg << "'...\n";
1151 break;
1152 case ON_LOOP_MSG:
1153 dbgs() << "' on Loop '" << Msg << "'...\n";
1154 break;
1155 case ON_CG_MSG:
1156 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1157 break;
1158 default:
1159 break;
1163 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1164 if (PassDebugging < Details)
1165 return;
1167 AnalysisUsage analysisUsage;
1168 P->getAnalysisUsage(analysisUsage);
1169 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1172 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1173 if (PassDebugging < Details)
1174 return;
1176 AnalysisUsage analysisUsage;
1177 P->getAnalysisUsage(analysisUsage);
1178 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1181 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1182 const AnalysisUsage::VectorType &Set) const {
1183 assert(PassDebugging >= Details);
1184 if (Set.empty())
1185 return;
1186 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1187 for (unsigned i = 0; i != Set.size(); ++i) {
1188 if (i) dbgs() << ',';
1189 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1190 if (!PInf) {
1191 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1192 // all drivers.
1193 dbgs() << " Uninitialized Pass";
1194 continue;
1196 dbgs() << ' ' << PInf->getPassName();
1198 dbgs() << '\n';
1201 /// Add RequiredPass into list of lower level passes required by pass P.
1202 /// RequiredPass is run on the fly by Pass Manager when P requests it
1203 /// through getAnalysis interface.
1204 /// This should be handled by specific pass manager.
1205 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1206 if (TPM) {
1207 TPM->dumpArguments();
1208 TPM->dumpPasses();
1211 // Module Level pass may required Function Level analysis info
1212 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1213 // to provide this on demand. In that case, in Pass manager terminology,
1214 // module level pass is requiring lower level analysis info managed by
1215 // lower level pass manager.
1217 // When Pass manager is not able to order required analysis info, Pass manager
1218 // checks whether any lower level manager will be able to provide this
1219 // analysis info on demand or not.
1220 #ifndef NDEBUG
1221 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1222 dbgs() << "' required by '" << P->getPassName() << "'\n";
1223 #endif
1224 llvm_unreachable("Unable to schedule pass");
1227 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1228 assert(0 && "Unable to find on the fly pass");
1229 return NULL;
1232 // Destructor
1233 PMDataManager::~PMDataManager() {
1234 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1235 E = PassVector.end(); I != E; ++I)
1236 delete *I;
1239 //===----------------------------------------------------------------------===//
1240 // NOTE: Is this the right place to define this method ?
1241 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1242 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1243 return PM.findAnalysisPass(ID, dir);
1246 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1247 Function &F) {
1248 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1251 //===----------------------------------------------------------------------===//
1252 // BBPassManager implementation
1254 /// Execute all of the passes scheduled for execution by invoking
1255 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1256 /// the function, and if so, return true.
1257 bool BBPassManager::runOnFunction(Function &F) {
1258 if (F.isDeclaration())
1259 return false;
1261 bool Changed = doInitialization(F);
1263 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1264 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1265 BasicBlockPass *BP = getContainedPass(Index);
1266 bool LocalChanged = false;
1268 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1269 dumpRequiredSet(BP);
1271 initializeAnalysisImpl(BP);
1274 // If the pass crashes, remember this.
1275 PassManagerPrettyStackEntry X(BP, *I);
1276 TimeRegion PassTimer(getPassTimer(BP));
1278 LocalChanged |= BP->runOnBasicBlock(*I);
1281 Changed |= LocalChanged;
1282 if (LocalChanged)
1283 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1284 I->getName());
1285 dumpPreservedSet(BP);
1287 verifyPreservedAnalysis(BP);
1288 removeNotPreservedAnalysis(BP);
1289 recordAvailableAnalysis(BP);
1290 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1293 return doFinalization(F) || Changed;
1296 // Implement doInitialization and doFinalization
1297 bool BBPassManager::doInitialization(Module &M) {
1298 bool Changed = false;
1300 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1301 Changed |= getContainedPass(Index)->doInitialization(M);
1303 return Changed;
1306 bool BBPassManager::doFinalization(Module &M) {
1307 bool Changed = false;
1309 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1310 Changed |= getContainedPass(Index)->doFinalization(M);
1312 return Changed;
1315 bool BBPassManager::doInitialization(Function &F) {
1316 bool Changed = false;
1318 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1319 BasicBlockPass *BP = getContainedPass(Index);
1320 Changed |= BP->doInitialization(F);
1323 return Changed;
1326 bool BBPassManager::doFinalization(Function &F) {
1327 bool Changed = false;
1329 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1330 BasicBlockPass *BP = getContainedPass(Index);
1331 Changed |= BP->doFinalization(F);
1334 return Changed;
1338 //===----------------------------------------------------------------------===//
1339 // FunctionPassManager implementation
1341 /// Create new Function pass manager
1342 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1343 FPM = new FunctionPassManagerImpl(0);
1344 // FPM is the top level manager.
1345 FPM->setTopLevelManager(FPM);
1347 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1348 FPM->setResolver(AR);
1351 FunctionPassManager::~FunctionPassManager() {
1352 delete FPM;
1355 /// addImpl - Add a pass to the queue of passes to run, without
1356 /// checking whether to add a printer pass.
1357 void FunctionPassManager::addImpl(Pass *P) {
1358 FPM->add(P);
1361 /// add - Add a pass to the queue of passes to run. This passes
1362 /// ownership of the Pass to the PassManager. When the
1363 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1364 /// there is no need to delete the pass. (TODO delete passes.)
1365 /// This implies that all passes MUST be allocated with 'new'.
1366 void FunctionPassManager::add(Pass *P) {
1367 // If this is a not a function pass, don't add a printer for it.
1368 const void *PassID = P->getPassID();
1369 if (P->getPassKind() == PT_Function)
1370 if (ShouldPrintBeforePass(PassID))
1371 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1372 + P->getPassName() + " ***"));
1374 addImpl(P);
1376 if (P->getPassKind() == PT_Function)
1377 if (ShouldPrintAfterPass(PassID))
1378 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1379 + P->getPassName() + " ***"));
1382 /// run - Execute all of the passes scheduled for execution. Keep
1383 /// track of whether any of the passes modifies the function, and if
1384 /// so, return true.
1386 bool FunctionPassManager::run(Function &F) {
1387 if (F.isMaterializable()) {
1388 std::string errstr;
1389 if (F.Materialize(&errstr))
1390 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1392 return FPM->run(F);
1396 /// doInitialization - Run all of the initializers for the function passes.
1398 bool FunctionPassManager::doInitialization() {
1399 return FPM->doInitialization(*M);
1402 /// doFinalization - Run all of the finalizers for the function passes.
1404 bool FunctionPassManager::doFinalization() {
1405 return FPM->doFinalization(*M);
1408 //===----------------------------------------------------------------------===//
1409 // FunctionPassManagerImpl implementation
1411 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1412 bool Changed = false;
1414 dumpArguments();
1415 dumpPasses();
1417 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1418 Changed |= getContainedManager(Index)->doInitialization(M);
1420 return Changed;
1423 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1424 bool Changed = false;
1426 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1427 Changed |= getContainedManager(Index)->doFinalization(M);
1429 return Changed;
1432 /// cleanup - After running all passes, clean up pass manager cache.
1433 void FPPassManager::cleanup() {
1434 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1435 FunctionPass *FP = getContainedPass(Index);
1436 AnalysisResolver *AR = FP->getResolver();
1437 assert(AR && "Analysis Resolver is not set");
1438 AR->clearAnalysisImpls();
1442 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1443 if (!wasRun)
1444 return;
1445 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1446 FPPassManager *FPPM = getContainedManager(Index);
1447 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1448 FPPM->getContainedPass(Index)->releaseMemory();
1451 wasRun = false;
1454 // Execute all the passes managed by this top level manager.
1455 // Return true if any function is modified by a pass.
1456 bool FunctionPassManagerImpl::run(Function &F) {
1457 bool Changed = false;
1458 TimingInfo::createTheTimeInfo();
1459 createDebugInfoProbe();
1461 initializeAllAnalysisInfo();
1462 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1463 Changed |= getContainedManager(Index)->runOnFunction(F);
1465 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1466 getContainedManager(Index)->cleanup();
1468 wasRun = true;
1469 return Changed;
1472 //===----------------------------------------------------------------------===//
1473 // FPPassManager implementation
1475 char FPPassManager::ID = 0;
1476 /// Print passes managed by this manager
1477 void FPPassManager::dumpPassStructure(unsigned Offset) {
1478 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1479 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1480 FunctionPass *FP = getContainedPass(Index);
1481 FP->dumpPassStructure(Offset + 1);
1482 dumpLastUses(FP, Offset+1);
1487 /// Execute all of the passes scheduled for execution by invoking
1488 /// runOnFunction method. Keep track of whether any of the passes modifies
1489 /// the function, and if so, return true.
1490 bool FPPassManager::runOnFunction(Function &F) {
1491 if (F.isDeclaration())
1492 return false;
1494 bool Changed = false;
1496 // Collect inherited analysis from Module level pass manager.
1497 populateInheritedAnalysis(TPM->activeStack);
1499 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1500 FunctionPass *FP = getContainedPass(Index);
1501 bool LocalChanged = false;
1503 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1504 dumpRequiredSet(FP);
1506 initializeAnalysisImpl(FP);
1507 if (TheDebugProbe)
1508 TheDebugProbe->initialize(FP, F);
1510 PassManagerPrettyStackEntry X(FP, F);
1511 TimeRegion PassTimer(getPassTimer(FP));
1513 LocalChanged |= FP->runOnFunction(F);
1515 if (TheDebugProbe)
1516 TheDebugProbe->finalize(FP, F);
1518 Changed |= LocalChanged;
1519 if (LocalChanged)
1520 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1521 dumpPreservedSet(FP);
1523 verifyPreservedAnalysis(FP);
1524 removeNotPreservedAnalysis(FP);
1525 recordAvailableAnalysis(FP);
1526 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1528 return Changed;
1531 bool FPPassManager::runOnModule(Module &M) {
1532 bool Changed = doInitialization(M);
1534 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1535 runOnFunction(*I);
1537 return doFinalization(M) || Changed;
1540 bool FPPassManager::doInitialization(Module &M) {
1541 bool Changed = false;
1543 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1544 Changed |= getContainedPass(Index)->doInitialization(M);
1546 return Changed;
1549 bool FPPassManager::doFinalization(Module &M) {
1550 bool Changed = false;
1552 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1553 Changed |= getContainedPass(Index)->doFinalization(M);
1555 return Changed;
1558 //===----------------------------------------------------------------------===//
1559 // MPPassManager implementation
1561 /// Execute all of the passes scheduled for execution by invoking
1562 /// runOnModule method. Keep track of whether any of the passes modifies
1563 /// the module, and if so, return true.
1564 bool
1565 MPPassManager::runOnModule(Module &M) {
1566 bool Changed = false;
1568 // Initialize on-the-fly passes
1569 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1570 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1571 I != E; ++I) {
1572 FunctionPassManagerImpl *FPP = I->second;
1573 Changed |= FPP->doInitialization(M);
1576 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1577 ModulePass *MP = getContainedPass(Index);
1578 bool LocalChanged = false;
1580 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1581 dumpRequiredSet(MP);
1583 initializeAnalysisImpl(MP);
1586 PassManagerPrettyStackEntry X(MP, M);
1587 TimeRegion PassTimer(getPassTimer(MP));
1589 LocalChanged |= MP->runOnModule(M);
1592 Changed |= LocalChanged;
1593 if (LocalChanged)
1594 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1595 M.getModuleIdentifier());
1596 dumpPreservedSet(MP);
1598 verifyPreservedAnalysis(MP);
1599 removeNotPreservedAnalysis(MP);
1600 recordAvailableAnalysis(MP);
1601 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1604 // Finalize on-the-fly passes
1605 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1606 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1607 I != E; ++I) {
1608 FunctionPassManagerImpl *FPP = I->second;
1609 // We don't know when is the last time an on-the-fly pass is run,
1610 // so we need to releaseMemory / finalize here
1611 FPP->releaseMemoryOnTheFly();
1612 Changed |= FPP->doFinalization(M);
1614 return Changed;
1617 /// Add RequiredPass into list of lower level passes required by pass P.
1618 /// RequiredPass is run on the fly by Pass Manager when P requests it
1619 /// through getAnalysis interface.
1620 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1621 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1622 "Unable to handle Pass that requires lower level Analysis pass");
1623 assert((P->getPotentialPassManagerType() <
1624 RequiredPass->getPotentialPassManagerType()) &&
1625 "Unable to handle Pass that requires lower level Analysis pass");
1627 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1628 if (!FPP) {
1629 FPP = new FunctionPassManagerImpl(0);
1630 // FPP is the top level manager.
1631 FPP->setTopLevelManager(FPP);
1633 OnTheFlyManagers[P] = FPP;
1635 FPP->add(RequiredPass);
1637 // Register P as the last user of RequiredPass.
1638 SmallVector<Pass *, 1> LU;
1639 LU.push_back(RequiredPass);
1640 FPP->setLastUser(LU, P);
1643 /// Return function pass corresponding to PassInfo PI, that is
1644 /// required by module pass MP. Instantiate analysis pass, by using
1645 /// its runOnFunction() for function F.
1646 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1647 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1648 assert(FPP && "Unable to find on the fly pass");
1650 FPP->releaseMemoryOnTheFly();
1651 FPP->run(F);
1652 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1656 //===----------------------------------------------------------------------===//
1657 // PassManagerImpl implementation
1659 /// run - Execute all of the passes scheduled for execution. Keep track of
1660 /// whether any of the passes modifies the module, and if so, return true.
1661 bool PassManagerImpl::run(Module &M) {
1662 bool Changed = false;
1663 TimingInfo::createTheTimeInfo();
1664 createDebugInfoProbe();
1666 dumpArguments();
1667 dumpPasses();
1669 initializeAllAnalysisInfo();
1670 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1671 Changed |= getContainedManager(Index)->runOnModule(M);
1672 return Changed;
1675 //===----------------------------------------------------------------------===//
1676 // PassManager implementation
1678 /// Create new pass manager
1679 PassManager::PassManager() {
1680 PM = new PassManagerImpl(0);
1681 // PM is the top level manager
1682 PM->setTopLevelManager(PM);
1685 PassManager::~PassManager() {
1686 delete PM;
1689 /// addImpl - Add a pass to the queue of passes to run, without
1690 /// checking whether to add a printer pass.
1691 void PassManager::addImpl(Pass *P) {
1692 PM->add(P);
1695 /// add - Add a pass to the queue of passes to run. This passes ownership of
1696 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1697 /// will be destroyed as well, so there is no need to delete the pass. This
1698 /// implies that all passes MUST be allocated with 'new'.
1699 void PassManager::add(Pass *P) {
1700 const void* PassID = P->getPassID();
1701 if (ShouldPrintBeforePass(PassID))
1702 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1703 + P->getPassName() + " ***"));
1705 addImpl(P);
1707 if (ShouldPrintAfterPass(PassID))
1708 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1709 + P->getPassName() + " ***"));
1712 /// run - Execute all of the passes scheduled for execution. Keep track of
1713 /// whether any of the passes modifies the module, and if so, return true.
1714 bool PassManager::run(Module &M) {
1715 return PM->run(M);
1718 //===----------------------------------------------------------------------===//
1719 // TimingInfo Class - This class is used to calculate information about the
1720 // amount of time each pass takes to execute. This only happens with
1721 // -time-passes is enabled on the command line.
1723 bool llvm::TimePassesIsEnabled = false;
1724 static cl::opt<bool,true>
1725 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1726 cl::desc("Time each pass, printing elapsed time for each on exit"));
1728 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1729 // a non null value (if the -time-passes option is enabled) or it leaves it
1730 // null. It may be called multiple times.
1731 void TimingInfo::createTheTimeInfo() {
1732 if (!TimePassesIsEnabled || TheTimeInfo) return;
1734 // Constructed the first time this is called, iff -time-passes is enabled.
1735 // This guarantees that the object will be constructed before static globals,
1736 // thus it will be destroyed before them.
1737 static ManagedStatic<TimingInfo> TTI;
1738 TheTimeInfo = &*TTI;
1741 /// If TimingInfo is enabled then start pass timer.
1742 Timer *llvm::getPassTimer(Pass *P) {
1743 if (TheTimeInfo)
1744 return TheTimeInfo->getPassTimer(P);
1745 return 0;
1748 //===----------------------------------------------------------------------===//
1749 // PMStack implementation
1752 // Pop Pass Manager from the stack and clear its analysis info.
1753 void PMStack::pop() {
1755 PMDataManager *Top = this->top();
1756 Top->initializeAnalysisInfo();
1758 S.pop_back();
1761 // Push PM on the stack and set its top level manager.
1762 void PMStack::push(PMDataManager *PM) {
1763 assert(PM && "Unable to push. Pass Manager expected");
1765 if (!this->empty()) {
1766 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1768 assert(TPM && "Unable to find top level manager");
1769 TPM->addIndirectPassManager(PM);
1770 PM->setTopLevelManager(TPM);
1773 S.push_back(PM);
1776 // Dump content of the pass manager stack.
1777 void PMStack::dump() const {
1778 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1779 E = S.end(); I != E; ++I)
1780 printf("%s ", (*I)->getAsPass()->getPassName());
1782 if (!S.empty())
1783 printf("\n");
1786 /// Find appropriate Module Pass Manager in the PM Stack and
1787 /// add self into that manager.
1788 void ModulePass::assignPassManager(PMStack &PMS,
1789 PassManagerType PreferredType) {
1790 // Find Module Pass Manager
1791 while (!PMS.empty()) {
1792 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1793 if (TopPMType == PreferredType)
1794 break; // We found desired pass manager
1795 else if (TopPMType > PMT_ModulePassManager)
1796 PMS.pop(); // Pop children pass managers
1797 else
1798 break;
1800 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1801 PMS.top()->add(this);
1804 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1805 /// in the PM Stack and add self into that manager.
1806 void FunctionPass::assignPassManager(PMStack &PMS,
1807 PassManagerType PreferredType) {
1809 // Find Module Pass Manager
1810 while (!PMS.empty()) {
1811 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1812 PMS.pop();
1813 else
1814 break;
1817 // Create new Function Pass Manager if needed.
1818 FPPassManager *FPP;
1819 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1820 FPP = (FPPassManager *)PMS.top();
1821 } else {
1822 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1823 PMDataManager *PMD = PMS.top();
1825 // [1] Create new Function Pass Manager
1826 FPP = new FPPassManager(PMD->getDepth() + 1);
1827 FPP->populateInheritedAnalysis(PMS);
1829 // [2] Set up new manager's top level manager
1830 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1831 TPM->addIndirectPassManager(FPP);
1833 // [3] Assign manager to manage this new manager. This may create
1834 // and push new managers into PMS
1835 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1837 // [4] Push new manager into PMS
1838 PMS.push(FPP);
1841 // Assign FPP as the manager of this pass.
1842 FPP->add(this);
1845 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1846 /// in the PM Stack and add self into that manager.
1847 void BasicBlockPass::assignPassManager(PMStack &PMS,
1848 PassManagerType PreferredType) {
1849 BBPassManager *BBP;
1851 // Basic Pass Manager is a leaf pass manager. It does not handle
1852 // any other pass manager.
1853 if (!PMS.empty() &&
1854 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1855 BBP = (BBPassManager *)PMS.top();
1856 } else {
1857 // If leaf manager is not Basic Block Pass manager then create new
1858 // basic Block Pass manager.
1859 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1860 PMDataManager *PMD = PMS.top();
1862 // [1] Create new Basic Block Manager
1863 BBP = new BBPassManager(PMD->getDepth() + 1);
1865 // [2] Set up new manager's top level manager
1866 // Basic Block Pass Manager does not live by itself
1867 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1868 TPM->addIndirectPassManager(BBP);
1870 // [3] Assign manager to manage this new manager. This may create
1871 // and push new managers into PMS
1872 BBP->assignPassManager(PMS, PreferredType);
1874 // [4] Push new manager into PMS
1875 PMS.push(BBP);
1878 // Assign BBP as the manager of this pass.
1879 BBP->add(this);
1882 PassManagerBase::~PassManagerBase() {}