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/Streams.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/System/Threading.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm-c/Core.h"
33 // See PassManagers.h for Pass Manager infrastructure overview.
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information. Often it is useful to find out what pass is
39 // running when a crash occurs in a utility. When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
44 // Different debug levels that can be enabled...
46 None
, Arguments
, Structure
, Executions
, Details
49 // Always verify dominfo if expensive checking is enabled.
51 bool VerifyDomInfo
= true;
53 bool VerifyDomInfo
= false;
55 static cl::opt
<bool,true>
56 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo
),
57 cl::desc("Verify dominator info (time consuming)"));
59 static cl::opt
<enum PassDebugLevel
>
60 PassDebugging("debug-pass", cl::Hidden
,
61 cl::desc("Print PassManager debugging information"),
63 clEnumVal(None
, "disable debug output"),
64 clEnumVal(Arguments
, "print pass arguments to pass to 'opt'"),
65 clEnumVal(Structure
, "print pass structure before run()"),
66 clEnumVal(Executions
, "print pass name before it is executed"),
67 clEnumVal(Details
, "print pass details when it is executed"),
69 } // End of llvm namespace
71 void PassManagerPrettyStackEntry::print(raw_ostream
&OS
) const {
73 OS
<< "Releasing pass '";
75 OS
<< "Running pass '";
77 OS
<< P
->getPassName() << "'";
80 OS
<< " on module '" << M
->getModuleIdentifier() << "'.\n";
91 else if (isa
<BasicBlock
>(V
))
97 WriteAsOperand(OS
, V
, /*PrintTy=*/false, M
);
104 //===----------------------------------------------------------------------===//
107 /// BBPassManager manages BasicBlockPass. It batches all the
108 /// pass together and sequence them to process one basic block before
109 /// processing next basic block.
110 class VISIBILITY_HIDDEN BBPassManager
: public PMDataManager
,
111 public FunctionPass
{
115 explicit BBPassManager(int Depth
)
116 : PMDataManager(Depth
), FunctionPass(&ID
) {}
118 /// Execute all of the passes scheduled for execution. Keep track of
119 /// whether any of the passes modifies the function, and if so, return true.
120 bool runOnFunction(Function
&F
);
122 /// Pass Manager itself does not invalidate any analysis info.
123 void getAnalysisUsage(AnalysisUsage
&Info
) const {
124 Info
.setPreservesAll();
127 bool doInitialization(Module
&M
);
128 bool doInitialization(Function
&F
);
129 bool doFinalization(Module
&M
);
130 bool doFinalization(Function
&F
);
132 virtual const char *getPassName() const {
133 return "BasicBlock Pass Manager";
136 // Print passes managed by this manager
137 void dumpPassStructure(unsigned Offset
) {
138 llvm::errs() << std::string(Offset
*2, ' ') << "BasicBlockPass Manager\n";
139 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
140 BasicBlockPass
*BP
= getContainedPass(Index
);
141 BP
->dumpPassStructure(Offset
+ 1);
142 dumpLastUses(BP
, Offset
+1);
146 BasicBlockPass
*getContainedPass(unsigned N
) {
147 assert(N
< PassVector
.size() && "Pass number out of range!");
148 BasicBlockPass
*BP
= static_cast<BasicBlockPass
*>(PassVector
[N
]);
152 virtual PassManagerType
getPassManagerType() const {
153 return PMT_BasicBlockPassManager
;
157 char BBPassManager::ID
= 0;
162 //===----------------------------------------------------------------------===//
163 // FunctionPassManagerImpl
165 /// FunctionPassManagerImpl manages FPPassManagers
166 class FunctionPassManagerImpl
: public Pass
,
167 public PMDataManager
,
168 public PMTopLevelManager
{
173 explicit FunctionPassManagerImpl(int Depth
) :
174 Pass(&ID
), PMDataManager(Depth
),
175 PMTopLevelManager(TLM_Function
), wasRun(false) { }
177 /// add - Add a pass to the queue of passes to run. This passes ownership of
178 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
179 /// will be destroyed as well, so there is no need to delete the pass. This
180 /// implies that all passes MUST be allocated with 'new'.
185 // Prepare for running an on the fly pass, freeing memory if needed
186 // from a previous run.
187 void releaseMemoryOnTheFly();
189 /// run - Execute all of the passes scheduled for execution. Keep track of
190 /// whether any of the passes modifies the module, and if so, return true.
191 bool run(Function
&F
);
193 /// doInitialization - Run all of the initializers for the function passes.
195 bool doInitialization(Module
&M
);
197 /// doFinalization - Run all of the finalizers for the function passes.
199 bool doFinalization(Module
&M
);
201 /// Pass Manager itself does not invalidate any analysis info.
202 void getAnalysisUsage(AnalysisUsage
&Info
) const {
203 Info
.setPreservesAll();
206 inline void addTopLevelPass(Pass
*P
) {
208 if (ImmutablePass
*IP
= dynamic_cast<ImmutablePass
*> (P
)) {
210 // P is a immutable pass and it will be managed by this
211 // top level manager. Set up analysis resolver to connect them.
212 AnalysisResolver
*AR
= new AnalysisResolver(*this);
214 initializeAnalysisImpl(P
);
215 addImmutablePass(IP
);
216 recordAvailableAnalysis(IP
);
218 P
->assignPassManager(activeStack
);
223 FPPassManager
*getContainedManager(unsigned N
) {
224 assert(N
< PassManagers
.size() && "Pass number out of range!");
225 FPPassManager
*FP
= static_cast<FPPassManager
*>(PassManagers
[N
]);
230 char FunctionPassManagerImpl::ID
= 0;
231 //===----------------------------------------------------------------------===//
234 /// MPPassManager manages ModulePasses and function pass managers.
235 /// It batches all Module passes and function pass managers together and
236 /// sequences them to process one module.
237 class MPPassManager
: public Pass
, public PMDataManager
{
240 explicit MPPassManager(int Depth
) :
241 Pass(&ID
), PMDataManager(Depth
) { }
243 // Delete on the fly managers.
244 virtual ~MPPassManager() {
245 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
246 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
248 FunctionPassManagerImpl
*FPP
= I
->second
;
253 /// run - Execute all of the passes scheduled for execution. Keep track of
254 /// whether any of the passes modifies the module, and if so, return true.
255 bool runOnModule(Module
&M
);
257 /// Pass Manager itself does not invalidate any analysis info.
258 void getAnalysisUsage(AnalysisUsage
&Info
) const {
259 Info
.setPreservesAll();
262 /// Add RequiredPass into list of lower level passes required by pass P.
263 /// RequiredPass is run on the fly by Pass Manager when P requests it
264 /// through getAnalysis interface.
265 virtual void addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
);
267 /// Return function pass corresponding to PassInfo PI, that is
268 /// required by module pass MP. Instantiate analysis pass, by using
269 /// its runOnFunction() for function F.
270 virtual Pass
* getOnTheFlyPass(Pass
*MP
, const PassInfo
*PI
, Function
&F
);
272 virtual const char *getPassName() const {
273 return "Module Pass Manager";
276 // Print passes managed by this manager
277 void dumpPassStructure(unsigned Offset
) {
278 llvm::errs() << std::string(Offset
*2, ' ') << "ModulePass Manager\n";
279 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
280 ModulePass
*MP
= getContainedPass(Index
);
281 MP
->dumpPassStructure(Offset
+ 1);
282 std::map
<Pass
*, FunctionPassManagerImpl
*>::const_iterator I
=
283 OnTheFlyManagers
.find(MP
);
284 if (I
!= OnTheFlyManagers
.end())
285 I
->second
->dumpPassStructure(Offset
+ 2);
286 dumpLastUses(MP
, Offset
+1);
290 ModulePass
*getContainedPass(unsigned N
) {
291 assert(N
< PassVector
.size() && "Pass number out of range!");
292 return static_cast<ModulePass
*>(PassVector
[N
]);
295 virtual PassManagerType
getPassManagerType() const {
296 return PMT_ModulePassManager
;
300 /// Collection of on the fly FPPassManagers. These managers manage
301 /// function passes that are required by module passes.
302 std::map
<Pass
*, FunctionPassManagerImpl
*> OnTheFlyManagers
;
305 char MPPassManager::ID
= 0;
306 //===----------------------------------------------------------------------===//
310 /// PassManagerImpl manages MPPassManagers
311 class PassManagerImpl
: public Pass
,
312 public PMDataManager
,
313 public PMTopLevelManager
{
317 explicit PassManagerImpl(int Depth
) :
318 Pass(&ID
), PMDataManager(Depth
), PMTopLevelManager(TLM_Pass
) { }
320 /// add - Add a pass to the queue of passes to run. This passes ownership of
321 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
322 /// will be destroyed as well, so there is no need to delete the pass. This
323 /// implies that all passes MUST be allocated with 'new'.
328 /// run - Execute all of the passes scheduled for execution. Keep track of
329 /// whether any of the passes modifies the module, and if so, return true.
332 /// Pass Manager itself does not invalidate any analysis info.
333 void getAnalysisUsage(AnalysisUsage
&Info
) const {
334 Info
.setPreservesAll();
337 inline void addTopLevelPass(Pass
*P
) {
338 if (ImmutablePass
*IP
= dynamic_cast<ImmutablePass
*> (P
)) {
340 // P is a immutable pass and it will be managed by this
341 // top level manager. Set up analysis resolver to connect them.
342 AnalysisResolver
*AR
= new AnalysisResolver(*this);
344 initializeAnalysisImpl(P
);
345 addImmutablePass(IP
);
346 recordAvailableAnalysis(IP
);
348 P
->assignPassManager(activeStack
);
352 MPPassManager
*getContainedManager(unsigned N
) {
353 assert(N
< PassManagers
.size() && "Pass number out of range!");
354 MPPassManager
*MP
= static_cast<MPPassManager
*>(PassManagers
[N
]);
359 char PassManagerImpl::ID
= 0;
360 } // End of llvm namespace
364 //===----------------------------------------------------------------------===//
365 /// TimingInfo Class - This class is used to calculate information about the
366 /// amount of time each pass takes to execute. This only happens when
367 /// -time-passes is enabled on the command line.
370 static ManagedStatic
<sys::SmartMutex
<true> > TimingInfoMutex
;
372 class VISIBILITY_HIDDEN TimingInfo
{
373 std::map
<Pass
*, Timer
> TimingData
;
377 // Use 'create' member to get this.
378 TimingInfo() : TG("... Pass execution timing report ...") {}
380 // TimingDtor - Print out information about timing information
382 // Delete all of the timers...
384 // TimerGroup is deleted next, printing the report.
387 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
388 // to a non null value (if the -time-passes option is enabled) or it leaves it
389 // null. It may be called multiple times.
390 static void createTheTimeInfo();
392 void passStarted(Pass
*P
) {
393 if (dynamic_cast<PMDataManager
*>(P
))
396 sys::SmartScopedLock
<true> Lock(*TimingInfoMutex
);
397 std::map
<Pass
*, Timer
>::iterator I
= TimingData
.find(P
);
398 if (I
== TimingData
.end())
399 I
=TimingData
.insert(std::make_pair(P
, Timer(P
->getPassName(), TG
))).first
;
400 I
->second
.startTimer();
403 void passEnded(Pass
*P
) {
404 if (dynamic_cast<PMDataManager
*>(P
))
407 sys::SmartScopedLock
<true> Lock(*TimingInfoMutex
);
408 std::map
<Pass
*, Timer
>::iterator I
= TimingData
.find(P
);
409 assert(I
!= TimingData
.end() && "passStarted/passEnded not nested right!");
410 I
->second
.stopTimer();
414 } // End of anon namespace
416 static TimingInfo
*TheTimeInfo
;
418 //===----------------------------------------------------------------------===//
419 // PMTopLevelManager implementation
421 /// Initialize top level manager. Create first pass manager.
422 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t
) {
424 MPPassManager
*MPP
= new MPPassManager(1);
425 MPP
->setTopLevelManager(this);
427 activeStack
.push(MPP
);
428 } else if (t
== TLM_Function
) {
429 FPPassManager
*FPP
= new FPPassManager(1);
430 FPP
->setTopLevelManager(this);
432 activeStack
.push(FPP
);
436 /// Set pass P as the last user of the given analysis passes.
437 void PMTopLevelManager::setLastUser(SmallVector
<Pass
*, 12> &AnalysisPasses
,
439 for (SmallVector
<Pass
*, 12>::iterator I
= AnalysisPasses
.begin(),
440 E
= AnalysisPasses
.end(); I
!= E
; ++I
) {
447 // If AP is the last user of other passes then make P last user of
449 for (DenseMap
<Pass
*, Pass
*>::iterator LUI
= LastUser
.begin(),
450 LUE
= LastUser
.end(); LUI
!= LUE
; ++LUI
) {
451 if (LUI
->second
== AP
)
452 // DenseMap iterator is not invalidated here because
453 // this is just updating exisitng entry.
454 LastUser
[LUI
->first
] = P
;
459 /// Collect passes whose last user is P
460 void PMTopLevelManager::collectLastUses(SmallVector
<Pass
*, 12> &LastUses
,
462 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator DMI
=
463 InversedLastUser
.find(P
);
464 if (DMI
== InversedLastUser
.end())
467 SmallPtrSet
<Pass
*, 8> &LU
= DMI
->second
;
468 for (SmallPtrSet
<Pass
*, 8>::iterator I
= LU
.begin(),
469 E
= LU
.end(); I
!= E
; ++I
) {
470 LastUses
.push_back(*I
);
475 AnalysisUsage
*PMTopLevelManager::findAnalysisUsage(Pass
*P
) {
476 AnalysisUsage
*AnUsage
= NULL
;
477 DenseMap
<Pass
*, AnalysisUsage
*>::iterator DMI
= AnUsageMap
.find(P
);
478 if (DMI
!= AnUsageMap
.end())
479 AnUsage
= DMI
->second
;
481 AnUsage
= new AnalysisUsage();
482 P
->getAnalysisUsage(*AnUsage
);
483 AnUsageMap
[P
] = AnUsage
;
488 /// Schedule pass P for execution. Make sure that passes required by
489 /// P are run before P is run. Update analysis info maintained by
490 /// the manager. Remove dead passes. This is a recursive function.
491 void PMTopLevelManager::schedulePass(Pass
*P
) {
493 // TODO : Allocate function manager for this pass, other wise required set
494 // may be inserted into previous function manager
496 // Give pass a chance to prepare the stage.
497 P
->preparePassManager(activeStack
);
499 // If P is an analysis pass and it is available then do not
500 // generate the analysis again. Stale analysis info should not be
501 // available at this point.
502 if (P
->getPassInfo() &&
503 P
->getPassInfo()->isAnalysis() && findAnalysisPass(P
->getPassInfo())) {
508 AnalysisUsage
*AnUsage
= findAnalysisUsage(P
);
510 bool checkAnalysis
= true;
511 while (checkAnalysis
) {
512 checkAnalysis
= false;
514 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
515 for (AnalysisUsage::VectorType::const_iterator I
= RequiredSet
.begin(),
516 E
= RequiredSet
.end(); I
!= E
; ++I
) {
518 Pass
*AnalysisPass
= findAnalysisPass(*I
);
520 AnalysisPass
= (*I
)->createPass();
521 if (P
->getPotentialPassManagerType () ==
522 AnalysisPass
->getPotentialPassManagerType())
523 // Schedule analysis pass that is managed by the same pass manager.
524 schedulePass(AnalysisPass
);
525 else if (P
->getPotentialPassManagerType () >
526 AnalysisPass
->getPotentialPassManagerType()) {
527 // Schedule analysis pass that is managed by a new manager.
528 schedulePass(AnalysisPass
);
529 // Recheck analysis passes to ensure that required analysises that
530 // are already checked are still available.
531 checkAnalysis
= true;
534 // Do not schedule this analysis. Lower level analsyis
535 // passes are run on the fly.
541 // Now all required passes are available.
545 /// Find the pass that implements Analysis AID. Search immutable
546 /// passes and all pass managers. If desired pass is not found
547 /// then return NULL.
548 Pass
*PMTopLevelManager::findAnalysisPass(AnalysisID AID
) {
551 // Check pass managers
552 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
553 E
= PassManagers
.end(); P
== NULL
&& I
!= E
; ++I
) {
554 PMDataManager
*PMD
= *I
;
555 P
= PMD
->findAnalysisPass(AID
, false);
558 // Check other pass managers
559 for (SmallVector
<PMDataManager
*, 8>::iterator
560 I
= IndirectPassManagers
.begin(),
561 E
= IndirectPassManagers
.end(); P
== NULL
&& I
!= E
; ++I
)
562 P
= (*I
)->findAnalysisPass(AID
, false);
564 for (SmallVector
<ImmutablePass
*, 8>::iterator I
= ImmutablePasses
.begin(),
565 E
= ImmutablePasses
.end(); P
== NULL
&& I
!= E
; ++I
) {
566 const PassInfo
*PI
= (*I
)->getPassInfo();
570 // If Pass not found then check the interfaces implemented by Immutable Pass
572 const std::vector
<const PassInfo
*> &ImmPI
=
573 PI
->getInterfacesImplemented();
574 if (std::find(ImmPI
.begin(), ImmPI
.end(), AID
) != ImmPI
.end())
582 // Print passes managed by this top level manager.
583 void PMTopLevelManager::dumpPasses() const {
585 if (PassDebugging
< Structure
)
588 // Print out the immutable passes
589 for (unsigned i
= 0, e
= ImmutablePasses
.size(); i
!= e
; ++i
) {
590 ImmutablePasses
[i
]->dumpPassStructure(0);
593 // Every class that derives from PMDataManager also derives from Pass
594 // (sometimes indirectly), but there's no inheritance relationship
595 // between PMDataManager and Pass, so we have to dynamic_cast to get
596 // from a PMDataManager* to a Pass*.
597 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
598 E
= PassManagers
.end(); I
!= E
; ++I
)
599 dynamic_cast<Pass
*>(*I
)->dumpPassStructure(1);
602 void PMTopLevelManager::dumpArguments() const {
604 if (PassDebugging
< Arguments
)
607 errs() << "Pass Arguments: ";
608 for (SmallVector
<PMDataManager
*, 8>::const_iterator I
= PassManagers
.begin(),
609 E
= PassManagers
.end(); I
!= E
; ++I
)
610 (*I
)->dumpPassArguments();
614 void PMTopLevelManager::initializeAllAnalysisInfo() {
615 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
616 E
= PassManagers
.end(); I
!= E
; ++I
)
617 (*I
)->initializeAnalysisInfo();
619 // Initailize other pass managers
620 for (SmallVector
<PMDataManager
*, 8>::iterator I
= IndirectPassManagers
.begin(),
621 E
= IndirectPassManagers
.end(); I
!= E
; ++I
)
622 (*I
)->initializeAnalysisInfo();
624 for (DenseMap
<Pass
*, Pass
*>::iterator DMI
= LastUser
.begin(),
625 DME
= LastUser
.end(); DMI
!= DME
; ++DMI
) {
626 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator InvDMI
=
627 InversedLastUser
.find(DMI
->second
);
628 if (InvDMI
!= InversedLastUser
.end()) {
629 SmallPtrSet
<Pass
*, 8> &L
= InvDMI
->second
;
630 L
.insert(DMI
->first
);
632 SmallPtrSet
<Pass
*, 8> L
; L
.insert(DMI
->first
);
633 InversedLastUser
[DMI
->second
] = L
;
639 PMTopLevelManager::~PMTopLevelManager() {
640 for (SmallVector
<PMDataManager
*, 8>::iterator I
= PassManagers
.begin(),
641 E
= PassManagers
.end(); I
!= E
; ++I
)
644 for (SmallVector
<ImmutablePass
*, 8>::iterator
645 I
= ImmutablePasses
.begin(), E
= ImmutablePasses
.end(); I
!= E
; ++I
)
648 for (DenseMap
<Pass
*, AnalysisUsage
*>::iterator DMI
= AnUsageMap
.begin(),
649 DME
= AnUsageMap
.end(); DMI
!= DME
; ++DMI
)
653 //===----------------------------------------------------------------------===//
654 // PMDataManager implementation
656 /// Augement AvailableAnalysis by adding analysis made available by pass P.
657 void PMDataManager::recordAvailableAnalysis(Pass
*P
) {
658 const PassInfo
*PI
= P
->getPassInfo();
661 AvailableAnalysis
[PI
] = P
;
663 //This pass is the current implementation of all of the interfaces it
664 //implements as well.
665 const std::vector
<const PassInfo
*> &II
= PI
->getInterfacesImplemented();
666 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
)
667 AvailableAnalysis
[II
[i
]] = P
;
670 // Return true if P preserves high level analysis used by other
671 // passes managed by this manager
672 bool PMDataManager::preserveHigherLevelAnalysis(Pass
*P
) {
673 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
674 if (AnUsage
->getPreservesAll())
677 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
678 for (SmallVector
<Pass
*, 8>::iterator I
= HigherLevelAnalysis
.begin(),
679 E
= HigherLevelAnalysis
.end(); I
!= E
; ++I
) {
681 if (!dynamic_cast<ImmutablePass
*>(P1
) &&
682 std::find(PreservedSet
.begin(), PreservedSet
.end(),
683 P1
->getPassInfo()) ==
691 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
692 void PMDataManager::verifyPreservedAnalysis(Pass
*P
) {
693 // Don't do this unless assertions are enabled.
697 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
698 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
700 // Verify preserved analysis
701 for (AnalysisUsage::VectorType::const_iterator I
= PreservedSet
.begin(),
702 E
= PreservedSet
.end(); I
!= E
; ++I
) {
704 if (Pass
*AP
= findAnalysisPass(AID
, true))
705 AP
->verifyAnalysis();
709 /// verifyDomInfo - Verify dominator information if it is available.
710 void PMDataManager::verifyDomInfo(Pass
&P
, Function
&F
) {
711 if (!VerifyDomInfo
|| !P
.getResolver())
714 DominatorTree
*DT
= P
.getAnalysisIfAvailable
<DominatorTree
>();
718 DominatorTree OtherDT
;
719 OtherDT
.getBase().recalculate(F
);
720 if (DT
->compare(OtherDT
)) {
721 errs() << "Dominator Information for " << F
.getName() << "\n";
722 errs() << "Pass '" << P
.getPassName() << "'\n";
723 errs() << "----- Valid -----\n";
725 errs() << "----- Invalid -----\n";
727 llvm_unreachable("Invalid dominator info");
730 DominanceFrontier
*DF
= P
.getAnalysisIfAvailable
<DominanceFrontier
>();
734 DominanceFrontier OtherDF
;
735 std::vector
<BasicBlock
*> DTRoots
= DT
->getRoots();
736 OtherDF
.calculate(*DT
, DT
->getNode(DTRoots
[0]));
737 if (DF
->compare(OtherDF
)) {
738 errs() << "Dominator Information for " << F
.getName() << "\n";
739 errs() << "Pass '" << P
.getPassName() << "'\n";
740 errs() << "----- Valid -----\n";
742 errs() << "----- Invalid -----\n";
744 llvm_unreachable("Invalid dominator info");
748 /// Remove Analysis not preserved by Pass P
749 void PMDataManager::removeNotPreservedAnalysis(Pass
*P
) {
750 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
751 if (AnUsage
->getPreservesAll())
754 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
755 for (std::map
<AnalysisID
, Pass
*>::iterator I
= AvailableAnalysis
.begin(),
756 E
= AvailableAnalysis
.end(); I
!= E
; ) {
757 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
758 if (!dynamic_cast<ImmutablePass
*>(Info
->second
)
759 && std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
760 PreservedSet
.end()) {
761 // Remove this analysis
762 if (PassDebugging
>= Details
) {
763 Pass
*S
= Info
->second
;
764 errs() << " -- '" << P
->getPassName() << "' is not preserving '";
765 errs() << S
->getPassName() << "'\n";
767 AvailableAnalysis
.erase(Info
);
771 // Check inherited analysis also. If P is not preserving analysis
772 // provided by parent manager then remove it here.
773 for (unsigned Index
= 0; Index
< PMT_Last
; ++Index
) {
775 if (!InheritedAnalysis
[Index
])
778 for (std::map
<AnalysisID
, Pass
*>::iterator
779 I
= InheritedAnalysis
[Index
]->begin(),
780 E
= InheritedAnalysis
[Index
]->end(); I
!= E
; ) {
781 std::map
<AnalysisID
, Pass
*>::iterator Info
= I
++;
782 if (!dynamic_cast<ImmutablePass
*>(Info
->second
) &&
783 std::find(PreservedSet
.begin(), PreservedSet
.end(), Info
->first
) ==
785 // Remove this analysis
786 InheritedAnalysis
[Index
]->erase(Info
);
791 /// Remove analysis passes that are not used any longer
792 void PMDataManager::removeDeadPasses(Pass
*P
, const StringRef
&Msg
,
793 enum PassDebuggingString DBG_STR
) {
795 SmallVector
<Pass
*, 12> DeadPasses
;
797 // If this is a on the fly manager then it does not have TPM.
801 TPM
->collectLastUses(DeadPasses
, P
);
803 if (PassDebugging
>= Details
&& !DeadPasses
.empty()) {
804 errs() << " -*- '" << P
->getPassName();
805 errs() << "' is the last user of following pass instances.";
806 errs() << " Free these instances\n";
809 for (SmallVector
<Pass
*, 12>::iterator I
= DeadPasses
.begin(),
810 E
= DeadPasses
.end(); I
!= E
; ++I
) {
812 dumpPassInfo(*I
, FREEING_MSG
, DBG_STR
, Msg
);
815 // If the pass crashes releasing memory, remember this.
816 PassManagerPrettyStackEntry
X(*I
);
818 if (TheTimeInfo
) TheTimeInfo
->passStarted(*I
);
819 (*I
)->releaseMemory();
820 if (TheTimeInfo
) TheTimeInfo
->passEnded(*I
);
822 if (const PassInfo
*PI
= (*I
)->getPassInfo()) {
823 std::map
<AnalysisID
, Pass
*>::iterator Pos
=
824 AvailableAnalysis
.find(PI
);
826 // It is possible that pass is already removed from the AvailableAnalysis
827 if (Pos
!= AvailableAnalysis
.end())
828 AvailableAnalysis
.erase(Pos
);
830 // Remove all interfaces this pass implements, for which it is also
831 // listed as the available implementation.
832 const std::vector
<const PassInfo
*> &II
= PI
->getInterfacesImplemented();
833 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
) {
834 Pos
= AvailableAnalysis
.find(II
[i
]);
835 if (Pos
!= AvailableAnalysis
.end() && Pos
->second
== *I
)
836 AvailableAnalysis
.erase(Pos
);
842 /// Add pass P into the PassVector. Update
843 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
844 void PMDataManager::add(Pass
*P
, bool ProcessAnalysis
) {
845 // This manager is going to manage pass P. Set up analysis resolver
847 AnalysisResolver
*AR
= new AnalysisResolver(*this);
850 // If a FunctionPass F is the last user of ModulePass info M
851 // then the F's manager, not F, records itself as a last user of M.
852 SmallVector
<Pass
*, 12> TransferLastUses
;
854 if (!ProcessAnalysis
) {
856 PassVector
.push_back(P
);
860 // At the moment, this pass is the last user of all required passes.
861 SmallVector
<Pass
*, 12> LastUses
;
862 SmallVector
<Pass
*, 8> RequiredPasses
;
863 SmallVector
<AnalysisID
, 8> ReqAnalysisNotAvailable
;
865 unsigned PDepth
= this->getDepth();
867 collectRequiredAnalysis(RequiredPasses
,
868 ReqAnalysisNotAvailable
, P
);
869 for (SmallVector
<Pass
*, 8>::iterator I
= RequiredPasses
.begin(),
870 E
= RequiredPasses
.end(); I
!= E
; ++I
) {
871 Pass
*PRequired
= *I
;
874 assert(PRequired
->getResolver() && "Analysis Resolver is not set");
875 PMDataManager
&DM
= PRequired
->getResolver()->getPMDataManager();
876 RDepth
= DM
.getDepth();
878 if (PDepth
== RDepth
)
879 LastUses
.push_back(PRequired
);
880 else if (PDepth
> RDepth
) {
881 // Let the parent claim responsibility of last use
882 TransferLastUses
.push_back(PRequired
);
883 // Keep track of higher level analysis used by this manager.
884 HigherLevelAnalysis
.push_back(PRequired
);
886 llvm_unreachable("Unable to accomodate Required Pass");
889 // Set P as P's last user until someone starts using P.
890 // However, if P is a Pass Manager then it does not need
891 // to record its last user.
892 if (!dynamic_cast<PMDataManager
*>(P
))
893 LastUses
.push_back(P
);
894 TPM
->setLastUser(LastUses
, P
);
896 if (!TransferLastUses
.empty()) {
897 Pass
*My_PM
= dynamic_cast<Pass
*>(this);
898 TPM
->setLastUser(TransferLastUses
, My_PM
);
899 TransferLastUses
.clear();
902 // Now, take care of required analysises that are not available.
903 for (SmallVector
<AnalysisID
, 8>::iterator
904 I
= ReqAnalysisNotAvailable
.begin(),
905 E
= ReqAnalysisNotAvailable
.end() ;I
!= E
; ++I
) {
906 Pass
*AnalysisPass
= (*I
)->createPass();
907 this->addLowerLevelRequiredPass(P
, AnalysisPass
);
910 // Take a note of analysis required and made available by this pass.
911 // Remove the analysis not preserved by this pass
912 removeNotPreservedAnalysis(P
);
913 recordAvailableAnalysis(P
);
916 PassVector
.push_back(P
);
920 /// Populate RP with analysis pass that are required by
921 /// pass P and are available. Populate RP_NotAvail with analysis
922 /// pass that are required by pass P but are not available.
923 void PMDataManager::collectRequiredAnalysis(SmallVector
<Pass
*, 8>&RP
,
924 SmallVector
<AnalysisID
, 8> &RP_NotAvail
,
926 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
927 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
928 for (AnalysisUsage::VectorType::const_iterator
929 I
= RequiredSet
.begin(), E
= RequiredSet
.end(); I
!= E
; ++I
) {
930 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
931 RP
.push_back(AnalysisPass
);
933 RP_NotAvail
.push_back(*I
);
936 const AnalysisUsage::VectorType
&IDs
= AnUsage
->getRequiredTransitiveSet();
937 for (AnalysisUsage::VectorType::const_iterator I
= IDs
.begin(),
938 E
= IDs
.end(); I
!= E
; ++I
) {
939 if (Pass
*AnalysisPass
= findAnalysisPass(*I
, true))
940 RP
.push_back(AnalysisPass
);
942 RP_NotAvail
.push_back(*I
);
946 // All Required analyses should be available to the pass as it runs! Here
947 // we fill in the AnalysisImpls member of the pass so that it can
948 // successfully use the getAnalysis() method to retrieve the
949 // implementations it needs.
951 void PMDataManager::initializeAnalysisImpl(Pass
*P
) {
952 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
954 for (AnalysisUsage::VectorType::const_iterator
955 I
= AnUsage
->getRequiredSet().begin(),
956 E
= AnUsage
->getRequiredSet().end(); I
!= E
; ++I
) {
957 Pass
*Impl
= findAnalysisPass(*I
, true);
959 // This may be analysis pass that is initialized on the fly.
960 // If that is not the case then it will raise an assert when it is used.
962 AnalysisResolver
*AR
= P
->getResolver();
963 assert(AR
&& "Analysis Resolver is not set");
964 AR
->addAnalysisImplsPair(*I
, Impl
);
968 /// Find the pass that implements Analysis AID. If desired pass is not found
969 /// then return NULL.
970 Pass
*PMDataManager::findAnalysisPass(AnalysisID AID
, bool SearchParent
) {
972 // Check if AvailableAnalysis map has one entry.
973 std::map
<AnalysisID
, Pass
*>::const_iterator I
= AvailableAnalysis
.find(AID
);
975 if (I
!= AvailableAnalysis
.end())
978 // Search Parents through TopLevelManager
980 return TPM
->findAnalysisPass(AID
);
985 // Print list of passes that are last used by P.
986 void PMDataManager::dumpLastUses(Pass
*P
, unsigned Offset
) const{
988 SmallVector
<Pass
*, 12> LUses
;
990 // If this is a on the fly manager then it does not have TPM.
994 TPM
->collectLastUses(LUses
, P
);
996 for (SmallVector
<Pass
*, 12>::iterator I
= LUses
.begin(),
997 E
= LUses
.end(); I
!= E
; ++I
) {
998 llvm::errs() << "--" << std::string(Offset
*2, ' ');
999 (*I
)->dumpPassStructure(0);
1003 void PMDataManager::dumpPassArguments() const {
1004 for (SmallVector
<Pass
*, 8>::const_iterator I
= PassVector
.begin(),
1005 E
= PassVector
.end(); I
!= E
; ++I
) {
1006 if (PMDataManager
*PMD
= dynamic_cast<PMDataManager
*>(*I
))
1007 PMD
->dumpPassArguments();
1009 if (const PassInfo
*PI
= (*I
)->getPassInfo())
1010 if (!PI
->isAnalysisGroup())
1011 errs() << " -" << PI
->getPassArgument();
1015 void PMDataManager::dumpPassInfo(Pass
*P
, enum PassDebuggingString S1
,
1016 enum PassDebuggingString S2
,
1017 const StringRef
&Msg
) {
1018 if (PassDebugging
< Executions
)
1020 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
1023 errs() << "Executing Pass '" << P
->getPassName();
1025 case MODIFICATION_MSG
:
1026 errs() << "Made Modification '" << P
->getPassName();
1029 errs() << " Freeing Pass '" << P
->getPassName();
1035 case ON_BASICBLOCK_MSG
:
1036 errs() << "' on BasicBlock '" << Msg
<< "'...\n";
1038 case ON_FUNCTION_MSG
:
1039 errs() << "' on Function '" << Msg
<< "'...\n";
1042 errs() << "' on Module '" << Msg
<< "'...\n";
1045 errs() << "' on Loop " << Msg
<< "'...\n";
1048 errs() << "' on Call Graph " << Msg
<< "'...\n";
1055 void PMDataManager::dumpRequiredSet(const Pass
*P
) const {
1056 if (PassDebugging
< Details
)
1059 AnalysisUsage analysisUsage
;
1060 P
->getAnalysisUsage(analysisUsage
);
1061 dumpAnalysisUsage("Required", P
, analysisUsage
.getRequiredSet());
1064 void PMDataManager::dumpPreservedSet(const Pass
*P
) const {
1065 if (PassDebugging
< Details
)
1068 AnalysisUsage analysisUsage
;
1069 P
->getAnalysisUsage(analysisUsage
);
1070 dumpAnalysisUsage("Preserved", P
, analysisUsage
.getPreservedSet());
1073 void PMDataManager::dumpAnalysisUsage(const StringRef
&Msg
, const Pass
*P
,
1074 const AnalysisUsage::VectorType
&Set
) const {
1075 assert(PassDebugging
>= Details
);
1078 errs() << (void*)P
<< std::string(getDepth()*2+3, ' ') << Msg
<< " Analyses:";
1079 for (unsigned i
= 0; i
!= Set
.size(); ++i
) {
1080 if (i
) errs() << ",";
1081 errs() << " " << Set
[i
]->getPassName();
1086 /// Add RequiredPass into list of lower level passes required by pass P.
1087 /// RequiredPass is run on the fly by Pass Manager when P requests it
1088 /// through getAnalysis interface.
1089 /// This should be handled by specific pass manager.
1090 void PMDataManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1092 TPM
->dumpArguments();
1096 // Module Level pass may required Function Level analysis info
1097 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1098 // to provide this on demand. In that case, in Pass manager terminology,
1099 // module level pass is requiring lower level analysis info managed by
1100 // lower level pass manager.
1102 // When Pass manager is not able to order required analysis info, Pass manager
1103 // checks whether any lower level manager will be able to provide this
1104 // analysis info on demand or not.
1106 errs() << "Unable to schedule '" << RequiredPass
->getPassName();
1107 errs() << "' required by '" << P
->getPassName() << "'\n";
1109 llvm_unreachable("Unable to schedule pass");
1113 PMDataManager::~PMDataManager() {
1114 for (SmallVector
<Pass
*, 8>::iterator I
= PassVector
.begin(),
1115 E
= PassVector
.end(); I
!= E
; ++I
)
1119 //===----------------------------------------------------------------------===//
1120 // NOTE: Is this the right place to define this method ?
1121 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1122 Pass
*AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID
, bool dir
) const {
1123 return PM
.findAnalysisPass(ID
, dir
);
1126 Pass
*AnalysisResolver::findImplPass(Pass
*P
, const PassInfo
*AnalysisPI
,
1128 return PM
.getOnTheFlyPass(P
, AnalysisPI
, F
);
1131 //===----------------------------------------------------------------------===//
1132 // BBPassManager implementation
1134 /// Execute all of the passes scheduled for execution by invoking
1135 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1136 /// the function, and if so, return true.
1137 bool BBPassManager::runOnFunction(Function
&F
) {
1138 if (F
.isDeclaration())
1141 bool Changed
= doInitialization(F
);
1143 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ++I
)
1144 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1145 BasicBlockPass
*BP
= getContainedPass(Index
);
1147 dumpPassInfo(BP
, EXECUTION_MSG
, ON_BASICBLOCK_MSG
, I
->getName());
1148 dumpRequiredSet(BP
);
1150 initializeAnalysisImpl(BP
);
1153 // If the pass crashes, remember this.
1154 PassManagerPrettyStackEntry
X(BP
, *I
);
1156 if (TheTimeInfo
) TheTimeInfo
->passStarted(BP
);
1157 Changed
|= BP
->runOnBasicBlock(*I
);
1158 if (TheTimeInfo
) TheTimeInfo
->passEnded(BP
);
1162 dumpPassInfo(BP
, MODIFICATION_MSG
, ON_BASICBLOCK_MSG
,
1164 dumpPreservedSet(BP
);
1166 verifyPreservedAnalysis(BP
);
1167 removeNotPreservedAnalysis(BP
);
1168 recordAvailableAnalysis(BP
);
1169 removeDeadPasses(BP
, I
->getName(), ON_BASICBLOCK_MSG
);
1172 return Changed
|= doFinalization(F
);
1175 // Implement doInitialization and doFinalization
1176 bool BBPassManager::doInitialization(Module
&M
) {
1177 bool Changed
= false;
1179 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1180 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1185 bool BBPassManager::doFinalization(Module
&M
) {
1186 bool Changed
= false;
1188 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1189 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1194 bool BBPassManager::doInitialization(Function
&F
) {
1195 bool Changed
= false;
1197 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1198 BasicBlockPass
*BP
= getContainedPass(Index
);
1199 Changed
|= BP
->doInitialization(F
);
1205 bool BBPassManager::doFinalization(Function
&F
) {
1206 bool Changed
= false;
1208 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1209 BasicBlockPass
*BP
= getContainedPass(Index
);
1210 Changed
|= BP
->doFinalization(F
);
1217 //===----------------------------------------------------------------------===//
1218 // FunctionPassManager implementation
1220 /// Create new Function pass manager
1221 FunctionPassManager::FunctionPassManager(ModuleProvider
*P
) {
1222 FPM
= new FunctionPassManagerImpl(0);
1223 // FPM is the top level manager.
1224 FPM
->setTopLevelManager(FPM
);
1226 AnalysisResolver
*AR
= new AnalysisResolver(*FPM
);
1227 FPM
->setResolver(AR
);
1232 FunctionPassManager::~FunctionPassManager() {
1236 /// add - Add a pass to the queue of passes to run. This passes
1237 /// ownership of the Pass to the PassManager. When the
1238 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1239 /// there is no need to delete the pass. (TODO delete passes.)
1240 /// This implies that all passes MUST be allocated with 'new'.
1241 void FunctionPassManager::add(Pass
*P
) {
1245 /// run - Execute all of the passes scheduled for execution. Keep
1246 /// track of whether any of the passes modifies the function, and if
1247 /// so, return true.
1249 bool FunctionPassManager::run(Function
&F
) {
1251 if (MP
->materializeFunction(&F
, &errstr
)) {
1252 llvm_report_error("Error reading bitcode file: " + errstr
);
1258 /// doInitialization - Run all of the initializers for the function passes.
1260 bool FunctionPassManager::doInitialization() {
1261 return FPM
->doInitialization(*MP
->getModule());
1264 /// doFinalization - Run all of the finalizers for the function passes.
1266 bool FunctionPassManager::doFinalization() {
1267 return FPM
->doFinalization(*MP
->getModule());
1270 //===----------------------------------------------------------------------===//
1271 // FunctionPassManagerImpl implementation
1273 bool FunctionPassManagerImpl::doInitialization(Module
&M
) {
1274 bool Changed
= false;
1276 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1277 Changed
|= getContainedManager(Index
)->doInitialization(M
);
1282 bool FunctionPassManagerImpl::doFinalization(Module
&M
) {
1283 bool Changed
= false;
1285 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1286 Changed
|= getContainedManager(Index
)->doFinalization(M
);
1291 /// cleanup - After running all passes, clean up pass manager cache.
1292 void FPPassManager::cleanup() {
1293 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1294 FunctionPass
*FP
= getContainedPass(Index
);
1295 AnalysisResolver
*AR
= FP
->getResolver();
1296 assert(AR
&& "Analysis Resolver is not set");
1297 AR
->clearAnalysisImpls();
1301 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1304 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
1305 FPPassManager
*FPPM
= getContainedManager(Index
);
1306 for (unsigned Index
= 0; Index
< FPPM
->getNumContainedPasses(); ++Index
) {
1307 FPPM
->getContainedPass(Index
)->releaseMemory();
1313 // Execute all the passes managed by this top level manager.
1314 // Return true if any function is modified by a pass.
1315 bool FunctionPassManagerImpl::run(Function
&F
) {
1316 bool Changed
= false;
1317 TimingInfo::createTheTimeInfo();
1322 initializeAllAnalysisInfo();
1323 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1324 Changed
|= getContainedManager(Index
)->runOnFunction(F
);
1326 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1327 getContainedManager(Index
)->cleanup();
1333 //===----------------------------------------------------------------------===//
1334 // FPPassManager implementation
1336 char FPPassManager::ID
= 0;
1337 /// Print passes managed by this manager
1338 void FPPassManager::dumpPassStructure(unsigned Offset
) {
1339 llvm::errs() << std::string(Offset
*2, ' ') << "FunctionPass Manager\n";
1340 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1341 FunctionPass
*FP
= getContainedPass(Index
);
1342 FP
->dumpPassStructure(Offset
+ 1);
1343 dumpLastUses(FP
, Offset
+1);
1348 /// Execute all of the passes scheduled for execution by invoking
1349 /// runOnFunction method. Keep track of whether any of the passes modifies
1350 /// the function, and if so, return true.
1351 bool FPPassManager::runOnFunction(Function
&F
) {
1352 if (F
.isDeclaration())
1355 bool Changed
= false;
1357 // Collect inherited analysis from Module level pass manager.
1358 populateInheritedAnalysis(TPM
->activeStack
);
1360 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1361 FunctionPass
*FP
= getContainedPass(Index
);
1363 dumpPassInfo(FP
, EXECUTION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1364 dumpRequiredSet(FP
);
1366 initializeAnalysisImpl(FP
);
1369 PassManagerPrettyStackEntry
X(FP
, F
);
1371 if (TheTimeInfo
) TheTimeInfo
->passStarted(FP
);
1372 Changed
|= FP
->runOnFunction(F
);
1373 if (TheTimeInfo
) TheTimeInfo
->passEnded(FP
);
1377 dumpPassInfo(FP
, MODIFICATION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1378 dumpPreservedSet(FP
);
1380 verifyPreservedAnalysis(FP
);
1381 removeNotPreservedAnalysis(FP
);
1382 recordAvailableAnalysis(FP
);
1383 removeDeadPasses(FP
, F
.getName(), ON_FUNCTION_MSG
);
1385 // If dominator information is available then verify the info if requested.
1386 verifyDomInfo(*FP
, F
);
1391 bool FPPassManager::runOnModule(Module
&M
) {
1392 bool Changed
= doInitialization(M
);
1394 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
1397 return Changed
|= doFinalization(M
);
1400 bool FPPassManager::doInitialization(Module
&M
) {
1401 bool Changed
= false;
1403 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1404 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1409 bool FPPassManager::doFinalization(Module
&M
) {
1410 bool Changed
= false;
1412 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1413 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1418 //===----------------------------------------------------------------------===//
1419 // MPPassManager implementation
1421 /// Execute all of the passes scheduled for execution by invoking
1422 /// runOnModule method. Keep track of whether any of the passes modifies
1423 /// the module, and if so, return true.
1425 MPPassManager::runOnModule(Module
&M
) {
1426 bool Changed
= false;
1428 // Initialize on-the-fly passes
1429 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
1430 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
1432 FunctionPassManagerImpl
*FPP
= I
->second
;
1433 Changed
|= FPP
->doInitialization(M
);
1436 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1437 ModulePass
*MP
= getContainedPass(Index
);
1439 dumpPassInfo(MP
, EXECUTION_MSG
, ON_MODULE_MSG
,
1440 M
.getModuleIdentifier().c_str());
1441 dumpRequiredSet(MP
);
1443 initializeAnalysisImpl(MP
);
1446 PassManagerPrettyStackEntry
X(MP
, M
);
1447 if (TheTimeInfo
) TheTimeInfo
->passStarted(MP
);
1448 Changed
|= MP
->runOnModule(M
);
1449 if (TheTimeInfo
) TheTimeInfo
->passEnded(MP
);
1453 dumpPassInfo(MP
, MODIFICATION_MSG
, ON_MODULE_MSG
,
1454 M
.getModuleIdentifier().c_str());
1455 dumpPreservedSet(MP
);
1457 verifyPreservedAnalysis(MP
);
1458 removeNotPreservedAnalysis(MP
);
1459 recordAvailableAnalysis(MP
);
1460 removeDeadPasses(MP
, M
.getModuleIdentifier().c_str(), ON_MODULE_MSG
);
1463 // Finalize on-the-fly passes
1464 for (std::map
<Pass
*, FunctionPassManagerImpl
*>::iterator
1465 I
= OnTheFlyManagers
.begin(), E
= OnTheFlyManagers
.end();
1467 FunctionPassManagerImpl
*FPP
= I
->second
;
1468 // We don't know when is the last time an on-the-fly pass is run,
1469 // so we need to releaseMemory / finalize here
1470 FPP
->releaseMemoryOnTheFly();
1471 Changed
|= FPP
->doFinalization(M
);
1476 /// Add RequiredPass into list of lower level passes required by pass P.
1477 /// RequiredPass is run on the fly by Pass Manager when P requests it
1478 /// through getAnalysis interface.
1479 void MPPassManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1480 assert(P
->getPotentialPassManagerType() == PMT_ModulePassManager
&&
1481 "Unable to handle Pass that requires lower level Analysis pass");
1482 assert((P
->getPotentialPassManagerType() <
1483 RequiredPass
->getPotentialPassManagerType()) &&
1484 "Unable to handle Pass that requires lower level Analysis pass");
1486 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[P
];
1488 FPP
= new FunctionPassManagerImpl(0);
1489 // FPP is the top level manager.
1490 FPP
->setTopLevelManager(FPP
);
1492 OnTheFlyManagers
[P
] = FPP
;
1494 FPP
->add(RequiredPass
);
1496 // Register P as the last user of RequiredPass.
1497 SmallVector
<Pass
*, 12> LU
;
1498 LU
.push_back(RequiredPass
);
1499 FPP
->setLastUser(LU
, P
);
1502 /// Return function pass corresponding to PassInfo PI, that is
1503 /// required by module pass MP. Instantiate analysis pass, by using
1504 /// its runOnFunction() for function F.
1505 Pass
* MPPassManager::getOnTheFlyPass(Pass
*MP
, const PassInfo
*PI
, Function
&F
){
1506 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[MP
];
1507 assert(FPP
&& "Unable to find on the fly pass");
1509 FPP
->releaseMemoryOnTheFly();
1511 return (dynamic_cast<PMTopLevelManager
*>(FPP
))->findAnalysisPass(PI
);
1515 //===----------------------------------------------------------------------===//
1516 // PassManagerImpl implementation
1518 /// run - Execute all of the passes scheduled for execution. Keep track of
1519 /// whether any of the passes modifies the module, and if so, return true.
1520 bool PassManagerImpl::run(Module
&M
) {
1521 bool Changed
= false;
1522 TimingInfo::createTheTimeInfo();
1527 initializeAllAnalysisInfo();
1528 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1529 Changed
|= getContainedManager(Index
)->runOnModule(M
);
1533 //===----------------------------------------------------------------------===//
1534 // PassManager implementation
1536 /// Create new pass manager
1537 PassManager::PassManager() {
1538 PM
= new PassManagerImpl(0);
1539 // PM is the top level manager
1540 PM
->setTopLevelManager(PM
);
1543 PassManager::~PassManager() {
1547 /// add - Add a pass to the queue of passes to run. This passes ownership of
1548 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1549 /// will be destroyed as well, so there is no need to delete the pass. This
1550 /// implies that all passes MUST be allocated with 'new'.
1551 void PassManager::add(Pass
*P
) {
1555 /// run - Execute all of the passes scheduled for execution. Keep track of
1556 /// whether any of the passes modifies the module, and if so, return true.
1557 bool PassManager::run(Module
&M
) {
1561 //===----------------------------------------------------------------------===//
1562 // TimingInfo Class - This class is used to calculate information about the
1563 // amount of time each pass takes to execute. This only happens with
1564 // -time-passes is enabled on the command line.
1566 bool llvm::TimePassesIsEnabled
= false;
1567 static cl::opt
<bool,true>
1568 EnableTiming("time-passes", cl::location(TimePassesIsEnabled
),
1569 cl::desc("Time each pass, printing elapsed time for each on exit"));
1571 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1572 // a non null value (if the -time-passes option is enabled) or it leaves it
1573 // null. It may be called multiple times.
1574 void TimingInfo::createTheTimeInfo() {
1575 if (!TimePassesIsEnabled
|| TheTimeInfo
) return;
1577 // Constructed the first time this is called, iff -time-passes is enabled.
1578 // This guarantees that the object will be constructed before static globals,
1579 // thus it will be destroyed before them.
1580 static ManagedStatic
<TimingInfo
> TTI
;
1581 TheTimeInfo
= &*TTI
;
1584 /// If TimingInfo is enabled then start pass timer.
1585 void llvm::StartPassTimer(Pass
*P
) {
1587 TheTimeInfo
->passStarted(P
);
1590 /// If TimingInfo is enabled then stop pass timer.
1591 void llvm::StopPassTimer(Pass
*P
) {
1593 TheTimeInfo
->passEnded(P
);
1596 //===----------------------------------------------------------------------===//
1597 // PMStack implementation
1600 // Pop Pass Manager from the stack and clear its analysis info.
1601 void PMStack::pop() {
1603 PMDataManager
*Top
= this->top();
1604 Top
->initializeAnalysisInfo();
1609 // Push PM on the stack and set its top level manager.
1610 void PMStack::push(PMDataManager
*PM
) {
1611 assert(PM
&& "Unable to push. Pass Manager expected");
1613 if (!this->empty()) {
1614 PMTopLevelManager
*TPM
= this->top()->getTopLevelManager();
1616 assert(TPM
&& "Unable to find top level manager");
1617 TPM
->addIndirectPassManager(PM
);
1618 PM
->setTopLevelManager(TPM
);
1624 // Dump content of the pass manager stack.
1625 void PMStack::dump() {
1626 for (std::deque
<PMDataManager
*>::iterator I
= S
.begin(),
1627 E
= S
.end(); I
!= E
; ++I
)
1628 printf("%s ", dynamic_cast<Pass
*>(*I
)->getPassName());
1634 /// Find appropriate Module Pass Manager in the PM Stack and
1635 /// add self into that manager.
1636 void ModulePass::assignPassManager(PMStack
&PMS
,
1637 PassManagerType PreferredType
) {
1638 // Find Module Pass Manager
1639 while(!PMS
.empty()) {
1640 PassManagerType TopPMType
= PMS
.top()->getPassManagerType();
1641 if (TopPMType
== PreferredType
)
1642 break; // We found desired pass manager
1643 else if (TopPMType
> PMT_ModulePassManager
)
1644 PMS
.pop(); // Pop children pass managers
1648 assert(!PMS
.empty() && "Unable to find appropriate Pass Manager");
1649 PMS
.top()->add(this);
1652 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1653 /// in the PM Stack and add self into that manager.
1654 void FunctionPass::assignPassManager(PMStack
&PMS
,
1655 PassManagerType PreferredType
) {
1657 // Find Module Pass Manager
1658 while(!PMS
.empty()) {
1659 if (PMS
.top()->getPassManagerType() > PMT_FunctionPassManager
)
1664 FPPassManager
*FPP
= dynamic_cast<FPPassManager
*>(PMS
.top());
1666 // Create new Function Pass Manager
1668 assert(!PMS
.empty() && "Unable to create Function Pass Manager");
1669 PMDataManager
*PMD
= PMS
.top();
1671 // [1] Create new Function Pass Manager
1672 FPP
= new FPPassManager(PMD
->getDepth() + 1);
1673 FPP
->populateInheritedAnalysis(PMS
);
1675 // [2] Set up new manager's top level manager
1676 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1677 TPM
->addIndirectPassManager(FPP
);
1679 // [3] Assign manager to manage this new manager. This may create
1680 // and push new managers into PMS
1681 FPP
->assignPassManager(PMS
, PMD
->getPassManagerType());
1683 // [4] Push new manager into PMS
1687 // Assign FPP as the manager of this pass.
1691 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1692 /// in the PM Stack and add self into that manager.
1693 void BasicBlockPass::assignPassManager(PMStack
&PMS
,
1694 PassManagerType PreferredType
) {
1695 BBPassManager
*BBP
= NULL
;
1697 // Basic Pass Manager is a leaf pass manager. It does not handle
1698 // any other pass manager.
1700 BBP
= dynamic_cast<BBPassManager
*>(PMS
.top());
1702 // If leaf manager is not Basic Block Pass manager then create new
1703 // basic Block Pass manager.
1706 assert(!PMS
.empty() && "Unable to create BasicBlock Pass Manager");
1707 PMDataManager
*PMD
= PMS
.top();
1709 // [1] Create new Basic Block Manager
1710 BBP
= new BBPassManager(PMD
->getDepth() + 1);
1712 // [2] Set up new manager's top level manager
1713 // Basic Block Pass Manager does not live by itself
1714 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1715 TPM
->addIndirectPassManager(BBP
);
1717 // [3] Assign manager to manage this new manager. This may create
1718 // and push new managers into PMS
1719 BBP
->assignPassManager(PMS
);
1721 // [4] Push new manager into PMS
1725 // Assign BBP as the manager of this pass.
1729 PassManagerBase::~PassManagerBase() {}
1731 /*===-- C Bindings --------------------------------------------------------===*/
1733 LLVMPassManagerRef
LLVMCreatePassManager() {
1734 return wrap(new PassManager());
1737 LLVMPassManagerRef
LLVMCreateFunctionPassManager(LLVMModuleProviderRef P
) {
1738 return wrap(new FunctionPassManager(unwrap(P
)));
1741 int LLVMRunPassManager(LLVMPassManagerRef PM
, LLVMModuleRef M
) {
1742 return unwrap
<PassManager
>(PM
)->run(*unwrap(M
));
1745 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM
) {
1746 return unwrap
<FunctionPassManager
>(FPM
)->doInitialization();
1749 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM
, LLVMValueRef F
) {
1750 return unwrap
<FunctionPassManager
>(FPM
)->run(*unwrap
<Function
>(F
));
1753 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM
) {
1754 return unwrap
<FunctionPassManager
>(FPM
)->doFinalization();
1757 void LLVMDisposePassManager(LLVMPassManagerRef PM
) {