1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
35 // See PassManagers.h for Pass Manager infrastructure overview.
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...
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"),
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"),
62 typedef llvm::cl::list
<const llvm::PassInfo
*, bool, PassNameParser
>
65 // Print IR out before/after specified passes.
67 PrintBefore("print-before",
68 llvm::cl::desc("Print IR before specified passes"),
72 PrintAfter("print-after",
73 llvm::cl::desc("Print IR after specified passes"),
77 PrintBeforeAll("print-before-all",
78 llvm::cl::desc("Print IR before each pass"),
81 PrintAfterAll("print-after-all",
82 llvm::cl::desc("Print IR after each pass"),
85 /// This is a helper to determine whether to print IR before or
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
];
95 if (PassInf
->getPassArgument() == PI
->getPassArgument()) {
104 /// This is a utility to check whether a pass should have IR dumped
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
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 '";
131 OS
<< "Running pass '";
133 OS
<< P
->getPassName() << "'";
136 OS
<< " on module '" << M
->getModuleIdentifier() << "'.\n";
145 if (isa
<Function
>(V
))
147 else if (isa
<BasicBlock
>(V
))
153 WriteAsOperand(OS
, V
, /*PrintTy=*/false, M
);
160 //===----------------------------------------------------------------------===//
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
{
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
]);
210 virtual PassManagerType
getPassManagerType() const {
211 return PMT_BasicBlockPassManager
;
215 char BBPassManager::ID
= 0;
220 //===----------------------------------------------------------------------===//
221 // FunctionPassManagerImpl
223 /// FunctionPassManagerImpl manages FPPassManagers
224 class FunctionPassManagerImpl
: public Pass
,
225 public PMDataManager
,
226 public PMTopLevelManager
{
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'.
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);
279 initializeAnalysisImpl(P
);
280 addImmutablePass(IP
);
281 recordAvailableAnalysis(IP
);
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
]);
295 char FunctionPassManagerImpl::ID
= 0;
297 //===----------------------------------------------------------------------===//
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
{
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();
314 FunctionPassManagerImpl
*FPP
= I
->second
;
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
;
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 //===----------------------------------------------------------------------===//
384 /// PassManagerImpl manages MPPassManagers
385 class PassManagerImpl
: public Pass
,
386 public PMDataManager
,
387 public PMTopLevelManager
{
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'.
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.
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);
423 initializeAnalysisImpl(P
);
424 addImmutablePass(IP
);
425 recordAvailableAnalysis(IP
);
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
]);
441 char PassManagerImpl::ID
= 0;
442 } // End of llvm namespace
446 //===----------------------------------------------------------------------===//
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
;
469 DenseMap
<Pass
*, Timer
*> TimingData
;
472 // Use 'create' member to get this.
473 TimingInfo() : TG("... Pass execution timing report ...") {}
475 // TimingDtor - Print out information about timing information
477 // Delete all of the timers, which accumulate their info into the
479 for (DenseMap
<Pass
*, Timer
*>::iterator I
= TimingData
.begin(),
480 E
= TimingData
.end(); I
!= E
; ++I
)
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())
495 sys::SmartScopedLock
<true> Lock(*TimingInfoMutex
);
496 Timer
*&T
= TimingData
[P
];
498 T
= new Timer(P
->getPassName(), TG
);
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.
519 PMTopLevelManager::setLastUser(const SmallVectorImpl
<Pass
*> &AnalysisPasses
,
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
) {
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
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
,
575 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator DMI
=
576 InversedLastUser
.find(P
);
577 if (DMI
== InversedLastUser
.end())
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
;
594 AnUsage
= new AnalysisUsage();
595 P
->getAnalysisUsage(*AnUsage
);
596 AnUsageMap
[P
] = 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.
616 PassRegistry::getPassRegistry()->getPassInfo(P
->getPassID());
617 if (PI
&& PI
->isAnalysis() && findAnalysisPass(P
->getPassID())) {
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
);
634 const PassInfo
*PI
= PassRegistry::getPassRegistry()->getPassInfo(*I
);
635 AnalysisPass
= PI
->createPass();
636 if (P
->getPotentialPassManagerType () ==
637 AnalysisPass
->getPotentialPassManagerType())
638 // Schedule analysis pass that is managed by the same pass manager.
639 schedulePass(AnalysisPass
);
640 else if (P
->getPotentialPassManagerType () >
641 AnalysisPass
->getPotentialPassManagerType()) {
642 // Schedule analysis pass that is managed by a new manager.
643 schedulePass(AnalysisPass
);
644 // Recheck analysis passes to ensure that required analyses that
645 // are already checked are still available.
646 checkAnalysis
= true;
649 // Do not schedule this analysis. Lower level analsyis
650 // passes are run on the fly.
656 // Now all required passes are available.
660 /// Find the pass that implements Analysis AID. Search immutable
661 /// passes and all pass managers. If desired pass is not found
662 /// then return NULL.
663 Pass
*PMTopLevelManager::findAnalysisPass(AnalysisID AID
) {
665 // Check pass managers
666 for (SmallVectorImpl
<PMDataManager
*>::iterator I
= PassManagers
.begin(),
667 E
= PassManagers
.end(); I
!= E
; ++I
)
668 if (Pass
*P
= (*I
)->findAnalysisPass(AID
, false))
671 // Check other pass managers
672 for (SmallVectorImpl
<PMDataManager
*>::iterator
673 I
= IndirectPassManagers
.begin(),
674 E
= IndirectPassManagers
.end(); I
!= E
; ++I
)
675 if (Pass
*P
= (*I
)->findAnalysisPass(AID
, false))
678 // Check the immutable passes. Iterate in reverse order so that we find
679 // the most recently registered passes first.
680 for (SmallVector
<ImmutablePass
*, 8>::reverse_iterator I
=
681 ImmutablePasses
.rbegin(), E
= ImmutablePasses
.rend(); I
!= E
; ++I
) {
682 AnalysisID PI
= (*I
)->getPassID();
686 // If Pass not found then check the interfaces implemented by Immutable Pass
687 const PassInfo
*PassInf
=
688 PassRegistry::getPassRegistry()->getPassInfo(PI
);
689 const std::vector
<const PassInfo
*> &ImmPI
=
690 PassInf
->getInterfacesImplemented();
691 for (std::vector
<const PassInfo
*>::const_iterator II
= ImmPI
.begin(),
692 EE
= ImmPI
.end(); II
!= EE
; ++II
) {
693 if ((*II
)->getTypeInfo() == AID
)
701 // Print passes managed by this top level manager.
702 void PMTopLevelManager::dumpPasses() const {
704 if (PassDebugging
< Structure
)
707 // Print out the immutable passes
708 for (unsigned i
= 0, e
= ImmutablePasses
.size(); i
!= e
; ++i
) {
709 ImmutablePasses
[i
]->dumpPassStructure(0);
712 // Every class that derives from PMDataManager also derives from Pass
713 // (sometimes indirectly), but there's no inheritance relationship
714 // between PMDataManager and Pass, so we have to getAsPass to get
715 // from a PMDataManager* to a Pass*.
716 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
717 E
= PassManagers
.end(); I
!= E
; ++I
)
718 (*I
)->getAsPass()->dumpPassStructure(1);
721 void PMTopLevelManager::dumpArguments() const {
723 if (PassDebugging
< Arguments
)
726 dbgs() << "Pass Arguments: ";
727 for (SmallVector
<ImmutablePass
*, 8>::const_iterator I
=
728 ImmutablePasses
.begin(), E
= ImmutablePasses
.end(); I
!= E
; ++I
)
729 if (const PassInfo
*PI
=
730 PassRegistry::getPassRegistry()->getPassInfo((*I
)->getPassID()))
731 if (!PI
->isAnalysisGroup())
732 dbgs() << " -" << PI
->getPassArgument();
733 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
734 E
= PassManagers
.end(); I
!= E
; ++I
)
735 (*I
)->dumpPassArguments();
739 void PMTopLevelManager::initializeAllAnalysisInfo() {
740 for (SmallVectorImpl
<PMDataManager
*>::iterator I
= PassManagers
.begin(),
741 E
= PassManagers
.end(); I
!= E
; ++I
)
742 (*I
)->initializeAnalysisInfo();
744 // Initailize other pass managers
745 for (SmallVectorImpl
<PMDataManager
*>::iterator
746 I
= IndirectPassManagers
.begin(), E
= IndirectPassManagers
.end();
748 (*I
)->initializeAnalysisInfo();
750 for (DenseMap
<Pass
*, Pass
*>::iterator DMI
= LastUser
.begin(),
751 DME
= LastUser
.end(); DMI
!= DME
; ++DMI
) {
752 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator InvDMI
=
753 InversedLastUser
.find(DMI
->second
);
754 if (InvDMI
!= InversedLastUser
.end()) {
755 SmallPtrSet
<Pass
*, 8> &L
= InvDMI
->second
;
756 L
.insert(DMI
->first
);
758 SmallPtrSet
<Pass
*, 8> L
; L
.insert(DMI
->first
);
759 InversedLastUser
[DMI
->second
] = L
;
765 PMTopLevelManager::~PMTopLevelManager() {
766 for (SmallVectorImpl
<PMDataManager
*>::iterator I
= PassManagers
.begin(),
767 E
= PassManagers
.end(); I
!= E
; ++I
)
770 for (SmallVectorImpl
<ImmutablePass
*>::iterator
771 I
= ImmutablePasses
.begin(), E
= ImmutablePasses
.end(); I
!= E
; ++I
)
774 for (DenseMap
<Pass
*, AnalysisUsage
*>::iterator DMI
= AnUsageMap
.begin(),
775 DME
= AnUsageMap
.end(); DMI
!= DME
; ++DMI
)
779 //===----------------------------------------------------------------------===//
780 // PMDataManager implementation
782 /// Augement AvailableAnalysis by adding analysis made available by pass P.
783 void PMDataManager::recordAvailableAnalysis(Pass
*P
) {
784 AnalysisID PI
= P
->getPassID();
786 AvailableAnalysis
[PI
] = P
;
788 assert(!AvailableAnalysis
.empty());
790 // This pass is the current implementation of all of the interfaces it
791 // implements as well.
792 const PassInfo
*PInf
= PassRegistry::getPassRegistry()->getPassInfo(PI
);
793 if (PInf
== 0) return;
794 const std::vector
<const PassInfo
*> &II
= PInf
->getInterfacesImplemented();
795 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
)
796 AvailableAnalysis
[II
[i
]->getTypeInfo()] = P
;
799 // Return true if P preserves high level analysis used by other
800 // passes managed by this manager
801 bool PMDataManager::preserveHigherLevelAnalysis(Pass
*P
) {
802 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
803 if (AnUsage
->getPreservesAll())
806 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
807 for (SmallVectorImpl
<Pass
*>::iterator I
= HigherLevelAnalysis
.begin(),
808 E
= HigherLevelAnalysis
.end(); I
!= E
; ++I
) {
810 if (P1
->getAsImmutablePass() == 0 &&
811 std::find(PreservedSet
.begin(), PreservedSet
.end(),
820 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
821 void PMDataManager::verifyPreservedAnalysis(Pass
*P
) {
822 // Don't do this unless assertions are enabled.
826 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
827 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
829 // Verify preserved analysis
830 for (AnalysisUsage::VectorType::const_iterator I
= PreservedSet
.begin(),
831 E
= PreservedSet
.end(); I
!= E
; ++I
) {
833 if (Pass
*AP
= findAnalysisPass(AID
, true)) {
834 TimeRegion
PassTimer(getPassTimer(AP
));
835 AP
->verifyAnalysis();
840 /// Remove Analysis not preserved by Pass P
841 void PMDataManager::removeNotPreservedAnalysis(Pass
*P
) {
842 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
843 if (AnUsage
->getPreservesAll())
846 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
847 for (std::map
<AnalysisID
, Pass
*>::iterator I
= AvailableAnalysis
.begin(),
848 E
= AvailableAnalysis
.end(); I
!= E
; ) {
849 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
850 if (Info
->second
->getAsImmutablePass() == 0 &&
851 std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
852 PreservedSet
.end()) {
853 // Remove this analysis
854 if (PassDebugging
>= Details
) {
855 Pass
*S
= Info
->second
;
856 dbgs() << " -- '" << P
->getPassName() << "' is not preserving '";
857 dbgs() << S
->getPassName() << "'\n";
859 AvailableAnalysis
.erase(Info
);
863 // Check inherited analysis also. If P is not preserving analysis
864 // provided by parent manager then remove it here.
865 for (unsigned Index
= 0; Index
< PMT_Last
; ++Index
) {
867 if (!InheritedAnalysis
[Index
])
870 for (std::map
<AnalysisID
, Pass
*>::iterator
871 I
= InheritedAnalysis
[Index
]->begin(),
872 E
= InheritedAnalysis
[Index
]->end(); I
!= E
; ) {
873 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
874 if (Info
->second
->getAsImmutablePass() == 0 &&
875 std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
876 PreservedSet
.end()) {
877 // Remove this analysis
878 if (PassDebugging
>= Details
) {
879 Pass
*S
= Info
->second
;
880 dbgs() << " -- '" << P
->getPassName() << "' is not preserving '";
881 dbgs() << S
->getPassName() << "'\n";
883 InheritedAnalysis
[Index
]->erase(Info
);
889 /// Remove analysis passes that are not used any longer
890 void PMDataManager::removeDeadPasses(Pass
*P
, StringRef Msg
,
891 enum PassDebuggingString DBG_STR
) {
893 SmallVector
<Pass
*, 12> DeadPasses
;
895 // If this is a on the fly manager then it does not have TPM.
899 TPM
->collectLastUses(DeadPasses
, P
);
901 if (PassDebugging
>= Details
&& !DeadPasses
.empty()) {
902 dbgs() << " -*- '" << P
->getPassName();
903 dbgs() << "' is the last user of following pass instances.";
904 dbgs() << " Free these instances\n";
907 for (SmallVectorImpl
<Pass
*>::iterator I
= DeadPasses
.begin(),
908 E
= DeadPasses
.end(); I
!= E
; ++I
)
909 freePass(*I
, Msg
, DBG_STR
);
912 void PMDataManager::freePass(Pass
*P
, StringRef Msg
,
913 enum PassDebuggingString DBG_STR
) {
914 dumpPassInfo(P
, FREEING_MSG
, DBG_STR
, Msg
);
917 // If the pass crashes releasing memory, remember this.
918 PassManagerPrettyStackEntry
X(P
);
919 TimeRegion
PassTimer(getPassTimer(P
));
924 AnalysisID PI
= P
->getPassID();
925 if (const PassInfo
*PInf
= PassRegistry::getPassRegistry()->getPassInfo(PI
)) {
926 // Remove the pass itself (if it is not already removed).
927 AvailableAnalysis
.erase(PI
);
929 // Remove all interfaces this pass implements, for which it is also
930 // listed as the available implementation.
931 const std::vector
<const PassInfo
*> &II
= PInf
->getInterfacesImplemented();
932 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
) {
933 std::map
<AnalysisID
, Pass
*>::iterator Pos
=
934 AvailableAnalysis
.find(II
[i
]->getTypeInfo());
935 if (Pos
!= AvailableAnalysis
.end() && Pos
->second
== P
)
936 AvailableAnalysis
.erase(Pos
);
941 /// Add pass P into the PassVector. Update
942 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
943 void PMDataManager::add(Pass
*P
, bool ProcessAnalysis
) {
944 // This manager is going to manage pass P. Set up analysis resolver
946 AnalysisResolver
*AR
= new AnalysisResolver(*this);
949 // If a FunctionPass F is the last user of ModulePass info M
950 // then the F's manager, not F, records itself as a last user of M.
951 SmallVector
<Pass
*, 12> TransferLastUses
;
953 if (!ProcessAnalysis
) {
955 PassVector
.push_back(P
);
959 // At the moment, this pass is the last user of all required passes.
960 SmallVector
<Pass
*, 12> LastUses
;
961 SmallVector
<Pass
*, 8> RequiredPasses
;
962 SmallVector
<AnalysisID
, 8> ReqAnalysisNotAvailable
;
964 unsigned PDepth
= this->getDepth();
966 collectRequiredAnalysis(RequiredPasses
,
967 ReqAnalysisNotAvailable
, P
);
968 for (SmallVectorImpl
<Pass
*>::iterator I
= RequiredPasses
.begin(),
969 E
= RequiredPasses
.end(); I
!= E
; ++I
) {
970 Pass
*PRequired
= *I
;
973 assert(PRequired
->getResolver() && "Analysis Resolver is not set");
974 PMDataManager
&DM
= PRequired
->getResolver()->getPMDataManager();
975 RDepth
= DM
.getDepth();
977 if (PDepth
== RDepth
)
978 LastUses
.push_back(PRequired
);
979 else if (PDepth
> RDepth
) {
980 // Let the parent claim responsibility of last use
981 TransferLastUses
.push_back(PRequired
);
982 // Keep track of higher level analysis used by this manager.
983 HigherLevelAnalysis
.push_back(PRequired
);
985 llvm_unreachable("Unable to accomodate Required Pass");
988 // Set P as P's last user until someone starts using P.
989 // However, if P is a Pass Manager then it does not need
990 // to record its last user.
991 if (P
->getAsPMDataManager() == 0)
992 LastUses
.push_back(P
);
993 TPM
->setLastUser(LastUses
, P
);
995 if (!TransferLastUses
.empty()) {
996 Pass
*My_PM
= getAsPass();
997 TPM
->setLastUser(TransferLastUses
, My_PM
);
998 TransferLastUses
.clear();
1001 // Now, take care of required analyses that are not available.
1002 for (SmallVectorImpl
<AnalysisID
>::iterator
1003 I
= ReqAnalysisNotAvailable
.begin(),
1004 E
= ReqAnalysisNotAvailable
.end() ;I
!= E
; ++I
) {
1005 const PassInfo
*PI
= PassRegistry::getPassRegistry()->getPassInfo(*I
);
1006 Pass
*AnalysisPass
= PI
->createPass();
1007 this->addLowerLevelRequiredPass(P
, AnalysisPass
);
1010 // Take a note of analysis required and made available by this pass.
1011 // Remove the analysis not preserved by this pass
1012 removeNotPreservedAnalysis(P
);
1013 recordAvailableAnalysis(P
);
1016 PassVector
.push_back(P
);
1020 /// Populate RP with analysis pass that are required by
1021 /// pass P and are available. Populate RP_NotAvail with analysis
1022 /// pass that are required by pass P but are not available.
1023 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl
<Pass
*> &RP
,
1024 SmallVectorImpl
<AnalysisID
> &RP_NotAvail
,
1026 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
1027 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
1028 for (AnalysisUsage::VectorType::const_iterator
1029 I
= RequiredSet
.begin(), E
= RequiredSet
.end(); I
!= E
; ++I
) {
1030 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
1031 RP
.push_back(AnalysisPass
);
1033 RP_NotAvail
.push_back(*I
);
1036 const AnalysisUsage::VectorType
&IDs
= AnUsage
->getRequiredTransitiveSet();
1037 for (AnalysisUsage::VectorType::const_iterator I
= IDs
.begin(),
1038 E
= IDs
.end(); I
!= E
; ++I
) {
1039 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
1040 RP
.push_back(AnalysisPass
);
1042 RP_NotAvail
.push_back(*I
);
1046 // All Required analyses should be available to the pass as it runs! Here
1047 // we fill in the AnalysisImpls member of the pass so that it can
1048 // successfully use the getAnalysis() method to retrieve the
1049 // implementations it needs.
1051 void PMDataManager::initializeAnalysisImpl(Pass
*P
) {
1052 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
1054 for (AnalysisUsage::VectorType::const_iterator
1055 I
= AnUsage
->getRequiredSet().begin(),
1056 E
= AnUsage
->getRequiredSet().end(); I
!= E
; ++I
) {
1057 Pass
*Impl
= findAnalysisPass(*I
, true);
1059 // This may be analysis pass that is initialized on the fly.
1060 // If that is not the case then it will raise an assert when it is used.
1062 AnalysisResolver
*AR
= P
->getResolver();
1063 assert(AR
&& "Analysis Resolver is not set");
1064 AR
->addAnalysisImplsPair(*I
, Impl
);
1068 /// Find the pass that implements Analysis AID. If desired pass is not found
1069 /// then return NULL.
1070 Pass
*PMDataManager::findAnalysisPass(AnalysisID AID
, bool SearchParent
) {
1072 // Check if AvailableAnalysis map has one entry.
1073 std::map
<AnalysisID
, Pass
*>::const_iterator I
= AvailableAnalysis
.find(AID
);
1075 if (I
!= AvailableAnalysis
.end())
1078 // Search Parents through TopLevelManager
1080 return TPM
->findAnalysisPass(AID
);
1085 // Print list of passes that are last used by P.
1086 void PMDataManager::dumpLastUses(Pass
*P
, unsigned Offset
) const{
1088 SmallVector
<Pass
*, 12> LUses
;
1090 // If this is a on the fly manager then it does not have TPM.
1094 TPM
->collectLastUses(LUses
, P
);
1096 for (SmallVectorImpl
<Pass
*>::iterator I
= LUses
.begin(),
1097 E
= LUses
.end(); I
!= E
; ++I
) {
1098 llvm::dbgs() << "--" << std::string(Offset
*2, ' ');
1099 (*I
)->dumpPassStructure(0);
1103 void PMDataManager::dumpPassArguments() const {
1104 for (SmallVectorImpl
<Pass
*>::const_iterator I
= PassVector
.begin(),
1105 E
= PassVector
.end(); I
!= E
; ++I
) {
1106 if (PMDataManager
*PMD
= (*I
)->getAsPMDataManager())
1107 PMD
->dumpPassArguments();
1109 if (const PassInfo
*PI
=
1110 PassRegistry::getPassRegistry()->getPassInfo((*I
)->getPassID()))
1111 if (!PI
->isAnalysisGroup())
1112 dbgs() << " -" << PI
->getPassArgument();
1116 void PMDataManager::dumpPassInfo(Pass
*P
, enum PassDebuggingString S1
,
1117 enum PassDebuggingString S2
,
1119 if (PassDebugging
< Executions
)
1121 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1124 dbgs() << "Executing Pass '" << P
->getPassName();
1126 case MODIFICATION_MSG
:
1127 dbgs() << "Made Modification '" << P
->getPassName();
1130 dbgs() << " Freeing Pass '" << P
->getPassName();
1136 case ON_BASICBLOCK_MSG
:
1137 dbgs() << "' on BasicBlock '" << Msg
<< "'...\n";
1139 case ON_FUNCTION_MSG
:
1140 dbgs() << "' on Function '" << Msg
<< "'...\n";
1143 dbgs() << "' on Module '" << Msg
<< "'...\n";
1146 dbgs() << "' on Region '" << Msg
<< "'...\n";
1149 dbgs() << "' on Loop '" << Msg
<< "'...\n";
1152 dbgs() << "' on Call Graph Nodes '" << Msg
<< "'...\n";
1159 void PMDataManager::dumpRequiredSet(const Pass
*P
) const {
1160 if (PassDebugging
< Details
)
1163 AnalysisUsage analysisUsage
;
1164 P
->getAnalysisUsage(analysisUsage
);
1165 dumpAnalysisUsage("Required", P
, analysisUsage
.getRequiredSet());
1168 void PMDataManager::dumpPreservedSet(const Pass
*P
) const {
1169 if (PassDebugging
< Details
)
1172 AnalysisUsage analysisUsage
;
1173 P
->getAnalysisUsage(analysisUsage
);
1174 dumpAnalysisUsage("Preserved", P
, analysisUsage
.getPreservedSet());
1177 void PMDataManager::dumpAnalysisUsage(StringRef Msg
, const Pass
*P
,
1178 const AnalysisUsage::VectorType
&Set
) const {
1179 assert(PassDebugging
>= Details
);
1182 dbgs() << (void*)P
<< std::string(getDepth()*2+3, ' ') << Msg
<< " Analyses:";
1183 for (unsigned i
= 0; i
!= Set
.size(); ++i
) {
1184 if (i
) dbgs() << ',';
1185 const PassInfo
*PInf
= PassRegistry::getPassRegistry()->getPassInfo(Set
[i
]);
1186 dbgs() << ' ' << PInf
->getPassName();
1191 /// Add RequiredPass into list of lower level passes required by pass P.
1192 /// RequiredPass is run on the fly by Pass Manager when P requests it
1193 /// through getAnalysis interface.
1194 /// This should be handled by specific pass manager.
1195 void PMDataManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1197 TPM
->dumpArguments();
1201 // Module Level pass may required Function Level analysis info
1202 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1203 // to provide this on demand. In that case, in Pass manager terminology,
1204 // module level pass is requiring lower level analysis info managed by
1205 // lower level pass manager.
1207 // When Pass manager is not able to order required analysis info, Pass manager
1208 // checks whether any lower level manager will be able to provide this
1209 // analysis info on demand or not.
1211 dbgs() << "Unable to schedule '" << RequiredPass
->getPassName();
1212 dbgs() << "' required by '" << P
->getPassName() << "'\n";
1214 llvm_unreachable("Unable to schedule pass");
1217 Pass
*PMDataManager::getOnTheFlyPass(Pass
*P
, AnalysisID PI
, Function
&F
) {
1218 assert(0 && "Unable to find on the fly pass");
1223 PMDataManager::~PMDataManager() {
1224 for (SmallVectorImpl
<Pass
*>::iterator I
= PassVector
.begin(),
1225 E
= PassVector
.end(); I
!= E
; ++I
)
1229 //===----------------------------------------------------------------------===//
1230 // NOTE: Is this the right place to define this method ?
1231 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1232 Pass
*AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID
, bool dir
) const {
1233 return PM
.findAnalysisPass(ID
, dir
);
1236 Pass
*AnalysisResolver::findImplPass(Pass
*P
, AnalysisID AnalysisPI
,
1238 return PM
.getOnTheFlyPass(P
, AnalysisPI
, F
);
1241 //===----------------------------------------------------------------------===//
1242 // BBPassManager implementation
1244 /// Execute all of the passes scheduled for execution by invoking
1245 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1246 /// the function, and if so, return true.
1247 bool BBPassManager::runOnFunction(Function
&F
) {
1248 if (F
.isDeclaration())
1251 bool Changed
= doInitialization(F
);
1253 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ++I
)
1254 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1255 BasicBlockPass
*BP
= getContainedPass(Index
);
1256 bool LocalChanged
= false;
1258 dumpPassInfo(BP
, EXECUTION_MSG
, ON_BASICBLOCK_MSG
, I
->getName());
1259 dumpRequiredSet(BP
);
1261 initializeAnalysisImpl(BP
);
1264 // If the pass crashes, remember this.
1265 PassManagerPrettyStackEntry
X(BP
, *I
);
1266 TimeRegion
PassTimer(getPassTimer(BP
));
1268 LocalChanged
|= BP
->runOnBasicBlock(*I
);
1271 Changed
|= LocalChanged
;
1273 dumpPassInfo(BP
, MODIFICATION_MSG
, ON_BASICBLOCK_MSG
,
1275 dumpPreservedSet(BP
);
1277 verifyPreservedAnalysis(BP
);
1278 removeNotPreservedAnalysis(BP
);
1279 recordAvailableAnalysis(BP
);
1280 removeDeadPasses(BP
, I
->getName(), ON_BASICBLOCK_MSG
);
1283 return doFinalization(F
) || Changed
;
1286 // Implement doInitialization and doFinalization
1287 bool BBPassManager::doInitialization(Module
&M
) {
1288 bool Changed
= false;
1290 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1291 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1296 bool BBPassManager::doFinalization(Module
&M
) {
1297 bool Changed
= false;
1299 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1300 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1305 bool BBPassManager::doInitialization(Function
&F
) {
1306 bool Changed
= false;
1308 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1309 BasicBlockPass
*BP
= getContainedPass(Index
);
1310 Changed
|= BP
->doInitialization(F
);
1316 bool BBPassManager::doFinalization(Function
&F
) {
1317 bool Changed
= false;
1319 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1320 BasicBlockPass
*BP
= getContainedPass(Index
);
1321 Changed
|= BP
->doFinalization(F
);
1328 //===----------------------------------------------------------------------===//
1329 // FunctionPassManager implementation
1331 /// Create new Function pass manager
1332 FunctionPassManager::FunctionPassManager(Module
*m
) : M(m
) {
1333 FPM
= new FunctionPassManagerImpl(0);
1334 // FPM is the top level manager.
1335 FPM
->setTopLevelManager(FPM
);
1337 AnalysisResolver
*AR
= new AnalysisResolver(*FPM
);
1338 FPM
->setResolver(AR
);
1341 FunctionPassManager::~FunctionPassManager() {
1345 /// addImpl - Add a pass to the queue of passes to run, without
1346 /// checking whether to add a printer pass.
1347 void FunctionPassManager::addImpl(Pass
*P
) {
1351 /// add - Add a pass to the queue of passes to run. This passes
1352 /// ownership of the Pass to the PassManager. When the
1353 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1354 /// there is no need to delete the pass. (TODO delete passes.)
1355 /// This implies that all passes MUST be allocated with 'new'.
1356 void FunctionPassManager::add(Pass
*P
) {
1357 // If this is a not a function pass, don't add a printer for it.
1358 const void *PassID
= P
->getPassID();
1359 if (P
->getPassKind() == PT_Function
)
1360 if (ShouldPrintBeforePass(PassID
))
1361 addImpl(P
->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1362 + P
->getPassName() + " ***"));
1366 if (P
->getPassKind() == PT_Function
)
1367 if (ShouldPrintAfterPass(PassID
))
1368 addImpl(P
->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1369 + P
->getPassName() + " ***"));
1372 /// run - Execute all of the passes scheduled for execution. Keep
1373 /// track of whether any of the passes modifies the function, and if
1374 /// so, return true.
1376 bool FunctionPassManager::run(Function
&F
) {
1377 if (F
.isMaterializable()) {
1379 if (F
.Materialize(&errstr
))
1380 report_fatal_error("Error reading bitcode file: " + Twine(errstr
));
1386 /// doInitialization - Run all of the initializers for the function passes.
1388 bool FunctionPassManager::doInitialization() {
1389 return FPM
->doInitialization(*M
);
1392 /// doFinalization - Run all of the finalizers for the function passes.
1394 bool FunctionPassManager::doFinalization() {
1395 return FPM
->doFinalization(*M
);
1398 //===----------------------------------------------------------------------===//
1399 // FunctionPassManagerImpl implementation
1401 bool FunctionPassManagerImpl::doInitialization(Module
&M
) {
1402 bool Changed
= false;
1407 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1408 Changed
|= getContainedManager(Index
)->doInitialization(M
);
1413 bool FunctionPassManagerImpl::doFinalization(Module
&M
) {
1414 bool Changed
= false;
1416 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1417 Changed
|= getContainedManager(Index
)->doFinalization(M
);
1422 /// cleanup - After running all passes, clean up pass manager cache.
1423 void FPPassManager::cleanup() {
1424 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1425 FunctionPass
*FP
= getContainedPass(Index
);
1426 AnalysisResolver
*AR
= FP
->getResolver();
1427 assert(AR
&& "Analysis Resolver is not set");
1428 AR
->clearAnalysisImpls();
1432 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1435 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
1436 FPPassManager
*FPPM
= getContainedManager(Index
);
1437 for (unsigned Index
= 0; Index
< FPPM
->getNumContainedPasses(); ++Index
) {
1438 FPPM
->getContainedPass(Index
)->releaseMemory();
1444 // Execute all the passes managed by this top level manager.
1445 // Return true if any function is modified by a pass.
1446 bool FunctionPassManagerImpl::run(Function
&F
) {
1447 bool Changed
= false;
1448 TimingInfo::createTheTimeInfo();
1449 createDebugInfoProbe();
1451 initializeAllAnalysisInfo();
1452 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1453 Changed
|= getContainedManager(Index
)->runOnFunction(F
);
1455 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1456 getContainedManager(Index
)->cleanup();
1462 //===----------------------------------------------------------------------===//
1463 // FPPassManager implementation
1465 char FPPassManager::ID
= 0;
1466 /// Print passes managed by this manager
1467 void FPPassManager::dumpPassStructure(unsigned Offset
) {
1468 llvm::dbgs() << std::string(Offset
*2, ' ') << "FunctionPass Manager\n";
1469 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1470 FunctionPass
*FP
= getContainedPass(Index
);
1471 FP
->dumpPassStructure(Offset
+ 1);
1472 dumpLastUses(FP
, Offset
+1);
1477 /// Execute all of the passes scheduled for execution by invoking
1478 /// runOnFunction method. Keep track of whether any of the passes modifies
1479 /// the function, and if so, return true.
1480 bool FPPassManager::runOnFunction(Function
&F
) {
1481 if (F
.isDeclaration())
1484 bool Changed
= false;
1486 // Collect inherited analysis from Module level pass manager.
1487 populateInheritedAnalysis(TPM
->activeStack
);
1489 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1490 FunctionPass
*FP
= getContainedPass(Index
);
1491 bool LocalChanged
= false;
1493 dumpPassInfo(FP
, EXECUTION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1494 dumpRequiredSet(FP
);
1496 initializeAnalysisImpl(FP
);
1498 TheDebugProbe
->initialize(FP
, F
);
1500 PassManagerPrettyStackEntry
X(FP
, F
);
1501 TimeRegion
PassTimer(getPassTimer(FP
));
1503 LocalChanged
|= FP
->runOnFunction(F
);
1506 TheDebugProbe
->finalize(FP
, F
);
1508 Changed
|= LocalChanged
;
1510 dumpPassInfo(FP
, MODIFICATION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1511 dumpPreservedSet(FP
);
1513 verifyPreservedAnalysis(FP
);
1514 removeNotPreservedAnalysis(FP
);
1515 recordAvailableAnalysis(FP
);
1516 removeDeadPasses(FP
, F
.getName(), ON_FUNCTION_MSG
);
1521 bool FPPassManager::runOnModule(Module
&M
) {
1522 bool Changed
= doInitialization(M
);
1524 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
1527 return doFinalization(M
) || Changed
;
1530 bool FPPassManager::doInitialization(Module
&M
) {
1531 bool Changed
= false;
1533 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1534 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1539 bool FPPassManager::doFinalization(Module
&M
) {
1540 bool Changed
= false;
1542 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1543 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1548 //===----------------------------------------------------------------------===//
1549 // MPPassManager implementation
1551 /// Execute all of the passes scheduled for execution by invoking
1552 /// runOnModule method. Keep track of whether any of the passes modifies
1553 /// the module, and if so, return true.
1555 MPPassManager::runOnModule(Module
&M
) {
1556 bool Changed
= false;
1558 // Initialize on-the-fly passes
1559 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
1560 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
1562 FunctionPassManagerImpl
*FPP
= I
->second
;
1563 Changed
|= FPP
->doInitialization(M
);
1566 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1567 ModulePass
*MP
= getContainedPass(Index
);
1568 bool LocalChanged
= false;
1570 dumpPassInfo(MP
, EXECUTION_MSG
, ON_MODULE_MSG
, M
.getModuleIdentifier());
1571 dumpRequiredSet(MP
);
1573 initializeAnalysisImpl(MP
);
1576 PassManagerPrettyStackEntry
X(MP
, M
);
1577 TimeRegion
PassTimer(getPassTimer(MP
));
1579 LocalChanged
|= MP
->runOnModule(M
);
1582 Changed
|= LocalChanged
;
1584 dumpPassInfo(MP
, MODIFICATION_MSG
, ON_MODULE_MSG
,
1585 M
.getModuleIdentifier());
1586 dumpPreservedSet(MP
);
1588 verifyPreservedAnalysis(MP
);
1589 removeNotPreservedAnalysis(MP
);
1590 recordAvailableAnalysis(MP
);
1591 removeDeadPasses(MP
, M
.getModuleIdentifier(), ON_MODULE_MSG
);
1594 // Finalize on-the-fly passes
1595 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
1596 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
1598 FunctionPassManagerImpl
*FPP
= I
->second
;
1599 // We don't know when is the last time an on-the-fly pass is run,
1600 // so we need to releaseMemory / finalize here
1601 FPP
->releaseMemoryOnTheFly();
1602 Changed
|= FPP
->doFinalization(M
);
1607 /// Add RequiredPass into list of lower level passes required by pass P.
1608 /// RequiredPass is run on the fly by Pass Manager when P requests it
1609 /// through getAnalysis interface.
1610 void MPPassManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1611 assert(P
->getPotentialPassManagerType() == PMT_ModulePassManager
&&
1612 "Unable to handle Pass that requires lower level Analysis pass");
1613 assert((P
->getPotentialPassManagerType() <
1614 RequiredPass
->getPotentialPassManagerType()) &&
1615 "Unable to handle Pass that requires lower level Analysis pass");
1617 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[P
];
1619 FPP
= new FunctionPassManagerImpl(0);
1620 // FPP is the top level manager.
1621 FPP
->setTopLevelManager(FPP
);
1623 OnTheFlyManagers
[P
] = FPP
;
1625 FPP
->add(RequiredPass
);
1627 // Register P as the last user of RequiredPass.
1628 SmallVector
<Pass
*, 1> LU
;
1629 LU
.push_back(RequiredPass
);
1630 FPP
->setLastUser(LU
, P
);
1633 /// Return function pass corresponding to PassInfo PI, that is
1634 /// required by module pass MP. Instantiate analysis pass, by using
1635 /// its runOnFunction() for function F.
1636 Pass
* MPPassManager::getOnTheFlyPass(Pass
*MP
, AnalysisID PI
, Function
&F
){
1637 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[MP
];
1638 assert(FPP
&& "Unable to find on the fly pass");
1640 FPP
->releaseMemoryOnTheFly();
1642 return ((PMTopLevelManager
*)FPP
)->findAnalysisPass(PI
);
1646 //===----------------------------------------------------------------------===//
1647 // PassManagerImpl implementation
1649 /// run - Execute all of the passes scheduled for execution. Keep track of
1650 /// whether any of the passes modifies the module, and if so, return true.
1651 bool PassManagerImpl::run(Module
&M
) {
1652 bool Changed
= false;
1653 TimingInfo::createTheTimeInfo();
1654 createDebugInfoProbe();
1659 initializeAllAnalysisInfo();
1660 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1661 Changed
|= getContainedManager(Index
)->runOnModule(M
);
1665 //===----------------------------------------------------------------------===//
1666 // PassManager implementation
1668 /// Create new pass manager
1669 PassManager::PassManager() {
1670 PM
= new PassManagerImpl(0);
1671 // PM is the top level manager
1672 PM
->setTopLevelManager(PM
);
1675 PassManager::~PassManager() {
1679 /// addImpl - Add a pass to the queue of passes to run, without
1680 /// checking whether to add a printer pass.
1681 void PassManager::addImpl(Pass
*P
) {
1685 /// add - Add a pass to the queue of passes to run. This passes ownership of
1686 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1687 /// will be destroyed as well, so there is no need to delete the pass. This
1688 /// implies that all passes MUST be allocated with 'new'.
1689 void PassManager::add(Pass
*P
) {
1690 const void* PassID
= P
->getPassID();
1691 if (ShouldPrintBeforePass(PassID
))
1692 addImpl(P
->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1693 + P
->getPassName() + " ***"));
1697 if (ShouldPrintAfterPass(PassID
))
1698 addImpl(P
->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1699 + P
->getPassName() + " ***"));
1702 /// run - Execute all of the passes scheduled for execution. Keep track of
1703 /// whether any of the passes modifies the module, and if so, return true.
1704 bool PassManager::run(Module
&M
) {
1708 //===----------------------------------------------------------------------===//
1709 // TimingInfo Class - This class is used to calculate information about the
1710 // amount of time each pass takes to execute. This only happens with
1711 // -time-passes is enabled on the command line.
1713 bool llvm::TimePassesIsEnabled
= false;
1714 static cl::opt
<bool,true>
1715 EnableTiming("time-passes", cl::location(TimePassesIsEnabled
),
1716 cl::desc("Time each pass, printing elapsed time for each on exit"));
1718 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1719 // a non null value (if the -time-passes option is enabled) or it leaves it
1720 // null. It may be called multiple times.
1721 void TimingInfo::createTheTimeInfo() {
1722 if (!TimePassesIsEnabled
|| TheTimeInfo
) return;
1724 // Constructed the first time this is called, iff -time-passes is enabled.
1725 // This guarantees that the object will be constructed before static globals,
1726 // thus it will be destroyed before them.
1727 static ManagedStatic
<TimingInfo
> TTI
;
1728 TheTimeInfo
= &*TTI
;
1731 /// If TimingInfo is enabled then start pass timer.
1732 Timer
*llvm::getPassTimer(Pass
*P
) {
1734 return TheTimeInfo
->getPassTimer(P
);
1738 //===----------------------------------------------------------------------===//
1739 // PMStack implementation
1742 // Pop Pass Manager from the stack and clear its analysis info.
1743 void PMStack::pop() {
1745 PMDataManager
*Top
= this->top();
1746 Top
->initializeAnalysisInfo();
1751 // Push PM on the stack and set its top level manager.
1752 void PMStack::push(PMDataManager
*PM
) {
1753 assert(PM
&& "Unable to push. Pass Manager expected");
1755 if (!this->empty()) {
1756 PMTopLevelManager
*TPM
= this->top()->getTopLevelManager();
1758 assert(TPM
&& "Unable to find top level manager");
1759 TPM
->addIndirectPassManager(PM
);
1760 PM
->setTopLevelManager(TPM
);
1766 // Dump content of the pass manager stack.
1767 void PMStack::dump() const {
1768 for (std::vector
<PMDataManager
*>::const_iterator I
= S
.begin(),
1769 E
= S
.end(); I
!= E
; ++I
)
1770 printf("%s ", (*I
)->getAsPass()->getPassName());
1776 /// Find appropriate Module Pass Manager in the PM Stack and
1777 /// add self into that manager.
1778 void ModulePass::assignPassManager(PMStack
&PMS
,
1779 PassManagerType PreferredType
) {
1780 // Find Module Pass Manager
1781 while (!PMS
.empty()) {
1782 PassManagerType TopPMType
= PMS
.top()->getPassManagerType();
1783 if (TopPMType
== PreferredType
)
1784 break; // We found desired pass manager
1785 else if (TopPMType
> PMT_ModulePassManager
)
1786 PMS
.pop(); // Pop children pass managers
1790 assert(!PMS
.empty() && "Unable to find appropriate Pass Manager");
1791 PMS
.top()->add(this);
1794 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1795 /// in the PM Stack and add self into that manager.
1796 void FunctionPass::assignPassManager(PMStack
&PMS
,
1797 PassManagerType PreferredType
) {
1799 // Find Module Pass Manager
1800 while (!PMS
.empty()) {
1801 if (PMS
.top()->getPassManagerType() > PMT_FunctionPassManager
)
1807 // Create new Function Pass Manager if needed.
1809 if (PMS
.top()->getPassManagerType() == PMT_FunctionPassManager
) {
1810 FPP
= (FPPassManager
*)PMS
.top();
1812 assert(!PMS
.empty() && "Unable to create Function Pass Manager");
1813 PMDataManager
*PMD
= PMS
.top();
1815 // [1] Create new Function Pass Manager
1816 FPP
= new FPPassManager(PMD
->getDepth() + 1);
1817 FPP
->populateInheritedAnalysis(PMS
);
1819 // [2] Set up new manager's top level manager
1820 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1821 TPM
->addIndirectPassManager(FPP
);
1823 // [3] Assign manager to manage this new manager. This may create
1824 // and push new managers into PMS
1825 FPP
->assignPassManager(PMS
, PMD
->getPassManagerType());
1827 // [4] Push new manager into PMS
1831 // Assign FPP as the manager of this pass.
1835 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1836 /// in the PM Stack and add self into that manager.
1837 void BasicBlockPass::assignPassManager(PMStack
&PMS
,
1838 PassManagerType PreferredType
) {
1841 // Basic Pass Manager is a leaf pass manager. It does not handle
1842 // any other pass manager.
1844 PMS
.top()->getPassManagerType() == PMT_BasicBlockPassManager
) {
1845 BBP
= (BBPassManager
*)PMS
.top();
1847 // If leaf manager is not Basic Block Pass manager then create new
1848 // basic Block Pass manager.
1849 assert(!PMS
.empty() && "Unable to create BasicBlock Pass Manager");
1850 PMDataManager
*PMD
= PMS
.top();
1852 // [1] Create new Basic Block Manager
1853 BBP
= new BBPassManager(PMD
->getDepth() + 1);
1855 // [2] Set up new manager's top level manager
1856 // Basic Block Pass Manager does not live by itself
1857 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1858 TPM
->addIndirectPassManager(BBP
);
1860 // [3] Assign manager to manage this new manager. This may create
1861 // and push new managers into PMS
1862 BBP
->assignPassManager(PMS
, PreferredType
);
1864 // [4] Push new manager into PMS
1868 // Assign BBP as the manager of this pass.
1872 PassManagerBase::~PassManagerBase() {}