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/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/System/Mutex.h"
24 #include "llvm/System/Threading.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm-c/Core.h"
32 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 None
, Arguments
, Structure
, Executions
, Details
48 // Always verify dominfo if expensive checking is enabled.
50 bool VerifyDomInfo
= true;
52 bool VerifyDomInfo
= false;
54 static cl::opt
<bool,true>
55 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo
),
56 cl::desc("Verify dominator info (time consuming)"));
58 static cl::opt
<enum PassDebugLevel
>
59 PassDebugging("debug-pass", cl::Hidden
,
60 cl::desc("Print PassManager debugging information"),
62 clEnumVal(None
, "disable debug output"),
63 clEnumVal(Arguments
, "print pass arguments to pass to 'opt'"),
64 clEnumVal(Structure
, "print pass structure before run()"),
65 clEnumVal(Executions
, "print pass name before it is executed"),
66 clEnumVal(Details
, "print pass details when it is executed"),
68 } // End of llvm namespace
70 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
71 /// or higher is specified.
72 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
73 return PassDebugging
>= Executions
;
79 void PassManagerPrettyStackEntry::print(raw_ostream
&OS
) const {
81 OS
<< "Releasing pass '";
83 OS
<< "Running pass '";
85 OS
<< P
->getPassName() << "'";
88 OS
<< " on module '" << M
->getModuleIdentifier() << "'.\n";
99 else if (isa
<BasicBlock
>(V
))
105 WriteAsOperand(OS
, V
, /*PrintTy=*/false, M
);
112 //===----------------------------------------------------------------------===//
115 /// BBPassManager manages BasicBlockPass. It batches all the
116 /// pass together and sequence them to process one basic block before
117 /// processing next basic block.
118 class VISIBILITY_HIDDEN BBPassManager
: public PMDataManager
,
119 public FunctionPass
{
123 explicit BBPassManager(int Depth
)
124 : PMDataManager(Depth
), FunctionPass(&ID
) {}
126 /// Execute all of the passes scheduled for execution. Keep track of
127 /// whether any of the passes modifies the function, and if so, return true.
128 bool runOnFunction(Function
&F
);
130 /// Pass Manager itself does not invalidate any analysis info.
131 void getAnalysisUsage(AnalysisUsage
&Info
) const {
132 Info
.setPreservesAll();
135 bool doInitialization(Module
&M
);
136 bool doInitialization(Function
&F
);
137 bool doFinalization(Module
&M
);
138 bool doFinalization(Function
&F
);
140 virtual const char *getPassName() const {
141 return "BasicBlock Pass Manager";
144 // Print passes managed by this manager
145 void dumpPassStructure(unsigned Offset
) {
146 llvm::errs() << std::string(Offset
*2, ' ') << "BasicBlockPass Manager\n";
147 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
148 BasicBlockPass
*BP
= getContainedPass(Index
);
149 BP
->dumpPassStructure(Offset
+ 1);
150 dumpLastUses(BP
, Offset
+1);
154 BasicBlockPass
*getContainedPass(unsigned N
) {
155 assert(N
< PassVector
.size() && "Pass number out of range!");
156 BasicBlockPass
*BP
= static_cast<BasicBlockPass
*>(PassVector
[N
]);
160 virtual PassManagerType
getPassManagerType() const {
161 return PMT_BasicBlockPassManager
;
165 char BBPassManager::ID
= 0;
170 //===----------------------------------------------------------------------===//
171 // FunctionPassManagerImpl
173 /// FunctionPassManagerImpl manages FPPassManagers
174 class FunctionPassManagerImpl
: public Pass
,
175 public PMDataManager
,
176 public PMTopLevelManager
{
181 explicit FunctionPassManagerImpl(int Depth
) :
182 Pass(&ID
), PMDataManager(Depth
),
183 PMTopLevelManager(TLM_Function
), wasRun(false) { }
185 /// add - Add a pass to the queue of passes to run. This passes ownership of
186 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
187 /// will be destroyed as well, so there is no need to delete the pass. This
188 /// implies that all passes MUST be allocated with 'new'.
193 // Prepare for running an on the fly pass, freeing memory if needed
194 // from a previous run.
195 void releaseMemoryOnTheFly();
197 /// run - Execute all of the passes scheduled for execution. Keep track of
198 /// whether any of the passes modifies the module, and if so, return true.
199 bool run(Function
&F
);
201 /// doInitialization - Run all of the initializers for the function passes.
203 bool doInitialization(Module
&M
);
205 /// doFinalization - Run all of the finalizers for the function passes.
207 bool doFinalization(Module
&M
);
209 /// Pass Manager itself does not invalidate any analysis info.
210 void getAnalysisUsage(AnalysisUsage
&Info
) const {
211 Info
.setPreservesAll();
214 inline void addTopLevelPass(Pass
*P
) {
216 if (ImmutablePass
*IP
= dynamic_cast<ImmutablePass
*> (P
)) {
218 // P is a immutable pass and it will be managed by this
219 // top level manager. Set up analysis resolver to connect them.
220 AnalysisResolver
*AR
= new AnalysisResolver(*this);
222 initializeAnalysisImpl(P
);
223 addImmutablePass(IP
);
224 recordAvailableAnalysis(IP
);
226 P
->assignPassManager(activeStack
);
231 FPPassManager
*getContainedManager(unsigned N
) {
232 assert(N
< PassManagers
.size() && "Pass number out of range!");
233 FPPassManager
*FP
= static_cast<FPPassManager
*>(PassManagers
[N
]);
238 char FunctionPassManagerImpl::ID
= 0;
239 //===----------------------------------------------------------------------===//
242 /// MPPassManager manages ModulePasses and function pass managers.
243 /// It batches all Module passes and function pass managers together and
244 /// sequences them to process one module.
245 class MPPassManager
: public Pass
, public PMDataManager
{
248 explicit MPPassManager(int Depth
) :
249 Pass(&ID
), PMDataManager(Depth
) { }
251 // Delete on the fly managers.
252 virtual ~MPPassManager() {
253 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
254 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
256 FunctionPassManagerImpl
*FPP
= I
->second
;
261 /// run - Execute all of the passes scheduled for execution. Keep track of
262 /// whether any of the passes modifies the module, and if so, return true.
263 bool runOnModule(Module
&M
);
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage
&Info
) const {
267 Info
.setPreservesAll();
270 /// Add RequiredPass into list of lower level passes required by pass P.
271 /// RequiredPass is run on the fly by Pass Manager when P requests it
272 /// through getAnalysis interface.
273 virtual void addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
);
275 /// Return function pass corresponding to PassInfo PI, that is
276 /// required by module pass MP. Instantiate analysis pass, by using
277 /// its runOnFunction() for function F.
278 virtual Pass
* getOnTheFlyPass(Pass
*MP
, const PassInfo
*PI
, Function
&F
);
280 virtual const char *getPassName() const {
281 return "Module Pass Manager";
284 // Print passes managed by this manager
285 void dumpPassStructure(unsigned Offset
) {
286 llvm::errs() << std::string(Offset
*2, ' ') << "ModulePass Manager\n";
287 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
288 ModulePass
*MP
= getContainedPass(Index
);
289 MP
->dumpPassStructure(Offset
+ 1);
290 std::map
<Pass
*, FunctionPassManagerImpl
*>::const_iterator I
=
291 OnTheFlyManagers
.find(MP
);
292 if (I
!= OnTheFlyManagers
.end())
293 I
->second
->dumpPassStructure(Offset
+ 2);
294 dumpLastUses(MP
, Offset
+1);
298 ModulePass
*getContainedPass(unsigned N
) {
299 assert(N
< PassVector
.size() && "Pass number out of range!");
300 return static_cast<ModulePass
*>(PassVector
[N
]);
303 virtual PassManagerType
getPassManagerType() const {
304 return PMT_ModulePassManager
;
308 /// Collection of on the fly FPPassManagers. These managers manage
309 /// function passes that are required by module passes.
310 std::map
<Pass
*, FunctionPassManagerImpl
*> OnTheFlyManagers
;
313 char MPPassManager::ID
= 0;
314 //===----------------------------------------------------------------------===//
318 /// PassManagerImpl manages MPPassManagers
319 class PassManagerImpl
: public Pass
,
320 public PMDataManager
,
321 public PMTopLevelManager
{
325 explicit PassManagerImpl(int Depth
) :
326 Pass(&ID
), PMDataManager(Depth
), PMTopLevelManager(TLM_Pass
) { }
328 /// add - Add a pass to the queue of passes to run. This passes ownership of
329 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
330 /// will be destroyed as well, so there is no need to delete the pass. This
331 /// implies that all passes MUST be allocated with 'new'.
336 /// run - Execute all of the passes scheduled for execution. Keep track of
337 /// whether any of the passes modifies the module, and if so, return true.
340 /// Pass Manager itself does not invalidate any analysis info.
341 void getAnalysisUsage(AnalysisUsage
&Info
) const {
342 Info
.setPreservesAll();
345 inline void addTopLevelPass(Pass
*P
) {
346 if (ImmutablePass
*IP
= dynamic_cast<ImmutablePass
*> (P
)) {
348 // P is a immutable pass and it will be managed by this
349 // top level manager. Set up analysis resolver to connect them.
350 AnalysisResolver
*AR
= new AnalysisResolver(*this);
352 initializeAnalysisImpl(P
);
353 addImmutablePass(IP
);
354 recordAvailableAnalysis(IP
);
356 P
->assignPassManager(activeStack
);
360 MPPassManager
*getContainedManager(unsigned N
) {
361 assert(N
< PassManagers
.size() && "Pass number out of range!");
362 MPPassManager
*MP
= static_cast<MPPassManager
*>(PassManagers
[N
]);
367 char PassManagerImpl::ID
= 0;
368 } // End of llvm namespace
372 //===----------------------------------------------------------------------===//
373 /// TimingInfo Class - This class is used to calculate information about the
374 /// amount of time each pass takes to execute. This only happens when
375 /// -time-passes is enabled on the command line.
378 static ManagedStatic
<sys::SmartMutex
<true> > TimingInfoMutex
;
380 class VISIBILITY_HIDDEN TimingInfo
{
381 std::map
<Pass
*, Timer
> TimingData
;
385 // Use 'create' member to get this.
386 TimingInfo() : TG("... Pass execution timing report ...") {}
388 // TimingDtor - Print out information about timing information
390 // Delete all of the timers...
392 // TimerGroup is deleted next, printing the report.
395 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
396 // to a non null value (if the -time-passes option is enabled) or it leaves it
397 // null. It may be called multiple times.
398 static void createTheTimeInfo();
400 void passStarted(Pass
*P
) {
401 if (dynamic_cast<PMDataManager
*>(P
))
404 sys::SmartScopedLock
<true> Lock(*TimingInfoMutex
);
405 std::map
<Pass
*, Timer
>::iterator I
= TimingData
.find(P
);
406 if (I
== TimingData
.end())
407 I
=TimingData
.insert(std::make_pair(P
, Timer(P
->getPassName(), TG
))).first
;
408 I
->second
.startTimer();
411 void passEnded(Pass
*P
) {
412 if (dynamic_cast<PMDataManager
*>(P
))
415 sys::SmartScopedLock
<true> Lock(*TimingInfoMutex
);
416 std::map
<Pass
*, Timer
>::iterator I
= TimingData
.find(P
);
417 assert(I
!= TimingData
.end() && "passStarted/passEnded not nested right!");
418 I
->second
.stopTimer();
422 } // End of anon namespace
424 static TimingInfo
*TheTimeInfo
;
426 //===----------------------------------------------------------------------===//
427 // PMTopLevelManager implementation
429 /// Initialize top level manager. Create first pass manager.
430 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t
) {
432 MPPassManager
*MPP
= new MPPassManager(1);
433 MPP
->setTopLevelManager(this);
435 activeStack
.push(MPP
);
436 } else if (t
== TLM_Function
) {
437 FPPassManager
*FPP
= new FPPassManager(1);
438 FPP
->setTopLevelManager(this);
440 activeStack
.push(FPP
);
444 /// Set pass P as the last user of the given analysis passes.
445 void PMTopLevelManager::setLastUser(SmallVector
<Pass
*, 12> &AnalysisPasses
,
447 for (SmallVector
<Pass
*, 12>::iterator I
= AnalysisPasses
.begin(),
448 E
= AnalysisPasses
.end(); I
!= E
; ++I
) {
455 // If AP is the last user of other passes then make P last user of
457 for (DenseMap
<Pass
*, Pass
*>::iterator LUI
= LastUser
.begin(),
458 LUE
= LastUser
.end(); LUI
!= LUE
; ++LUI
) {
459 if (LUI
->second
== AP
)
460 // DenseMap iterator is not invalidated here because
461 // this is just updating exisitng entry.
462 LastUser
[LUI
->first
] = P
;
467 /// Collect passes whose last user is P
468 void PMTopLevelManager::collectLastUses(SmallVector
<Pass
*, 12> &LastUses
,
470 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator DMI
=
471 InversedLastUser
.find(P
);
472 if (DMI
== InversedLastUser
.end())
475 SmallPtrSet
<Pass
*, 8> &LU
= DMI
->second
;
476 for (SmallPtrSet
<Pass
*, 8>::iterator I
= LU
.begin(),
477 E
= LU
.end(); I
!= E
; ++I
) {
478 LastUses
.push_back(*I
);
483 AnalysisUsage
*PMTopLevelManager::findAnalysisUsage(Pass
*P
) {
484 AnalysisUsage
*AnUsage
= NULL
;
485 DenseMap
<Pass
*, AnalysisUsage
*>::iterator DMI
= AnUsageMap
.find(P
);
486 if (DMI
!= AnUsageMap
.end())
487 AnUsage
= DMI
->second
;
489 AnUsage
= new AnalysisUsage();
490 P
->getAnalysisUsage(*AnUsage
);
491 AnUsageMap
[P
] = AnUsage
;
496 /// Schedule pass P for execution. Make sure that passes required by
497 /// P are run before P is run. Update analysis info maintained by
498 /// the manager. Remove dead passes. This is a recursive function.
499 void PMTopLevelManager::schedulePass(Pass
*P
) {
501 // TODO : Allocate function manager for this pass, other wise required set
502 // may be inserted into previous function manager
504 // Give pass a chance to prepare the stage.
505 P
->preparePassManager(activeStack
);
507 // If P is an analysis pass and it is available then do not
508 // generate the analysis again. Stale analysis info should not be
509 // available at this point.
510 if (P
->getPassInfo() &&
511 P
->getPassInfo()->isAnalysis() && findAnalysisPass(P
->getPassInfo())) {
516 AnalysisUsage
*AnUsage
= findAnalysisUsage(P
);
518 bool checkAnalysis
= true;
519 while (checkAnalysis
) {
520 checkAnalysis
= false;
522 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
523 for (AnalysisUsage::VectorType::const_iterator I
= RequiredSet
.begin(),
524 E
= RequiredSet
.end(); I
!= E
; ++I
) {
526 Pass
*AnalysisPass
= findAnalysisPass(*I
);
528 AnalysisPass
= (*I
)->createPass();
529 if (P
->getPotentialPassManagerType () ==
530 AnalysisPass
->getPotentialPassManagerType())
531 // Schedule analysis pass that is managed by the same pass manager.
532 schedulePass(AnalysisPass
);
533 else if (P
->getPotentialPassManagerType () >
534 AnalysisPass
->getPotentialPassManagerType()) {
535 // Schedule analysis pass that is managed by a new manager.
536 schedulePass(AnalysisPass
);
537 // Recheck analysis passes to ensure that required analysises that
538 // are already checked are still available.
539 checkAnalysis
= true;
542 // Do not schedule this analysis. Lower level analsyis
543 // passes are run on the fly.
549 // Now all required passes are available.
553 /// Find the pass that implements Analysis AID. Search immutable
554 /// passes and all pass managers. If desired pass is not found
555 /// then return NULL.
556 Pass
*PMTopLevelManager::findAnalysisPass(AnalysisID AID
) {
559 // Check pass managers
560 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
561 E
= PassManagers
.end(); P
== NULL
&& I
!= E
; ++I
) {
562 PMDataManager
*PMD
= *I
;
563 P
= PMD
->findAnalysisPass(AID
, false);
566 // Check other pass managers
567 for (SmallVector
<PMDataManager
*, 8>::iterator
568 I
= IndirectPassManagers
.begin(),
569 E
= IndirectPassManagers
.end(); P
== NULL
&& I
!= E
; ++I
)
570 P
= (*I
)->findAnalysisPass(AID
, false);
572 for (SmallVector
<ImmutablePass
*, 8>::iterator I
= ImmutablePasses
.begin(),
573 E
= ImmutablePasses
.end(); P
== NULL
&& I
!= E
; ++I
) {
574 const PassInfo
*PI
= (*I
)->getPassInfo();
578 // If Pass not found then check the interfaces implemented by Immutable Pass
580 const std::vector
<const PassInfo
*> &ImmPI
=
581 PI
->getInterfacesImplemented();
582 if (std::find(ImmPI
.begin(), ImmPI
.end(), AID
) != ImmPI
.end())
590 // Print passes managed by this top level manager.
591 void PMTopLevelManager::dumpPasses() const {
593 if (PassDebugging
< Structure
)
596 // Print out the immutable passes
597 for (unsigned i
= 0, e
= ImmutablePasses
.size(); i
!= e
; ++i
) {
598 ImmutablePasses
[i
]->dumpPassStructure(0);
601 // Every class that derives from PMDataManager also derives from Pass
602 // (sometimes indirectly), but there's no inheritance relationship
603 // between PMDataManager and Pass, so we have to dynamic_cast to get
604 // from a PMDataManager* to a Pass*.
605 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
606 E
= PassManagers
.end(); I
!= E
; ++I
)
607 dynamic_cast<Pass
*>(*I
)->dumpPassStructure(1);
610 void PMTopLevelManager::dumpArguments() const {
612 if (PassDebugging
< Arguments
)
615 errs() << "Pass Arguments: ";
616 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
617 E
= PassManagers
.end(); I
!= E
; ++I
)
618 (*I
)->dumpPassArguments();
622 void PMTopLevelManager::initializeAllAnalysisInfo() {
623 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
624 E
= PassManagers
.end(); I
!= E
; ++I
)
625 (*I
)->initializeAnalysisInfo();
627 // Initailize other pass managers
628 for (SmallVector
<PMDataManager
*, 8>::iterator I
= IndirectPassManagers
.begin(),
629 E
= IndirectPassManagers
.end(); I
!= E
; ++I
)
630 (*I
)->initializeAnalysisInfo();
632 for (DenseMap
<Pass
*, Pass
*>::iterator DMI
= LastUser
.begin(),
633 DME
= LastUser
.end(); DMI
!= DME
; ++DMI
) {
634 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator InvDMI
=
635 InversedLastUser
.find(DMI
->second
);
636 if (InvDMI
!= InversedLastUser
.end()) {
637 SmallPtrSet
<Pass
*, 8> &L
= InvDMI
->second
;
638 L
.insert(DMI
->first
);
640 SmallPtrSet
<Pass
*, 8> L
; L
.insert(DMI
->first
);
641 InversedLastUser
[DMI
->second
] = L
;
647 PMTopLevelManager::~PMTopLevelManager() {
648 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
649 E
= PassManagers
.end(); I
!= E
; ++I
)
652 for (SmallVector
<ImmutablePass
*, 8>::iterator
653 I
= ImmutablePasses
.begin(), E
= ImmutablePasses
.end(); I
!= E
; ++I
)
656 for (DenseMap
<Pass
*, AnalysisUsage
*>::iterator DMI
= AnUsageMap
.begin(),
657 DME
= AnUsageMap
.end(); DMI
!= DME
; ++DMI
)
661 //===----------------------------------------------------------------------===//
662 // PMDataManager implementation
664 /// Augement AvailableAnalysis by adding analysis made available by pass P.
665 void PMDataManager::recordAvailableAnalysis(Pass
*P
) {
666 const PassInfo
*PI
= P
->getPassInfo();
669 AvailableAnalysis
[PI
] = P
;
671 //This pass is the current implementation of all of the interfaces it
672 //implements as well.
673 const std::vector
<const PassInfo
*> &II
= PI
->getInterfacesImplemented();
674 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
)
675 AvailableAnalysis
[II
[i
]] = P
;
678 // Return true if P preserves high level analysis used by other
679 // passes managed by this manager
680 bool PMDataManager::preserveHigherLevelAnalysis(Pass
*P
) {
681 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
682 if (AnUsage
->getPreservesAll())
685 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
686 for (SmallVector
<Pass
*, 8>::iterator I
= HigherLevelAnalysis
.begin(),
687 E
= HigherLevelAnalysis
.end(); I
!= E
; ++I
) {
689 if (!dynamic_cast<ImmutablePass
*>(P1
) &&
690 std::find(PreservedSet
.begin(), PreservedSet
.end(),
691 P1
->getPassInfo()) ==
699 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
700 void PMDataManager::verifyPreservedAnalysis(Pass
*P
) {
701 // Don't do this unless assertions are enabled.
705 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
706 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
708 // Verify preserved analysis
709 for (AnalysisUsage::VectorType::const_iterator I
= PreservedSet
.begin(),
710 E
= PreservedSet
.end(); I
!= E
; ++I
) {
712 if (Pass
*AP
= findAnalysisPass(AID
, true))
713 AP
->verifyAnalysis();
717 /// verifyDomInfo - Verify dominator information if it is available.
718 void PMDataManager::verifyDomInfo(Pass
&P
, Function
&F
) {
719 if (!VerifyDomInfo
|| !P
.getResolver())
722 DominatorTree
*DT
= P
.getAnalysisIfAvailable
<DominatorTree
>();
726 DominatorTree OtherDT
;
727 OtherDT
.getBase().recalculate(F
);
728 if (DT
->compare(OtherDT
)) {
729 errs() << "Dominator Information for " << F
.getName() << "\n";
730 errs() << "Pass '" << P
.getPassName() << "'\n";
731 errs() << "----- Valid -----\n";
733 errs() << "----- Invalid -----\n";
735 llvm_unreachable("Invalid dominator info");
738 DominanceFrontier
*DF
= P
.getAnalysisIfAvailable
<DominanceFrontier
>();
742 DominanceFrontier OtherDF
;
743 std::vector
<BasicBlock
*> DTRoots
= DT
->getRoots();
744 OtherDF
.calculate(*DT
, DT
->getNode(DTRoots
[0]));
745 if (DF
->compare(OtherDF
)) {
746 errs() << "Dominator Information for " << F
.getName() << "\n";
747 errs() << "Pass '" << P
.getPassName() << "'\n";
748 errs() << "----- Valid -----\n";
750 errs() << "----- Invalid -----\n";
752 llvm_unreachable("Invalid dominator info");
756 /// Remove Analysis not preserved by Pass P
757 void PMDataManager::removeNotPreservedAnalysis(Pass
*P
) {
758 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
759 if (AnUsage
->getPreservesAll())
762 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
763 for (std::map
<AnalysisID
, Pass
*>::iterator I
= AvailableAnalysis
.begin(),
764 E
= AvailableAnalysis
.end(); I
!= E
; ) {
765 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
766 if (!dynamic_cast<ImmutablePass
*>(Info
->second
)
767 && std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
768 PreservedSet
.end()) {
769 // Remove this analysis
770 if (PassDebugging
>= Details
) {
771 Pass
*S
= Info
->second
;
772 errs() << " -- '" << P
->getPassName() << "' is not preserving '";
773 errs() << S
->getPassName() << "'\n";
775 AvailableAnalysis
.erase(Info
);
779 // Check inherited analysis also. If P is not preserving analysis
780 // provided by parent manager then remove it here.
781 for (unsigned Index
= 0; Index
< PMT_Last
; ++Index
) {
783 if (!InheritedAnalysis
[Index
])
786 for (std::map
<AnalysisID
, Pass
*>::iterator
787 I
= InheritedAnalysis
[Index
]->begin(),
788 E
= InheritedAnalysis
[Index
]->end(); I
!= E
; ) {
789 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
790 if (!dynamic_cast<ImmutablePass
*>(Info
->second
) &&
791 std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
793 // Remove this analysis
794 InheritedAnalysis
[Index
]->erase(Info
);
799 /// Remove analysis passes that are not used any longer
800 void PMDataManager::removeDeadPasses(Pass
*P
, const StringRef
&Msg
,
801 enum PassDebuggingString DBG_STR
) {
803 SmallVector
<Pass
*, 12> DeadPasses
;
805 // If this is a on the fly manager then it does not have TPM.
809 TPM
->collectLastUses(DeadPasses
, P
);
811 if (PassDebugging
>= Details
&& !DeadPasses
.empty()) {
812 errs() << " -*- '" << P
->getPassName();
813 errs() << "' is the last user of following pass instances.";
814 errs() << " Free these instances\n";
817 for (SmallVector
<Pass
*, 12>::iterator I
= DeadPasses
.begin(),
818 E
= DeadPasses
.end(); I
!= E
; ++I
) {
820 dumpPassInfo(*I
, FREEING_MSG
, DBG_STR
, Msg
);
823 // If the pass crashes releasing memory, remember this.
824 PassManagerPrettyStackEntry
X(*I
);
826 if (TheTimeInfo
) TheTimeInfo
->passStarted(*I
);
827 (*I
)->releaseMemory();
828 if (TheTimeInfo
) TheTimeInfo
->passEnded(*I
);
830 if (const PassInfo
*PI
= (*I
)->getPassInfo()) {
831 std::map
<AnalysisID
, Pass
*>::iterator Pos
=
832 AvailableAnalysis
.find(PI
);
834 // It is possible that pass is already removed from the AvailableAnalysis
835 if (Pos
!= AvailableAnalysis
.end())
836 AvailableAnalysis
.erase(Pos
);
838 // Remove all interfaces this pass implements, for which it is also
839 // listed as the available implementation.
840 const std::vector
<const PassInfo
*> &II
= PI
->getInterfacesImplemented();
841 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
) {
842 Pos
= AvailableAnalysis
.find(II
[i
]);
843 if (Pos
!= AvailableAnalysis
.end() && Pos
->second
== *I
)
844 AvailableAnalysis
.erase(Pos
);
850 /// Add pass P into the PassVector. Update
851 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
852 void PMDataManager::add(Pass
*P
, bool ProcessAnalysis
) {
853 // This manager is going to manage pass P. Set up analysis resolver
855 AnalysisResolver
*AR
= new AnalysisResolver(*this);
858 // If a FunctionPass F is the last user of ModulePass info M
859 // then the F's manager, not F, records itself as a last user of M.
860 SmallVector
<Pass
*, 12> TransferLastUses
;
862 if (!ProcessAnalysis
) {
864 PassVector
.push_back(P
);
868 // At the moment, this pass is the last user of all required passes.
869 SmallVector
<Pass
*, 12> LastUses
;
870 SmallVector
<Pass
*, 8> RequiredPasses
;
871 SmallVector
<AnalysisID
, 8> ReqAnalysisNotAvailable
;
873 unsigned PDepth
= this->getDepth();
875 collectRequiredAnalysis(RequiredPasses
,
876 ReqAnalysisNotAvailable
, P
);
877 for (SmallVector
<Pass
*, 8>::iterator I
= RequiredPasses
.begin(),
878 E
= RequiredPasses
.end(); I
!= E
; ++I
) {
879 Pass
*PRequired
= *I
;
882 assert(PRequired
->getResolver() && "Analysis Resolver is not set");
883 PMDataManager
&DM
= PRequired
->getResolver()->getPMDataManager();
884 RDepth
= DM
.getDepth();
886 if (PDepth
== RDepth
)
887 LastUses
.push_back(PRequired
);
888 else if (PDepth
> RDepth
) {
889 // Let the parent claim responsibility of last use
890 TransferLastUses
.push_back(PRequired
);
891 // Keep track of higher level analysis used by this manager.
892 HigherLevelAnalysis
.push_back(PRequired
);
894 llvm_unreachable("Unable to accomodate Required Pass");
897 // Set P as P's last user until someone starts using P.
898 // However, if P is a Pass Manager then it does not need
899 // to record its last user.
900 if (!dynamic_cast<PMDataManager
*>(P
))
901 LastUses
.push_back(P
);
902 TPM
->setLastUser(LastUses
, P
);
904 if (!TransferLastUses
.empty()) {
905 Pass
*My_PM
= dynamic_cast<Pass
*>(this);
906 TPM
->setLastUser(TransferLastUses
, My_PM
);
907 TransferLastUses
.clear();
910 // Now, take care of required analysises that are not available.
911 for (SmallVector
<AnalysisID
, 8>::iterator
912 I
= ReqAnalysisNotAvailable
.begin(),
913 E
= ReqAnalysisNotAvailable
.end() ;I
!= E
; ++I
) {
914 Pass
*AnalysisPass
= (*I
)->createPass();
915 this->addLowerLevelRequiredPass(P
, AnalysisPass
);
918 // Take a note of analysis required and made available by this pass.
919 // Remove the analysis not preserved by this pass
920 removeNotPreservedAnalysis(P
);
921 recordAvailableAnalysis(P
);
924 PassVector
.push_back(P
);
928 /// Populate RP with analysis pass that are required by
929 /// pass P and are available. Populate RP_NotAvail with analysis
930 /// pass that are required by pass P but are not available.
931 void PMDataManager::collectRequiredAnalysis(SmallVector
<Pass
*, 8>&RP
,
932 SmallVector
<AnalysisID
, 8> &RP_NotAvail
,
934 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
935 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
936 for (AnalysisUsage::VectorType::const_iterator
937 I
= RequiredSet
.begin(), E
= RequiredSet
.end(); I
!= E
; ++I
) {
938 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
939 RP
.push_back(AnalysisPass
);
941 RP_NotAvail
.push_back(*I
);
944 const AnalysisUsage::VectorType
&IDs
= AnUsage
->getRequiredTransitiveSet();
945 for (AnalysisUsage::VectorType::const_iterator I
= IDs
.begin(),
946 E
= IDs
.end(); I
!= E
; ++I
) {
947 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
948 RP
.push_back(AnalysisPass
);
950 RP_NotAvail
.push_back(*I
);
954 // All Required analyses should be available to the pass as it runs! Here
955 // we fill in the AnalysisImpls member of the pass so that it can
956 // successfully use the getAnalysis() method to retrieve the
957 // implementations it needs.
959 void PMDataManager::initializeAnalysisImpl(Pass
*P
) {
960 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
962 for (AnalysisUsage::VectorType::const_iterator
963 I
= AnUsage
->getRequiredSet().begin(),
964 E
= AnUsage
->getRequiredSet().end(); I
!= E
; ++I
) {
965 Pass
*Impl
= findAnalysisPass(*I
, true);
967 // This may be analysis pass that is initialized on the fly.
968 // If that is not the case then it will raise an assert when it is used.
970 AnalysisResolver
*AR
= P
->getResolver();
971 assert(AR
&& "Analysis Resolver is not set");
972 AR
->addAnalysisImplsPair(*I
, Impl
);
976 /// Find the pass that implements Analysis AID. If desired pass is not found
977 /// then return NULL.
978 Pass
*PMDataManager::findAnalysisPass(AnalysisID AID
, bool SearchParent
) {
980 // Check if AvailableAnalysis map has one entry.
981 std::map
<AnalysisID
, Pass
*>::const_iterator I
= AvailableAnalysis
.find(AID
);
983 if (I
!= AvailableAnalysis
.end())
986 // Search Parents through TopLevelManager
988 return TPM
->findAnalysisPass(AID
);
993 // Print list of passes that are last used by P.
994 void PMDataManager::dumpLastUses(Pass
*P
, unsigned Offset
) const{
996 SmallVector
<Pass
*, 12> LUses
;
998 // If this is a on the fly manager then it does not have TPM.
1002 TPM
->collectLastUses(LUses
, P
);
1004 for (SmallVector
<Pass
*, 12>::iterator I
= LUses
.begin(),
1005 E
= LUses
.end(); I
!= E
; ++I
) {
1006 llvm::errs() << "--" << std::string(Offset
*2, ' ');
1007 (*I
)->dumpPassStructure(0);
1011 void PMDataManager::dumpPassArguments() const {
1012 for (SmallVector
<Pass
*, 8>::const_iterator I
= PassVector
.begin(),
1013 E
= PassVector
.end(); I
!= E
; ++I
) {
1014 if (PMDataManager
*PMD
= dynamic_cast<PMDataManager
*>(*I
))
1015 PMD
->dumpPassArguments();
1017 if (const PassInfo
*PI
= (*I
)->getPassInfo())
1018 if (!PI
->isAnalysisGroup())
1019 errs() << " -" << PI
->getPassArgument();
1023 void PMDataManager::dumpPassInfo(Pass
*P
, enum PassDebuggingString S1
,
1024 enum PassDebuggingString S2
,
1025 const StringRef
&Msg
) {
1026 if (PassDebugging
< Executions
)
1028 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
1031 errs() << "Executing Pass '" << P
->getPassName();
1033 case MODIFICATION_MSG
:
1034 errs() << "Made Modification '" << P
->getPassName();
1037 errs() << " Freeing Pass '" << P
->getPassName();
1043 case ON_BASICBLOCK_MSG
:
1044 errs() << "' on BasicBlock '" << Msg
<< "'...\n";
1046 case ON_FUNCTION_MSG
:
1047 errs() << "' on Function '" << Msg
<< "'...\n";
1050 errs() << "' on Module '" << Msg
<< "'...\n";
1053 errs() << "' on Loop '" << Msg
<< "'...\n";
1056 errs() << "' on Call Graph Nodes '" << Msg
<< "'...\n";
1063 void PMDataManager::dumpRequiredSet(const Pass
*P
) const {
1064 if (PassDebugging
< Details
)
1067 AnalysisUsage analysisUsage
;
1068 P
->getAnalysisUsage(analysisUsage
);
1069 dumpAnalysisUsage("Required", P
, analysisUsage
.getRequiredSet());
1072 void PMDataManager::dumpPreservedSet(const Pass
*P
) const {
1073 if (PassDebugging
< Details
)
1076 AnalysisUsage analysisUsage
;
1077 P
->getAnalysisUsage(analysisUsage
);
1078 dumpAnalysisUsage("Preserved", P
, analysisUsage
.getPreservedSet());
1081 void PMDataManager::dumpAnalysisUsage(const StringRef
&Msg
, const Pass
*P
,
1082 const AnalysisUsage::VectorType
&Set
) const {
1083 assert(PassDebugging
>= Details
);
1086 errs() << (void*)P
<< std::string(getDepth()*2+3, ' ') << Msg
<< " Analyses:";
1087 for (unsigned i
= 0; i
!= Set
.size(); ++i
) {
1088 if (i
) errs() << ',';
1089 errs() << ' ' << Set
[i
]->getPassName();
1094 /// Add RequiredPass into list of lower level passes required by pass P.
1095 /// RequiredPass is run on the fly by Pass Manager when P requests it
1096 /// through getAnalysis interface.
1097 /// This should be handled by specific pass manager.
1098 void PMDataManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1100 TPM
->dumpArguments();
1104 // Module Level pass may required Function Level analysis info
1105 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1106 // to provide this on demand. In that case, in Pass manager terminology,
1107 // module level pass is requiring lower level analysis info managed by
1108 // lower level pass manager.
1110 // When Pass manager is not able to order required analysis info, Pass manager
1111 // checks whether any lower level manager will be able to provide this
1112 // analysis info on demand or not.
1114 errs() << "Unable to schedule '" << RequiredPass
->getPassName();
1115 errs() << "' required by '" << P
->getPassName() << "'\n";
1117 llvm_unreachable("Unable to schedule pass");
1121 PMDataManager::~PMDataManager() {
1122 for (SmallVector
<Pass
*, 8>::iterator I
= PassVector
.begin(),
1123 E
= PassVector
.end(); I
!= E
; ++I
)
1127 //===----------------------------------------------------------------------===//
1128 // NOTE: Is this the right place to define this method ?
1129 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1130 Pass
*AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID
, bool dir
) const {
1131 return PM
.findAnalysisPass(ID
, dir
);
1134 Pass
*AnalysisResolver::findImplPass(Pass
*P
, const PassInfo
*AnalysisPI
,
1136 return PM
.getOnTheFlyPass(P
, AnalysisPI
, F
);
1139 //===----------------------------------------------------------------------===//
1140 // BBPassManager implementation
1142 /// Execute all of the passes scheduled for execution by invoking
1143 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1144 /// the function, and if so, return true.
1145 bool BBPassManager::runOnFunction(Function
&F
) {
1146 if (F
.isDeclaration())
1149 bool Changed
= doInitialization(F
);
1151 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ++I
)
1152 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1153 BasicBlockPass
*BP
= getContainedPass(Index
);
1155 dumpPassInfo(BP
, EXECUTION_MSG
, ON_BASICBLOCK_MSG
, I
->getName());
1156 dumpRequiredSet(BP
);
1158 initializeAnalysisImpl(BP
);
1161 // If the pass crashes, remember this.
1162 PassManagerPrettyStackEntry
X(BP
, *I
);
1164 if (TheTimeInfo
) TheTimeInfo
->passStarted(BP
);
1165 Changed
|= BP
->runOnBasicBlock(*I
);
1166 if (TheTimeInfo
) TheTimeInfo
->passEnded(BP
);
1170 dumpPassInfo(BP
, MODIFICATION_MSG
, ON_BASICBLOCK_MSG
,
1172 dumpPreservedSet(BP
);
1174 verifyPreservedAnalysis(BP
);
1175 removeNotPreservedAnalysis(BP
);
1176 recordAvailableAnalysis(BP
);
1177 removeDeadPasses(BP
, I
->getName(), ON_BASICBLOCK_MSG
);
1180 return Changed
|= doFinalization(F
);
1183 // Implement doInitialization and doFinalization
1184 bool BBPassManager::doInitialization(Module
&M
) {
1185 bool Changed
= false;
1187 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1188 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1193 bool BBPassManager::doFinalization(Module
&M
) {
1194 bool Changed
= false;
1196 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1197 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1202 bool BBPassManager::doInitialization(Function
&F
) {
1203 bool Changed
= false;
1205 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1206 BasicBlockPass
*BP
= getContainedPass(Index
);
1207 Changed
|= BP
->doInitialization(F
);
1213 bool BBPassManager::doFinalization(Function
&F
) {
1214 bool Changed
= false;
1216 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1217 BasicBlockPass
*BP
= getContainedPass(Index
);
1218 Changed
|= BP
->doFinalization(F
);
1225 //===----------------------------------------------------------------------===//
1226 // FunctionPassManager implementation
1228 /// Create new Function pass manager
1229 FunctionPassManager::FunctionPassManager(ModuleProvider
*P
) {
1230 FPM
= new FunctionPassManagerImpl(0);
1231 // FPM is the top level manager.
1232 FPM
->setTopLevelManager(FPM
);
1234 AnalysisResolver
*AR
= new AnalysisResolver(*FPM
);
1235 FPM
->setResolver(AR
);
1240 FunctionPassManager::~FunctionPassManager() {
1244 /// add - Add a pass to the queue of passes to run. This passes
1245 /// ownership of the Pass to the PassManager. When the
1246 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1247 /// there is no need to delete the pass. (TODO delete passes.)
1248 /// This implies that all passes MUST be allocated with 'new'.
1249 void FunctionPassManager::add(Pass
*P
) {
1253 /// run - Execute all of the passes scheduled for execution. Keep
1254 /// track of whether any of the passes modifies the function, and if
1255 /// so, return true.
1257 bool FunctionPassManager::run(Function
&F
) {
1259 if (MP
->materializeFunction(&F
, &errstr
)) {
1260 llvm_report_error("Error reading bitcode file: " + errstr
);
1266 /// doInitialization - Run all of the initializers for the function passes.
1268 bool FunctionPassManager::doInitialization() {
1269 return FPM
->doInitialization(*MP
->getModule());
1272 /// doFinalization - Run all of the finalizers for the function passes.
1274 bool FunctionPassManager::doFinalization() {
1275 return FPM
->doFinalization(*MP
->getModule());
1278 //===----------------------------------------------------------------------===//
1279 // FunctionPassManagerImpl implementation
1281 bool FunctionPassManagerImpl::doInitialization(Module
&M
) {
1282 bool Changed
= false;
1284 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1285 Changed
|= getContainedManager(Index
)->doInitialization(M
);
1290 bool FunctionPassManagerImpl::doFinalization(Module
&M
) {
1291 bool Changed
= false;
1293 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1294 Changed
|= getContainedManager(Index
)->doFinalization(M
);
1299 /// cleanup - After running all passes, clean up pass manager cache.
1300 void FPPassManager::cleanup() {
1301 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1302 FunctionPass
*FP
= getContainedPass(Index
);
1303 AnalysisResolver
*AR
= FP
->getResolver();
1304 assert(AR
&& "Analysis Resolver is not set");
1305 AR
->clearAnalysisImpls();
1309 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1312 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
1313 FPPassManager
*FPPM
= getContainedManager(Index
);
1314 for (unsigned Index
= 0; Index
< FPPM
->getNumContainedPasses(); ++Index
) {
1315 FPPM
->getContainedPass(Index
)->releaseMemory();
1321 // Execute all the passes managed by this top level manager.
1322 // Return true if any function is modified by a pass.
1323 bool FunctionPassManagerImpl::run(Function
&F
) {
1324 bool Changed
= false;
1325 TimingInfo::createTheTimeInfo();
1330 initializeAllAnalysisInfo();
1331 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1332 Changed
|= getContainedManager(Index
)->runOnFunction(F
);
1334 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1335 getContainedManager(Index
)->cleanup();
1341 //===----------------------------------------------------------------------===//
1342 // FPPassManager implementation
1344 char FPPassManager::ID
= 0;
1345 /// Print passes managed by this manager
1346 void FPPassManager::dumpPassStructure(unsigned Offset
) {
1347 llvm::errs() << std::string(Offset
*2, ' ') << "FunctionPass Manager\n";
1348 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1349 FunctionPass
*FP
= getContainedPass(Index
);
1350 FP
->dumpPassStructure(Offset
+ 1);
1351 dumpLastUses(FP
, Offset
+1);
1356 /// Execute all of the passes scheduled for execution by invoking
1357 /// runOnFunction method. Keep track of whether any of the passes modifies
1358 /// the function, and if so, return true.
1359 bool FPPassManager::runOnFunction(Function
&F
) {
1360 if (F
.isDeclaration())
1363 bool Changed
= false;
1365 // Collect inherited analysis from Module level pass manager.
1366 populateInheritedAnalysis(TPM
->activeStack
);
1368 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1369 FunctionPass
*FP
= getContainedPass(Index
);
1371 dumpPassInfo(FP
, EXECUTION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1372 dumpRequiredSet(FP
);
1374 initializeAnalysisImpl(FP
);
1377 PassManagerPrettyStackEntry
X(FP
, F
);
1379 if (TheTimeInfo
) TheTimeInfo
->passStarted(FP
);
1380 Changed
|= FP
->runOnFunction(F
);
1381 if (TheTimeInfo
) TheTimeInfo
->passEnded(FP
);
1385 dumpPassInfo(FP
, MODIFICATION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1386 dumpPreservedSet(FP
);
1388 verifyPreservedAnalysis(FP
);
1389 removeNotPreservedAnalysis(FP
);
1390 recordAvailableAnalysis(FP
);
1391 removeDeadPasses(FP
, F
.getName(), ON_FUNCTION_MSG
);
1393 // If dominator information is available then verify the info if requested.
1394 verifyDomInfo(*FP
, F
);
1399 bool FPPassManager::runOnModule(Module
&M
) {
1400 bool Changed
= doInitialization(M
);
1402 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
1405 return Changed
|= doFinalization(M
);
1408 bool FPPassManager::doInitialization(Module
&M
) {
1409 bool Changed
= false;
1411 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1412 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1417 bool FPPassManager::doFinalization(Module
&M
) {
1418 bool Changed
= false;
1420 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1421 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1426 //===----------------------------------------------------------------------===//
1427 // MPPassManager implementation
1429 /// Execute all of the passes scheduled for execution by invoking
1430 /// runOnModule method. Keep track of whether any of the passes modifies
1431 /// the module, and if so, return true.
1433 MPPassManager::runOnModule(Module
&M
) {
1434 bool Changed
= false;
1436 // Initialize on-the-fly passes
1437 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
1438 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
1440 FunctionPassManagerImpl
*FPP
= I
->second
;
1441 Changed
|= FPP
->doInitialization(M
);
1444 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1445 ModulePass
*MP
= getContainedPass(Index
);
1447 dumpPassInfo(MP
, EXECUTION_MSG
, ON_MODULE_MSG
,
1448 M
.getModuleIdentifier().c_str());
1449 dumpRequiredSet(MP
);
1451 initializeAnalysisImpl(MP
);
1454 PassManagerPrettyStackEntry
X(MP
, M
);
1455 if (TheTimeInfo
) TheTimeInfo
->passStarted(MP
);
1456 Changed
|= MP
->runOnModule(M
);
1457 if (TheTimeInfo
) TheTimeInfo
->passEnded(MP
);
1461 dumpPassInfo(MP
, MODIFICATION_MSG
, ON_MODULE_MSG
,
1462 M
.getModuleIdentifier().c_str());
1463 dumpPreservedSet(MP
);
1465 verifyPreservedAnalysis(MP
);
1466 removeNotPreservedAnalysis(MP
);
1467 recordAvailableAnalysis(MP
);
1468 removeDeadPasses(MP
, M
.getModuleIdentifier().c_str(), ON_MODULE_MSG
);
1471 // Finalize on-the-fly passes
1472 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
1473 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
1475 FunctionPassManagerImpl
*FPP
= I
->second
;
1476 // We don't know when is the last time an on-the-fly pass is run,
1477 // so we need to releaseMemory / finalize here
1478 FPP
->releaseMemoryOnTheFly();
1479 Changed
|= FPP
->doFinalization(M
);
1484 /// Add RequiredPass into list of lower level passes required by pass P.
1485 /// RequiredPass is run on the fly by Pass Manager when P requests it
1486 /// through getAnalysis interface.
1487 void MPPassManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1488 assert(P
->getPotentialPassManagerType() == PMT_ModulePassManager
&&
1489 "Unable to handle Pass that requires lower level Analysis pass");
1490 assert((P
->getPotentialPassManagerType() <
1491 RequiredPass
->getPotentialPassManagerType()) &&
1492 "Unable to handle Pass that requires lower level Analysis pass");
1494 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[P
];
1496 FPP
= new FunctionPassManagerImpl(0);
1497 // FPP is the top level manager.
1498 FPP
->setTopLevelManager(FPP
);
1500 OnTheFlyManagers
[P
] = FPP
;
1502 FPP
->add(RequiredPass
);
1504 // Register P as the last user of RequiredPass.
1505 SmallVector
<Pass
*, 12> LU
;
1506 LU
.push_back(RequiredPass
);
1507 FPP
->setLastUser(LU
, P
);
1510 /// Return function pass corresponding to PassInfo PI, that is
1511 /// required by module pass MP. Instantiate analysis pass, by using
1512 /// its runOnFunction() for function F.
1513 Pass
* MPPassManager::getOnTheFlyPass(Pass
*MP
, const PassInfo
*PI
, Function
&F
){
1514 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[MP
];
1515 assert(FPP
&& "Unable to find on the fly pass");
1517 FPP
->releaseMemoryOnTheFly();
1519 return (dynamic_cast<PMTopLevelManager
*>(FPP
))->findAnalysisPass(PI
);
1523 //===----------------------------------------------------------------------===//
1524 // PassManagerImpl implementation
1526 /// run - Execute all of the passes scheduled for execution. Keep track of
1527 /// whether any of the passes modifies the module, and if so, return true.
1528 bool PassManagerImpl::run(Module
&M
) {
1529 bool Changed
= false;
1530 TimingInfo::createTheTimeInfo();
1535 initializeAllAnalysisInfo();
1536 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1537 Changed
|= getContainedManager(Index
)->runOnModule(M
);
1541 //===----------------------------------------------------------------------===//
1542 // PassManager implementation
1544 /// Create new pass manager
1545 PassManager::PassManager() {
1546 PM
= new PassManagerImpl(0);
1547 // PM is the top level manager
1548 PM
->setTopLevelManager(PM
);
1551 PassManager::~PassManager() {
1555 /// add - Add a pass to the queue of passes to run. This passes ownership of
1556 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1557 /// will be destroyed as well, so there is no need to delete the pass. This
1558 /// implies that all passes MUST be allocated with 'new'.
1559 void PassManager::add(Pass
*P
) {
1563 /// run - Execute all of the passes scheduled for execution. Keep track of
1564 /// whether any of the passes modifies the module, and if so, return true.
1565 bool PassManager::run(Module
&M
) {
1569 //===----------------------------------------------------------------------===//
1570 // TimingInfo Class - This class is used to calculate information about the
1571 // amount of time each pass takes to execute. This only happens with
1572 // -time-passes is enabled on the command line.
1574 bool llvm::TimePassesIsEnabled
= false;
1575 static cl::opt
<bool,true>
1576 EnableTiming("time-passes", cl::location(TimePassesIsEnabled
),
1577 cl::desc("Time each pass, printing elapsed time for each on exit"));
1579 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1580 // a non null value (if the -time-passes option is enabled) or it leaves it
1581 // null. It may be called multiple times.
1582 void TimingInfo::createTheTimeInfo() {
1583 if (!TimePassesIsEnabled
|| TheTimeInfo
) return;
1585 // Constructed the first time this is called, iff -time-passes is enabled.
1586 // This guarantees that the object will be constructed before static globals,
1587 // thus it will be destroyed before them.
1588 static ManagedStatic
<TimingInfo
> TTI
;
1589 TheTimeInfo
= &*TTI
;
1592 /// If TimingInfo is enabled then start pass timer.
1593 void llvm::StartPassTimer(Pass
*P
) {
1595 TheTimeInfo
->passStarted(P
);
1598 /// If TimingInfo is enabled then stop pass timer.
1599 void llvm::StopPassTimer(Pass
*P
) {
1601 TheTimeInfo
->passEnded(P
);
1604 //===----------------------------------------------------------------------===//
1605 // PMStack implementation
1608 // Pop Pass Manager from the stack and clear its analysis info.
1609 void PMStack::pop() {
1611 PMDataManager
*Top
= this->top();
1612 Top
->initializeAnalysisInfo();
1617 // Push PM on the stack and set its top level manager.
1618 void PMStack::push(PMDataManager
*PM
) {
1619 assert(PM
&& "Unable to push. Pass Manager expected");
1621 if (!this->empty()) {
1622 PMTopLevelManager
*TPM
= this->top()->getTopLevelManager();
1624 assert(TPM
&& "Unable to find top level manager");
1625 TPM
->addIndirectPassManager(PM
);
1626 PM
->setTopLevelManager(TPM
);
1632 // Dump content of the pass manager stack.
1633 void PMStack::dump() {
1634 for (std::deque
<PMDataManager
*>::iterator I
= S
.begin(),
1635 E
= S
.end(); I
!= E
; ++I
)
1636 printf("%s ", dynamic_cast<Pass
*>(*I
)->getPassName());
1642 /// Find appropriate Module Pass Manager in the PM Stack and
1643 /// add self into that manager.
1644 void ModulePass::assignPassManager(PMStack
&PMS
,
1645 PassManagerType PreferredType
) {
1646 // Find Module Pass Manager
1647 while(!PMS
.empty()) {
1648 PassManagerType TopPMType
= PMS
.top()->getPassManagerType();
1649 if (TopPMType
== PreferredType
)
1650 break; // We found desired pass manager
1651 else if (TopPMType
> PMT_ModulePassManager
)
1652 PMS
.pop(); // Pop children pass managers
1656 assert(!PMS
.empty() && "Unable to find appropriate Pass Manager");
1657 PMS
.top()->add(this);
1660 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1661 /// in the PM Stack and add self into that manager.
1662 void FunctionPass::assignPassManager(PMStack
&PMS
,
1663 PassManagerType PreferredType
) {
1665 // Find Module Pass Manager
1666 while(!PMS
.empty()) {
1667 if (PMS
.top()->getPassManagerType() > PMT_FunctionPassManager
)
1672 FPPassManager
*FPP
= dynamic_cast<FPPassManager
*>(PMS
.top());
1674 // Create new Function Pass Manager
1676 assert(!PMS
.empty() && "Unable to create Function Pass Manager");
1677 PMDataManager
*PMD
= PMS
.top();
1679 // [1] Create new Function Pass Manager
1680 FPP
= new FPPassManager(PMD
->getDepth() + 1);
1681 FPP
->populateInheritedAnalysis(PMS
);
1683 // [2] Set up new manager's top level manager
1684 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1685 TPM
->addIndirectPassManager(FPP
);
1687 // [3] Assign manager to manage this new manager. This may create
1688 // and push new managers into PMS
1689 FPP
->assignPassManager(PMS
, PMD
->getPassManagerType());
1691 // [4] Push new manager into PMS
1695 // Assign FPP as the manager of this pass.
1699 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1700 /// in the PM Stack and add self into that manager.
1701 void BasicBlockPass::assignPassManager(PMStack
&PMS
,
1702 PassManagerType PreferredType
) {
1703 BBPassManager
*BBP
= NULL
;
1705 // Basic Pass Manager is a leaf pass manager. It does not handle
1706 // any other pass manager.
1708 BBP
= dynamic_cast<BBPassManager
*>(PMS
.top());
1710 // If leaf manager is not Basic Block Pass manager then create new
1711 // basic Block Pass manager.
1714 assert(!PMS
.empty() && "Unable to create BasicBlock Pass Manager");
1715 PMDataManager
*PMD
= PMS
.top();
1717 // [1] Create new Basic Block Manager
1718 BBP
= new BBPassManager(PMD
->getDepth() + 1);
1720 // [2] Set up new manager's top level manager
1721 // Basic Block Pass Manager does not live by itself
1722 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1723 TPM
->addIndirectPassManager(BBP
);
1725 // [3] Assign manager to manage this new manager. This may create
1726 // and push new managers into PMS
1727 BBP
->assignPassManager(PMS
);
1729 // [4] Push new manager into PMS
1733 // Assign BBP as the manager of this pass.
1737 PassManagerBase::~PassManagerBase() {}
1739 /*===-- C Bindings --------------------------------------------------------===*/
1741 LLVMPassManagerRef
LLVMCreatePassManager() {
1742 return wrap(new PassManager());
1745 LLVMPassManagerRef
LLVMCreateFunctionPassManager(LLVMModuleProviderRef P
) {
1746 return wrap(new FunctionPassManager(unwrap(P
)));
1749 int LLVMRunPassManager(LLVMPassManagerRef PM
, LLVMModuleRef M
) {
1750 return unwrap
<PassManager
>(PM
)->run(*unwrap(M
));
1753 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM
) {
1754 return unwrap
<FunctionPassManager
>(FPM
)->doInitialization();
1757 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM
, LLVMValueRef F
) {
1758 return unwrap
<FunctionPassManager
>(FPM
)->run(*unwrap
<Function
>(F
));
1761 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM
) {
1762 return unwrap
<FunctionPassManager
>(FPM
)->doFinalization();
1765 void LLVMDisposePassManager(LLVMPassManagerRef PM
) {