LLVM  4.0.0
LegacyPassManager.cpp
Go to the documentation of this file.
1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the legacy LLVM Pass Manager infrastructure.
11 //
12 //===----------------------------------------------------------------------===//
13 
16 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/Chrono.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/Error.h"
26 #include "llvm/Support/Mutex.h"
27 #include "llvm/Support/Timer.h"
29 #include <algorithm>
30 #include <map>
31 #include <unordered_set>
32 using namespace llvm;
33 using namespace llvm::legacy;
34 
35 // See PassManagers.h for Pass Manager infrastructure overview.
36 
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.
42 //
43 
44 namespace {
45 // Different debug levels that can be enabled...
47  Disabled, Arguments, Structure, Executions, Details
48 };
49 }
50 
52 PassDebugging("debug-pass", cl::Hidden,
53  cl::desc("Print PassManager debugging information"),
54  cl::values(
55  clEnumVal(Disabled , "disable debug output"),
56  clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
57  clEnumVal(Structure , "print pass structure before run()"),
58  clEnumVal(Executions, "print pass name before it is executed"),
59  clEnumVal(Details , "print pass details when it is executed")));
60 
61 namespace {
63 PassOptionList;
64 }
65 
66 // Print IR out before/after specified passes.
67 static PassOptionList
68 PrintBefore("print-before",
69  llvm::cl::desc("Print IR before specified passes"),
70  cl::Hidden);
71 
72 static PassOptionList
73 PrintAfter("print-after",
74  llvm::cl::desc("Print IR after specified passes"),
75  cl::Hidden);
76 
77 static cl::opt<bool>
78 PrintBeforeAll("print-before-all",
79  llvm::cl::desc("Print IR before each pass"),
80  cl::init(false));
81 static cl::opt<bool>
82 PrintAfterAll("print-after-all",
83  llvm::cl::desc("Print IR after each pass"),
84  cl::init(false));
85 
87  PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
88  cl::desc("Only print IR for functions whose name "
89  "match this for all print-[before|after][-all] "
90  "options"),
92 
93 /// This is a helper to determine whether to print IR before or
94 /// after a pass.
95 
96 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
97  PassOptionList &PassesToPrint) {
98  for (auto *PassInf : PassesToPrint) {
99  if (PassInf)
100  if (PassInf->getPassArgument() == PI->getPassArgument()) {
101  return true;
102  }
103  }
104  return false;
105 }
106 
107 /// This is a utility to check whether a pass should have IR dumped
108 /// before it.
109 static bool ShouldPrintBeforePass(const PassInfo *PI) {
111 }
112 
113 /// This is a utility to check whether a pass should have IR dumped
114 /// after it.
115 static bool ShouldPrintAfterPass(const PassInfo *PI) {
117 }
118 
120  static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
121  PrintFuncsList.end());
122  return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
123 }
124 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
125 /// or higher is specified.
127  return PassDebugging >= Executions;
128 }
129 
130 
131 
132 
134  if (!V && !M)
135  OS << "Releasing pass '";
136  else
137  OS << "Running pass '";
138 
139  OS << P->getPassName() << "'";
140 
141  if (M) {
142  OS << " on module '" << M->getModuleIdentifier() << "'.\n";
143  return;
144  }
145  if (!V) {
146  OS << '\n';
147  return;
148  }
149 
150  OS << " on ";
151  if (isa<Function>(V))
152  OS << "function";
153  else if (isa<BasicBlock>(V))
154  OS << "basic block";
155  else
156  OS << "value";
157 
158  OS << " '";
159  V->printAsOperand(OS, /*PrintTy=*/false, M);
160  OS << "'\n";
161 }
162 
163 
164 namespace {
165 //===----------------------------------------------------------------------===//
166 // BBPassManager
167 //
168 /// BBPassManager manages BasicBlockPass. It batches all the
169 /// pass together and sequence them to process one basic block before
170 /// processing next basic block.
171 class BBPassManager : public PMDataManager, public FunctionPass {
172 
173 public:
174  static char ID;
175  explicit BBPassManager()
176  : PMDataManager(), FunctionPass(ID) {}
177 
178  /// Execute all of the passes scheduled for execution. Keep track of
179  /// whether any of the passes modifies the function, and if so, return true.
180  bool runOnFunction(Function &F) override;
181 
182  /// Pass Manager itself does not invalidate any analysis info.
183  void getAnalysisUsage(AnalysisUsage &Info) const override {
184  Info.setPreservesAll();
185  }
186 
187  bool doInitialization(Module &M) override;
188  bool doInitialization(Function &F);
189  bool doFinalization(Module &M) override;
190  bool doFinalization(Function &F);
191 
192  PMDataManager *getAsPMDataManager() override { return this; }
193  Pass *getAsPass() override { return this; }
194 
195  StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
196 
197  // Print passes managed by this manager
198  void dumpPassStructure(unsigned Offset) override {
199  dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
200  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
201  BasicBlockPass *BP = getContainedPass(Index);
202  BP->dumpPassStructure(Offset + 1);
203  dumpLastUses(BP, Offset+1);
204  }
205  }
206 
207  BasicBlockPass *getContainedPass(unsigned N) {
208  assert(N < PassVector.size() && "Pass number out of range!");
209  BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
210  return BP;
211  }
212 
213  PassManagerType getPassManagerType() const override {
215  }
216 };
217 
218 char BBPassManager::ID = 0;
219 } // End anonymous namespace
220 
221 namespace llvm {
222 namespace legacy {
223 //===----------------------------------------------------------------------===//
224 // FunctionPassManagerImpl
225 //
226 /// FunctionPassManagerImpl manages FPPassManagers
228  public PMDataManager,
229  public PMTopLevelManager {
230  virtual void anchor();
231 private:
232  bool wasRun;
233 public:
234  static char ID;
237  PMTopLevelManager(new FPPassManager()), wasRun(false) {}
238 
239  /// \copydoc FunctionPassManager::add()
240  void add(Pass *P) {
241  schedulePass(P);
242  }
243 
244  /// createPrinterPass - Get a function printer pass.
246  const std::string &Banner) const override {
247  return createPrintFunctionPass(O, Banner);
248  }
249 
250  // Prepare for running an on the fly pass, freeing memory if needed
251  // from a previous run.
252  void releaseMemoryOnTheFly();
253 
254  /// run - Execute all of the passes scheduled for execution. Keep track of
255  /// whether any of the passes modifies the module, and if so, return true.
256  bool run(Function &F);
257 
258  /// doInitialization - Run all of the initializers for the function passes.
259  ///
260  bool doInitialization(Module &M) override;
261 
262  /// doFinalization - Run all of the finalizers for the function passes.
263  ///
264  bool doFinalization(Module &M) override;
265 
266 
267  PMDataManager *getAsPMDataManager() override { return this; }
268  Pass *getAsPass() override { return this; }
271  }
272 
273  /// Pass Manager itself does not invalidate any analysis info.
274  void getAnalysisUsage(AnalysisUsage &Info) const override {
275  Info.setPreservesAll();
276  }
277 
279  assert(N < PassManagers.size() && "Pass number out of range!");
280  FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
281  return FP;
282  }
283 };
284 
285 void FunctionPassManagerImpl::anchor() {}
286 
288 } // End of legacy namespace
289 } // End of llvm namespace
290 
291 namespace {
292 //===----------------------------------------------------------------------===//
293 // MPPassManager
294 //
295 /// MPPassManager manages ModulePasses and function pass managers.
296 /// It batches all Module passes and function pass managers together and
297 /// sequences them to process one module.
298 class MPPassManager : public Pass, public PMDataManager {
299 public:
300  static char ID;
301  explicit MPPassManager() :
303 
304  // Delete on the fly managers.
305  ~MPPassManager() override {
306  for (auto &OnTheFlyManager : OnTheFlyManagers) {
307  FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
308  delete FPP;
309  }
310  }
311 
312  /// createPrinterPass - Get a module printer pass.
313  Pass *createPrinterPass(raw_ostream &O,
314  const std::string &Banner) const override {
315  return createPrintModulePass(O, Banner);
316  }
317 
318  /// run - Execute all of the passes scheduled for execution. Keep track of
319  /// whether any of the passes modifies the module, and if so, return true.
320  bool runOnModule(Module &M);
321 
324 
325  /// Pass Manager itself does not invalidate any analysis info.
326  void getAnalysisUsage(AnalysisUsage &Info) const override {
327  Info.setPreservesAll();
328  }
329 
330  /// Add RequiredPass into list of lower level passes required by pass P.
331  /// RequiredPass is run on the fly by Pass Manager when P requests it
332  /// through getAnalysis interface.
333  void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
334 
335  /// Return function pass corresponding to PassInfo PI, that is
336  /// required by module pass MP. Instantiate analysis pass, by using
337  /// its runOnFunction() for function F.
338  Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
339 
340  StringRef getPassName() const override { return "Module Pass Manager"; }
341 
342  PMDataManager *getAsPMDataManager() override { return this; }
343  Pass *getAsPass() override { return this; }
344 
345  // Print passes managed by this manager
346  void dumpPassStructure(unsigned Offset) override {
347  dbgs().indent(Offset*2) << "ModulePass Manager\n";
348  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349  ModulePass *MP = getContainedPass(Index);
350  MP->dumpPassStructure(Offset + 1);
351  std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352  OnTheFlyManagers.find(MP);
353  if (I != OnTheFlyManagers.end())
354  I->second->dumpPassStructure(Offset + 2);
355  dumpLastUses(MP, Offset+1);
356  }
357  }
358 
359  ModulePass *getContainedPass(unsigned N) {
360  assert(N < PassVector.size() && "Pass number out of range!");
361  return static_cast<ModulePass *>(PassVector[N]);
362  }
363 
364  PassManagerType getPassManagerType() const override {
365  return PMT_ModulePassManager;
366  }
367 
368  private:
369  /// Collection of on the fly FPPassManagers. These managers manage
370  /// function passes that are required by module passes.
371  std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
372 };
373 
374 char MPPassManager::ID = 0;
375 } // End anonymous namespace
376 
377 namespace llvm {
378 namespace legacy {
379 //===----------------------------------------------------------------------===//
380 // PassManagerImpl
381 //
382 
383 /// PassManagerImpl manages MPPassManagers
384 class PassManagerImpl : public Pass,
385  public PMDataManager,
386  public PMTopLevelManager {
387  virtual void anchor();
388 
389 public:
390  static char ID;
391  explicit PassManagerImpl() :
393  PMTopLevelManager(new MPPassManager()) {}
394 
395  /// \copydoc PassManager::add()
396  void add(Pass *P) {
397  schedulePass(P);
398  }
399 
400  /// createPrinterPass - Get a module printer pass.
402  const std::string &Banner) const override {
403  return createPrintModulePass(O, Banner);
404  }
405 
406  /// run - Execute all of the passes scheduled for execution. Keep track of
407  /// whether any of the passes modifies the module, and if so, return true.
408  bool run(Module &M);
409 
412 
413  /// Pass Manager itself does not invalidate any analysis info.
414  void getAnalysisUsage(AnalysisUsage &Info) const override {
415  Info.setPreservesAll();
416  }
417 
418  PMDataManager *getAsPMDataManager() override { return this; }
419  Pass *getAsPass() override { return this; }
421  return PMT_ModulePassManager;
422  }
423 
424  MPPassManager *getContainedManager(unsigned N) {
425  assert(N < PassManagers.size() && "Pass number out of range!");
426  MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
427  return MP;
428  }
429 };
430 
431 void PassManagerImpl::anchor() {}
432 
433 char PassManagerImpl::ID = 0;
434 } // End of legacy namespace
435 } // End of llvm namespace
436 
437 namespace {
438 
439 //===----------------------------------------------------------------------===//
440 /// TimingInfo Class - This class is used to calculate information about the
441 /// amount of time each pass takes to execute. This only happens when
442 /// -time-passes is enabled on the command line.
443 ///
444 
445 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
446 
447 class TimingInfo {
448  DenseMap<Pass*, Timer*> TimingData;
449  TimerGroup TG;
450 public:
451  // Use 'create' member to get this.
452  TimingInfo() : TG("pass", "... Pass execution timing report ...") {}
453 
454  // TimingDtor - Print out information about timing information
455  ~TimingInfo() {
456  // Delete all of the timers, which accumulate their info into the
457  // TimerGroup.
458  for (auto &I : TimingData)
459  delete I.second;
460  // TimerGroup is deleted next, printing the report.
461  }
462 
463  // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
464  // to a non-null value (if the -time-passes option is enabled) or it leaves it
465  // null. It may be called multiple times.
466  static void createTheTimeInfo();
467 
468  /// getPassTimer - Return the timer for the specified pass if it exists.
469  Timer *getPassTimer(Pass *P) {
470  if (P->getAsPMDataManager())
471  return nullptr;
472 
473  sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
474  Timer *&T = TimingData[P];
475  if (!T) {
476  StringRef PassName = P->getPassName();
477  T = new Timer(PassName, PassName, TG);
478  }
479  return T;
480  }
481 };
482 
483 } // End of anon namespace
484 
485 static TimingInfo *TheTimeInfo;
486 
487 //===----------------------------------------------------------------------===//
488 // PMTopLevelManager implementation
489 
490 /// Initialize top level manager. Create first pass manager.
492  PMDM->setTopLevelManager(this);
493  addPassManager(PMDM);
494  activeStack.push(PMDM);
495 }
496 
497 /// Set pass P as the last user of the given analysis passes.
498 void
500  unsigned PDepth = 0;
501  if (P->getResolver())
502  PDepth = P->getResolver()->getPMDataManager().getDepth();
503 
504  for (Pass *AP : AnalysisPasses) {
505  LastUser[AP] = P;
506 
507  if (P == AP)
508  continue;
509 
510  // Update the last users of passes that are required transitive by AP.
511  AnalysisUsage *AnUsage = findAnalysisUsage(AP);
512  const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
513  SmallVector<Pass *, 12> LastUses;
514  SmallVector<Pass *, 12> LastPMUses;
515  for (AnalysisID ID : IDs) {
516  Pass *AnalysisPass = findAnalysisPass(ID);
517  assert(AnalysisPass && "Expected analysis pass to exist.");
518  AnalysisResolver *AR = AnalysisPass->getResolver();
519  assert(AR && "Expected analysis resolver to exist.");
520  unsigned APDepth = AR->getPMDataManager().getDepth();
521 
522  if (PDepth == APDepth)
523  LastUses.push_back(AnalysisPass);
524  else if (PDepth > APDepth)
525  LastPMUses.push_back(AnalysisPass);
526  }
527 
528  setLastUser(LastUses, P);
529 
530  // If this pass has a corresponding pass manager, push higher level
531  // analysis to this pass manager.
532  if (P->getResolver())
533  setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
534 
535 
536  // If AP is the last user of other passes then make P last user of
537  // such passes.
538  for (auto LU : LastUser) {
539  if (LU.second == AP)
540  // DenseMap iterator is not invalidated here because
541  // this is just updating existing entries.
542  LastUser[LU.first] = P;
543  }
544  }
545 }
546 
547 /// Collect passes whose last user is P
549  Pass *P) {
551  InversedLastUser.find(P);
552  if (DMI == InversedLastUser.end())
553  return;
554 
555  SmallPtrSet<Pass *, 8> &LU = DMI->second;
556  for (Pass *LUP : LU) {
557  LastUses.push_back(LUP);
558  }
559 
560 }
561 
563  AnalysisUsage *AnUsage = nullptr;
564  auto DMI = AnUsageMap.find(P);
565  if (DMI != AnUsageMap.end())
566  AnUsage = DMI->second;
567  else {
568  // Look up the analysis usage from the pass instance (different instances
569  // of the same pass can produce different results), but unique the
570  // resulting object to reduce memory usage. This helps to greatly reduce
571  // memory usage when we have many instances of only a few pass types
572  // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
573  // of dependencies.
574  AnalysisUsage AU;
575  P->getAnalysisUsage(AU);
576 
577  AUFoldingSetNode* Node = nullptr;
579  AUFoldingSetNode::Profile(ID, AU);
580  void *IP = nullptr;
581  if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
582  Node = N;
583  else {
584  Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
585  UniqueAnalysisUsages.InsertNode(Node, IP);
586  }
587  assert(Node && "cached analysis usage must be non null");
588 
589  AnUsageMap[P] = &Node->AU;
590  AnUsage = &Node->AU;;
591  }
592  return AnUsage;
593 }
594 
595 /// Schedule pass P for execution. Make sure that passes required by
596 /// P are run before P is run. Update analysis info maintained by
597 /// the manager. Remove dead passes. This is a recursive function.
599 
600  // TODO : Allocate function manager for this pass, other wise required set
601  // may be inserted into previous function manager
602 
603  // Give pass a chance to prepare the stage.
605 
606  // If P is an analysis pass and it is available then do not
607  // generate the analysis again. Stale analysis info should not be
608  // available at this point.
609  const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
610  if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
611  delete P;
612  return;
613  }
614 
615  AnalysisUsage *AnUsage = findAnalysisUsage(P);
616 
617  bool checkAnalysis = true;
618  while (checkAnalysis) {
619  checkAnalysis = false;
620 
621  const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
623  E = RequiredSet.end(); I != E; ++I) {
624 
625  Pass *AnalysisPass = findAnalysisPass(*I);
626  if (!AnalysisPass) {
627  const PassInfo *PI = findAnalysisPassInfo(*I);
628 
629  if (!PI) {
630  // Pass P is not in the global PassRegistry
631  dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
632  dbgs() << "Verify if there is a pass dependency cycle." << "\n";
633  dbgs() << "Required Passes:" << "\n";
634  for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
635  E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
636  Pass *AnalysisPass2 = findAnalysisPass(*I2);
637  if (AnalysisPass2) {
638  dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
639  } else {
640  dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
641  dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
642  dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
643  }
644  }
645  }
646 
647  assert(PI && "Expected required passes to be initialized");
648  AnalysisPass = PI->createPass();
649  if (P->getPotentialPassManagerType () ==
650  AnalysisPass->getPotentialPassManagerType())
651  // Schedule analysis pass that is managed by the same pass manager.
652  schedulePass(AnalysisPass);
653  else if (P->getPotentialPassManagerType () >
654  AnalysisPass->getPotentialPassManagerType()) {
655  // Schedule analysis pass that is managed by a new manager.
656  schedulePass(AnalysisPass);
657  // Recheck analysis passes to ensure that required analyses that
658  // are already checked are still available.
659  checkAnalysis = true;
660  } else
661  // Do not schedule this analysis. Lower level analysis
662  // passes are run on the fly.
663  delete AnalysisPass;
664  }
665  }
666  }
667 
668  // Now all required passes are available.
669  if (ImmutablePass *IP = P->getAsImmutablePass()) {
670  // P is a immutable pass and it will be managed by this
671  // top level manager. Set up analysis resolver to connect them.
672  PMDataManager *DM = getAsPMDataManager();
673  AnalysisResolver *AR = new AnalysisResolver(*DM);
674  P->setResolver(AR);
675  DM->initializeAnalysisImpl(P);
676  addImmutablePass(IP);
677  DM->recordAvailableAnalysis(IP);
678  return;
679  }
680 
681  if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
682  Pass *PP = P->createPrinterPass(
683  dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
684  PP->assignPassManager(activeStack, getTopLevelPassManagerType());
685  }
686 
687  // Add the requested pass to the best available pass manager.
688  P->assignPassManager(activeStack, getTopLevelPassManagerType());
689 
690  if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
691  Pass *PP = P->createPrinterPass(
692  dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
693  PP->assignPassManager(activeStack, getTopLevelPassManagerType());
694  }
695 }
696 
697 /// Find the pass that implements Analysis AID. Search immutable
698 /// passes and all pass managers. If desired pass is not found
699 /// then return NULL.
701  // For immutable passes we have a direct mapping from ID to pass, so check
702  // that first.
703  if (Pass *P = ImmutablePassMap.lookup(AID))
704  return P;
705 
706  // Check pass managers
708  if (Pass *P = PassManager->findAnalysisPass(AID, false))
709  return P;
710 
711  // Check other pass managers
712  for (PMDataManager *IndirectPassManager : IndirectPassManagers)
713  if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
714  return P;
715 
716  return nullptr;
717 }
718 
720  const PassInfo *&PI = AnalysisPassInfos[AID];
721  if (!PI)
723  else
724  assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
725  "The pass info pointer changed for an analysis ID!");
726 
727  return PI;
728 }
729 
731  P->initializePass();
732  ImmutablePasses.push_back(P);
733 
734  // Add this pass to the map from its analysis ID. We clobber any prior runs
735  // of the pass in the map so that the last one added is the one found when
736  // doing lookups.
737  AnalysisID AID = P->getPassID();
738  ImmutablePassMap[AID] = P;
739 
740  // Also add any interfaces implemented by the immutable pass to the map for
741  // fast lookup.
742  const PassInfo *PassInf = findAnalysisPassInfo(AID);
743  assert(PassInf && "Expected all immutable passes to be initialized");
744  for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
745  ImmutablePassMap[ImmPI->getTypeInfo()] = P;
746 }
747 
748 // Print passes managed by this top level manager.
750 
751  if (PassDebugging < Structure)
752  return;
753 
754  // Print out the immutable passes
755  for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
756  ImmutablePasses[i]->dumpPassStructure(0);
757  }
758 
759  // Every class that derives from PMDataManager also derives from Pass
760  // (sometimes indirectly), but there's no inheritance relationship
761  // between PMDataManager and Pass, so we have to getAsPass to get
762  // from a PMDataManager* to a Pass*.
763  for (PMDataManager *Manager : PassManagers)
764  Manager->getAsPass()->dumpPassStructure(1);
765 }
766 
768 
769  if (PassDebugging < Arguments)
770  return;
771 
772  dbgs() << "Pass Arguments: ";
773  for (ImmutablePass *P : ImmutablePasses)
774  if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
775  assert(PI && "Expected all immutable passes to be initialized");
776  if (!PI->isAnalysisGroup())
777  dbgs() << " -" << PI->getPassArgument();
778  }
779  for (PMDataManager *PM : PassManagers)
780  PM->dumpPassArguments();
781  dbgs() << "\n";
782 }
783 
785  for (PMDataManager *PM : PassManagers)
786  PM->initializeAnalysisInfo();
787 
788  // Initailize other pass managers
789  for (PMDataManager *IPM : IndirectPassManagers)
790  IPM->initializeAnalysisInfo();
791 
792  for (auto LU : LastUser) {
793  SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
794  L.insert(LU.first);
795  }
796 }
797 
798 /// Destructor
800  for (PMDataManager *PM : PassManagers)
801  delete PM;
802 
803  for (ImmutablePass *P : ImmutablePasses)
804  delete P;
805 }
806 
807 //===----------------------------------------------------------------------===//
808 // PMDataManager implementation
809 
810 /// Augement AvailableAnalysis by adding analysis made available by pass P.
812  AnalysisID PI = P->getPassID();
813 
814  AvailableAnalysis[PI] = P;
815 
816  assert(!AvailableAnalysis.empty());
817 
818  // This pass is the current implementation of all of the interfaces it
819  // implements as well.
820  const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
821  if (!PInf) return;
822  const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
823  for (unsigned i = 0, e = II.size(); i != e; ++i)
824  AvailableAnalysis[II[i]->getTypeInfo()] = P;
825 }
826 
827 // Return true if P preserves high level analysis used by other
828 // passes managed by this manager
830  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
831  if (AnUsage->getPreservesAll())
832  return true;
833 
834  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
835  for (Pass *P1 : HigherLevelAnalysis) {
836  if (P1->getAsImmutablePass() == nullptr &&
837  !is_contained(PreservedSet, P1->getPassID()))
838  return false;
839  }
840 
841  return true;
842 }
843 
844 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
846  // Don't do this unless assertions are enabled.
847 #ifdef NDEBUG
848  return;
849 #endif
850  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
851  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
852 
853  // Verify preserved analysis
854  for (AnalysisID AID : PreservedSet) {
855  if (Pass *AP = findAnalysisPass(AID, true)) {
856  TimeRegion PassTimer(getPassTimer(AP));
857  AP->verifyAnalysis();
858  }
859  }
860 }
861 
862 /// Remove Analysis not preserved by Pass P
864  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
865  if (AnUsage->getPreservesAll())
866  return;
867 
868  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
869  for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
870  E = AvailableAnalysis.end(); I != E; ) {
872  if (Info->second->getAsImmutablePass() == nullptr &&
873  !is_contained(PreservedSet, Info->first)) {
874  // Remove this analysis
875  if (PassDebugging >= Details) {
876  Pass *S = Info->second;
877  dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
878  dbgs() << S->getPassName() << "'\n";
879  }
880  AvailableAnalysis.erase(Info);
881  }
882  }
883 
884  // Check inherited analysis also. If P is not preserving analysis
885  // provided by parent manager then remove it here.
886  for (unsigned Index = 0; Index < PMT_Last; ++Index) {
887 
888  if (!InheritedAnalysis[Index])
889  continue;
890 
892  I = InheritedAnalysis[Index]->begin(),
893  E = InheritedAnalysis[Index]->end(); I != E; ) {
895  if (Info->second->getAsImmutablePass() == nullptr &&
896  !is_contained(PreservedSet, Info->first)) {
897  // Remove this analysis
898  if (PassDebugging >= Details) {
899  Pass *S = Info->second;
900  dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
901  dbgs() << S->getPassName() << "'\n";
902  }
903  InheritedAnalysis[Index]->erase(Info);
904  }
905  }
906  }
907 }
908 
909 /// Remove analysis passes that are not used any longer
911  enum PassDebuggingString DBG_STR) {
912 
913  SmallVector<Pass *, 12> DeadPasses;
914 
915  // If this is a on the fly manager then it does not have TPM.
916  if (!TPM)
917  return;
918 
919  TPM->collectLastUses(DeadPasses, P);
920 
921  if (PassDebugging >= Details && !DeadPasses.empty()) {
922  dbgs() << " -*- '" << P->getPassName();
923  dbgs() << "' is the last user of following pass instances.";
924  dbgs() << " Free these instances\n";
925  }
926 
927  for (Pass *P : DeadPasses)
928  freePass(P, Msg, DBG_STR);
929 }
930 
932  enum PassDebuggingString DBG_STR) {
933  dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
934 
935  {
936  // If the pass crashes releasing memory, remember this.
938  TimeRegion PassTimer(getPassTimer(P));
939 
940  P->releaseMemory();
941  }
942 
943  AnalysisID PI = P->getPassID();
944  if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
945  // Remove the pass itself (if it is not already removed).
946  AvailableAnalysis.erase(PI);
947 
948  // Remove all interfaces this pass implements, for which it is also
949  // listed as the available implementation.
950  const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
951  for (unsigned i = 0, e = II.size(); i != e; ++i) {
953  AvailableAnalysis.find(II[i]->getTypeInfo());
954  if (Pos != AvailableAnalysis.end() && Pos->second == P)
955  AvailableAnalysis.erase(Pos);
956  }
957  }
958 }
959 
960 /// Add pass P into the PassVector. Update
961 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
962 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
963  // This manager is going to manage pass P. Set up analysis resolver
964  // to connect them.
965  AnalysisResolver *AR = new AnalysisResolver(*this);
966  P->setResolver(AR);
967 
968  // If a FunctionPass F is the last user of ModulePass info M
969  // then the F's manager, not F, records itself as a last user of M.
970  SmallVector<Pass *, 12> TransferLastUses;
971 
972  if (!ProcessAnalysis) {
973  // Add pass
974  PassVector.push_back(P);
975  return;
976  }
977 
978  // At the moment, this pass is the last user of all required passes.
979  SmallVector<Pass *, 12> LastUses;
980  SmallVector<Pass *, 8> UsedPasses;
981  SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
982 
983  unsigned PDepth = this->getDepth();
984 
985  collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
986  for (Pass *PUsed : UsedPasses) {
987  unsigned RDepth = 0;
988 
989  assert(PUsed->getResolver() && "Analysis Resolver is not set");
990  PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
991  RDepth = DM.getDepth();
992 
993  if (PDepth == RDepth)
994  LastUses.push_back(PUsed);
995  else if (PDepth > RDepth) {
996  // Let the parent claim responsibility of last use
997  TransferLastUses.push_back(PUsed);
998  // Keep track of higher level analysis used by this manager.
999  HigherLevelAnalysis.push_back(PUsed);
1000  } else
1001  llvm_unreachable("Unable to accommodate Used Pass");
1002  }
1003 
1004  // Set P as P's last user until someone starts using P.
1005  // However, if P is a Pass Manager then it does not need
1006  // to record its last user.
1007  if (!P->getAsPMDataManager())
1008  LastUses.push_back(P);
1009  TPM->setLastUser(LastUses, P);
1010 
1011  if (!TransferLastUses.empty()) {
1012  Pass *My_PM = getAsPass();
1013  TPM->setLastUser(TransferLastUses, My_PM);
1014  TransferLastUses.clear();
1015  }
1016 
1017  // Now, take care of required analyses that are not available.
1018  for (AnalysisID ID : ReqAnalysisNotAvailable) {
1019  const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1020  Pass *AnalysisPass = PI->createPass();
1021  this->addLowerLevelRequiredPass(P, AnalysisPass);
1022  }
1023 
1024  // Take a note of analysis required and made available by this pass.
1025  // Remove the analysis not preserved by this pass
1028 
1029  // Add pass
1030  PassVector.push_back(P);
1031 }
1032 
1033 
1034 /// Populate UP with analysis pass that are used or required by
1035 /// pass P and are available. Populate RP_NotAvail with analysis
1036 /// pass that are required by pass P but are not available.
1039  Pass *P) {
1040  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1041 
1042  for (const auto &UsedID : AnUsage->getUsedSet())
1043  if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1044  UP.push_back(AnalysisPass);
1045 
1046  for (const auto &RequiredID : AnUsage->getRequiredSet())
1047  if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1048  UP.push_back(AnalysisPass);
1049  else
1050  RP_NotAvail.push_back(RequiredID);
1051 
1052  for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1053  if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1054  UP.push_back(AnalysisPass);
1055  else
1056  RP_NotAvail.push_back(RequiredID);
1057 }
1058 
1059 // All Required analyses should be available to the pass as it runs! Here
1060 // we fill in the AnalysisImpls member of the pass so that it can
1061 // successfully use the getAnalysis() method to retrieve the
1062 // implementations it needs.
1063 //
1065  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1066 
1068  I = AnUsage->getRequiredSet().begin(),
1069  E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1070  Pass *Impl = findAnalysisPass(*I, true);
1071  if (!Impl)
1072  // This may be analysis pass that is initialized on the fly.
1073  // If that is not the case then it will raise an assert when it is used.
1074  continue;
1075  AnalysisResolver *AR = P->getResolver();
1076  assert(AR && "Analysis Resolver is not set");
1077  AR->addAnalysisImplsPair(*I, Impl);
1078  }
1079 }
1080 
1081 /// Find the pass that implements Analysis AID. If desired pass is not found
1082 /// then return NULL.
1084 
1085  // Check if AvailableAnalysis map has one entry.
1086  DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1087 
1088  if (I != AvailableAnalysis.end())
1089  return I->second;
1090 
1091  // Search Parents through TopLevelManager
1092  if (SearchParent)
1093  return TPM->findAnalysisPass(AID);
1094 
1095  return nullptr;
1096 }
1097 
1098 // Print list of passes that are last used by P.
1099 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1100 
1102 
1103  // If this is a on the fly manager then it does not have TPM.
1104  if (!TPM)
1105  return;
1106 
1107  TPM->collectLastUses(LUses, P);
1108 
1109  for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1110  E = LUses.end(); I != E; ++I) {
1111  dbgs() << "--" << std::string(Offset*2, ' ');
1112  (*I)->dumpPassStructure(0);
1113  }
1114 }
1115 
1118  E = PassVector.end(); I != E; ++I) {
1119  if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1120  PMD->dumpPassArguments();
1121  else
1122  if (const PassInfo *PI =
1123  TPM->findAnalysisPassInfo((*I)->getPassID()))
1124  if (!PI->isAnalysisGroup())
1125  dbgs() << " -" << PI->getPassArgument();
1126  }
1127 }
1128 
1130  enum PassDebuggingString S2,
1131  StringRef Msg) {
1132  if (PassDebugging < Executions)
1133  return;
1134  dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1135  << std::string(getDepth() * 2 + 1, ' ');
1136  switch (S1) {
1137  case EXECUTION_MSG:
1138  dbgs() << "Executing Pass '" << P->getPassName();
1139  break;
1140  case MODIFICATION_MSG:
1141  dbgs() << "Made Modification '" << P->getPassName();
1142  break;
1143  case FREEING_MSG:
1144  dbgs() << " Freeing Pass '" << P->getPassName();
1145  break;
1146  default:
1147  break;
1148  }
1149  switch (S2) {
1150  case ON_BASICBLOCK_MSG:
1151  dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1152  break;
1153  case ON_FUNCTION_MSG:
1154  dbgs() << "' on Function '" << Msg << "'...\n";
1155  break;
1156  case ON_MODULE_MSG:
1157  dbgs() << "' on Module '" << Msg << "'...\n";
1158  break;
1159  case ON_REGION_MSG:
1160  dbgs() << "' on Region '" << Msg << "'...\n";
1161  break;
1162  case ON_LOOP_MSG:
1163  dbgs() << "' on Loop '" << Msg << "'...\n";
1164  break;
1165  case ON_CG_MSG:
1166  dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1167  break;
1168  default:
1169  break;
1170  }
1171 }
1172 
1174  if (PassDebugging < Details)
1175  return;
1176 
1177  AnalysisUsage analysisUsage;
1178  P->getAnalysisUsage(analysisUsage);
1179  dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1180 }
1181 
1183  if (PassDebugging < Details)
1184  return;
1185 
1186  AnalysisUsage analysisUsage;
1187  P->getAnalysisUsage(analysisUsage);
1188  dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1189 }
1190 
1191 void PMDataManager::dumpUsedSet(const Pass *P) const {
1192  if (PassDebugging < Details)
1193  return;
1194 
1195  AnalysisUsage analysisUsage;
1196  P->getAnalysisUsage(analysisUsage);
1197  dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1198 }
1199 
1200 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1201  const AnalysisUsage::VectorType &Set) const {
1202  assert(PassDebugging >= Details);
1203  if (Set.empty())
1204  return;
1205  dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1206  for (unsigned i = 0; i != Set.size(); ++i) {
1207  if (i) dbgs() << ',';
1208  const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1209  if (!PInf) {
1210  // Some preserved passes, such as AliasAnalysis, may not be initialized by
1211  // all drivers.
1212  dbgs() << " Uninitialized Pass";
1213  continue;
1214  }
1215  dbgs() << ' ' << PInf->getPassName();
1216  }
1217  dbgs() << '\n';
1218 }
1219 
1220 /// Add RequiredPass into list of lower level passes required by pass P.
1221 /// RequiredPass is run on the fly by Pass Manager when P requests it
1222 /// through getAnalysis interface.
1223 /// This should be handled by specific pass manager.
1225  if (TPM) {
1226  TPM->dumpArguments();
1227  TPM->dumpPasses();
1228  }
1229 
1230  // Module Level pass may required Function Level analysis info
1231  // (e.g. dominator info). Pass manager uses on the fly function pass manager
1232  // to provide this on demand. In that case, in Pass manager terminology,
1233  // module level pass is requiring lower level analysis info managed by
1234  // lower level pass manager.
1235 
1236  // When Pass manager is not able to order required analysis info, Pass manager
1237  // checks whether any lower level manager will be able to provide this
1238  // analysis info on demand or not.
1239 #ifndef NDEBUG
1240  dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1241  dbgs() << "' required by '" << P->getPassName() << "'\n";
1242 #endif
1243  llvm_unreachable("Unable to schedule pass");
1244 }
1245 
1247  llvm_unreachable("Unable to find on the fly pass");
1248 }
1249 
1250 // Destructor
1253  E = PassVector.end(); I != E; ++I)
1254  delete *I;
1255 }
1256 
1257 //===----------------------------------------------------------------------===//
1258 // NOTE: Is this the right place to define this method ?
1259 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1261  return PM.findAnalysisPass(ID, dir);
1262 }
1263 
1265  Function &F) {
1266  return PM.getOnTheFlyPass(P, AnalysisPI, F);
1267 }
1268 
1269 //===----------------------------------------------------------------------===//
1270 // BBPassManager implementation
1271 
1272 /// Execute all of the passes scheduled for execution by invoking
1273 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1274 /// the function, and if so, return true.
1275 bool BBPassManager::runOnFunction(Function &F) {
1276  if (F.isDeclaration())
1277  return false;
1278 
1279  bool Changed = doInitialization(F);
1280 
1281  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1282  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1283  BasicBlockPass *BP = getContainedPass(Index);
1284  bool LocalChanged = false;
1285 
1286  dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1287  dumpRequiredSet(BP);
1288 
1289  initializeAnalysisImpl(BP);
1290 
1291  {
1292  // If the pass crashes, remember this.
1294  TimeRegion PassTimer(getPassTimer(BP));
1295 
1296  LocalChanged |= BP->runOnBasicBlock(*I);
1297  }
1298 
1299  Changed |= LocalChanged;
1300  if (LocalChanged)
1301  dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1302  I->getName());
1303  dumpPreservedSet(BP);
1304  dumpUsedSet(BP);
1305 
1306  verifyPreservedAnalysis(BP);
1307  removeNotPreservedAnalysis(BP);
1308  recordAvailableAnalysis(BP);
1309  removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1310  }
1311 
1312  return doFinalization(F) || Changed;
1313 }
1314 
1315 // Implement doInitialization and doFinalization
1316 bool BBPassManager::doInitialization(Module &M) {
1317  bool Changed = false;
1318 
1319  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1320  Changed |= getContainedPass(Index)->doInitialization(M);
1321 
1322  return Changed;
1323 }
1324 
1325 bool BBPassManager::doFinalization(Module &M) {
1326  bool Changed = false;
1327 
1328  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1329  Changed |= getContainedPass(Index)->doFinalization(M);
1330 
1331  return Changed;
1332 }
1333 
1334 bool BBPassManager::doInitialization(Function &F) {
1335  bool Changed = false;
1336 
1337  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1338  BasicBlockPass *BP = getContainedPass(Index);
1339  Changed |= BP->doInitialization(F);
1340  }
1341 
1342  return Changed;
1343 }
1344 
1345 bool BBPassManager::doFinalization(Function &F) {
1346  bool Changed = false;
1347 
1348  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1349  BasicBlockPass *BP = getContainedPass(Index);
1350  Changed |= BP->doFinalization(F);
1351  }
1352 
1353  return Changed;
1354 }
1355 
1356 
1357 //===----------------------------------------------------------------------===//
1358 // FunctionPassManager implementation
1359 
1360 /// Create new Function pass manager
1362  FPM = new FunctionPassManagerImpl();
1363  // FPM is the top level manager.
1364  FPM->setTopLevelManager(FPM);
1365 
1366  AnalysisResolver *AR = new AnalysisResolver(*FPM);
1367  FPM->setResolver(AR);
1368 }
1369 
1371  delete FPM;
1372 }
1373 
1375  FPM->add(P);
1376 }
1377 
1378 /// run - Execute all of the passes scheduled for execution. Keep
1379 /// track of whether any of the passes modifies the function, and if
1380 /// so, return true.
1381 ///
1383  handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1384  report_fatal_error("Error reading bitcode file: " + EIB.message());
1385  });
1386  return FPM->run(F);
1387 }
1388 
1389 
1390 /// doInitialization - Run all of the initializers for the function passes.
1391 ///
1393  return FPM->doInitialization(*M);
1394 }
1395 
1396 /// doFinalization - Run all of the finalizers for the function passes.
1397 ///
1399  return FPM->doFinalization(*M);
1400 }
1401 
1402 //===----------------------------------------------------------------------===//
1403 // FunctionPassManagerImpl implementation
1404 //
1406  bool Changed = false;
1407 
1408  dumpArguments();
1409  dumpPasses();
1410 
1411  for (ImmutablePass *ImPass : getImmutablePasses())
1412  Changed |= ImPass->doInitialization(M);
1413 
1414  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1415  Changed |= getContainedManager(Index)->doInitialization(M);
1416 
1417  return Changed;
1418 }
1419 
1421  bool Changed = false;
1422 
1423  for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1424  Changed |= getContainedManager(Index)->doFinalization(M);
1425 
1426  for (ImmutablePass *ImPass : getImmutablePasses())
1427  Changed |= ImPass->doFinalization(M);
1428 
1429  return Changed;
1430 }
1431 
1432 /// cleanup - After running all passes, clean up pass manager cache.
1434  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1435  FunctionPass *FP = getContainedPass(Index);
1436  AnalysisResolver *AR = FP->getResolver();
1437  assert(AR && "Analysis Resolver is not set");
1438  AR->clearAnalysisImpls();
1439  }
1440 }
1441 
1443  if (!wasRun)
1444  return;
1445  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1446  FPPassManager *FPPM = getContainedManager(Index);
1447  for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1448  FPPM->getContainedPass(Index)->releaseMemory();
1449  }
1450  }
1451  wasRun = false;
1452 }
1453 
1454 // Execute all the passes managed by this top level manager.
1455 // Return true if any function is modified by a pass.
1457  bool Changed = false;
1458  TimingInfo::createTheTimeInfo();
1459 
1461  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1462  Changed |= getContainedManager(Index)->runOnFunction(F);
1463  F.getContext().yield();
1464  }
1465 
1466  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1467  getContainedManager(Index)->cleanup();
1468 
1469  wasRun = true;
1470  return Changed;
1471 }
1472 
1473 //===----------------------------------------------------------------------===//
1474 // FPPassManager implementation
1475 
1476 char FPPassManager::ID = 0;
1477 /// Print passes managed by this manager
1478 void FPPassManager::dumpPassStructure(unsigned Offset) {
1479  dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1480  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1481  FunctionPass *FP = getContainedPass(Index);
1482  FP->dumpPassStructure(Offset + 1);
1483  dumpLastUses(FP, Offset+1);
1484  }
1485 }
1486 
1487 
1488 /// Execute all of the passes scheduled for execution by invoking
1489 /// runOnFunction method. Keep track of whether any of the passes modifies
1490 /// the function, and if so, return true.
1492  if (F.isDeclaration())
1493  return false;
1494 
1495  bool Changed = false;
1496 
1497  // Collect inherited analysis from Module level pass manager.
1498  populateInheritedAnalysis(TPM->activeStack);
1499 
1500  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1501  FunctionPass *FP = getContainedPass(Index);
1502  bool LocalChanged = false;
1503 
1504  dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1505  dumpRequiredSet(FP);
1506 
1507  initializeAnalysisImpl(FP);
1508 
1509  {
1511  TimeRegion PassTimer(getPassTimer(FP));
1512 
1513  LocalChanged |= FP->runOnFunction(F);
1514  }
1515 
1516  Changed |= LocalChanged;
1517  if (LocalChanged)
1518  dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1519  dumpPreservedSet(FP);
1520  dumpUsedSet(FP);
1521 
1522  verifyPreservedAnalysis(FP);
1523  removeNotPreservedAnalysis(FP);
1524  recordAvailableAnalysis(FP);
1525  removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1526  }
1527  return Changed;
1528 }
1529 
1531  bool Changed = false;
1532 
1533  for (Function &F : M)
1534  Changed |= runOnFunction(F);
1535 
1536  return Changed;
1537 }
1538 
1540  bool Changed = false;
1541 
1542  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1543  Changed |= getContainedPass(Index)->doInitialization(M);
1544 
1545  return Changed;
1546 }
1547 
1549  bool Changed = false;
1550 
1551  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1552  Changed |= getContainedPass(Index)->doFinalization(M);
1553 
1554  return Changed;
1555 }
1556 
1557 //===----------------------------------------------------------------------===//
1558 // MPPassManager implementation
1559 
1560 /// Execute all of the passes scheduled for execution by invoking
1561 /// runOnModule method. Keep track of whether any of the passes modifies
1562 /// the module, and if so, return true.
1563 bool
1564 MPPassManager::runOnModule(Module &M) {
1565  bool Changed = false;
1566 
1567  // Initialize on-the-fly passes
1568  for (auto &OnTheFlyManager : OnTheFlyManagers) {
1569  FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1570  Changed |= FPP->doInitialization(M);
1571  }
1572 
1573  // Initialize module passes
1574  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1575  Changed |= getContainedPass(Index)->doInitialization(M);
1576 
1577  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1578  ModulePass *MP = getContainedPass(Index);
1579  bool LocalChanged = false;
1580 
1581  dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1582  dumpRequiredSet(MP);
1583 
1584  initializeAnalysisImpl(MP);
1585 
1586  {
1588  TimeRegion PassTimer(getPassTimer(MP));
1589 
1590  LocalChanged |= MP->runOnModule(M);
1591  }
1592 
1593  Changed |= LocalChanged;
1594  if (LocalChanged)
1595  dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1596  M.getModuleIdentifier());
1597  dumpPreservedSet(MP);
1598  dumpUsedSet(MP);
1599 
1600  verifyPreservedAnalysis(MP);
1601  removeNotPreservedAnalysis(MP);
1602  recordAvailableAnalysis(MP);
1603  removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1604  }
1605 
1606  // Finalize module passes
1607  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1608  Changed |= getContainedPass(Index)->doFinalization(M);
1609 
1610  // Finalize on-the-fly passes
1611  for (auto &OnTheFlyManager : OnTheFlyManagers) {
1612  FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1613  // We don't know when is the last time an on-the-fly pass is run,
1614  // so we need to releaseMemory / finalize here
1615  FPP->releaseMemoryOnTheFly();
1616  Changed |= FPP->doFinalization(M);
1617  }
1618 
1619  return Changed;
1620 }
1621 
1622 /// Add RequiredPass into list of lower level passes required by pass P.
1623 /// RequiredPass is run on the fly by Pass Manager when P requests it
1624 /// through getAnalysis interface.
1625 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1627  "Unable to handle Pass that requires lower level Analysis pass");
1629  RequiredPass->getPotentialPassManagerType()) &&
1630  "Unable to handle Pass that requires lower level Analysis pass");
1631  if (!RequiredPass)
1632  return;
1633 
1634  FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1635  if (!FPP) {
1636  FPP = new FunctionPassManagerImpl();
1637  // FPP is the top level manager.
1638  FPP->setTopLevelManager(FPP);
1639 
1640  OnTheFlyManagers[P] = FPP;
1641  }
1642  const PassInfo *RequiredPassPI =
1643  TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1644 
1645  Pass *FoundPass = nullptr;
1646  if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1647  FoundPass =
1648  ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1649  }
1650  if (!FoundPass) {
1651  FoundPass = RequiredPass;
1652  // This should be guaranteed to add RequiredPass to the passmanager given
1653  // that we checked for an available analysis above.
1654  FPP->add(RequiredPass);
1655  }
1656  // Register P as the last user of FoundPass or RequiredPass.
1658  LU.push_back(FoundPass);
1659  FPP->setLastUser(LU, P);
1660 }
1661 
1662 /// Return function pass corresponding to PassInfo PI, that is
1663 /// required by module pass MP. Instantiate analysis pass, by using
1664 /// its runOnFunction() for function F.
1665 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1666  FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1667  assert(FPP && "Unable to find on the fly pass");
1668 
1669  FPP->releaseMemoryOnTheFly();
1670  FPP->run(F);
1671  return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1672 }
1673 
1674 
1675 //===----------------------------------------------------------------------===//
1676 // PassManagerImpl implementation
1677 
1678 //
1679 /// run - Execute all of the passes scheduled for execution. Keep track of
1680 /// whether any of the passes modifies the module, and if so, return true.
1682  bool Changed = false;
1683  TimingInfo::createTheTimeInfo();
1684 
1685  dumpArguments();
1686  dumpPasses();
1687 
1688  for (ImmutablePass *ImPass : getImmutablePasses())
1689  Changed |= ImPass->doInitialization(M);
1690 
1692  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1693  Changed |= getContainedManager(Index)->runOnModule(M);
1694  M.getContext().yield();
1695  }
1696 
1697  for (ImmutablePass *ImPass : getImmutablePasses())
1698  Changed |= ImPass->doFinalization(M);
1699 
1700  return Changed;
1701 }
1702 
1703 //===----------------------------------------------------------------------===//
1704 // PassManager implementation
1705 
1706 /// Create new pass manager
1708  PM = new PassManagerImpl();
1709  // PM is the top level manager
1710  PM->setTopLevelManager(PM);
1711 }
1712 
1714  delete PM;
1715 }
1716 
1718  PM->add(P);
1719 }
1720 
1721 /// run - Execute all of the passes scheduled for execution. Keep track of
1722 /// whether any of the passes modifies the module, and if so, return true.
1724  return PM->run(M);
1725 }
1726 
1727 //===----------------------------------------------------------------------===//
1728 // TimingInfo implementation
1729 
1730 bool llvm::TimePassesIsEnabled = false;
1731 static cl::opt<bool,true>
1733  cl::desc("Time each pass, printing elapsed time for each on exit"));
1734 
1735 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1736 // a non-null value (if the -time-passes option is enabled) or it leaves it
1737 // null. It may be called multiple times.
1738 void TimingInfo::createTheTimeInfo() {
1739  if (!TimePassesIsEnabled || TheTimeInfo) return;
1740 
1741  // Constructed the first time this is called, iff -time-passes is enabled.
1742  // This guarantees that the object will be constructed before static globals,
1743  // thus it will be destroyed before them.
1744  static ManagedStatic<TimingInfo> TTI;
1745  TheTimeInfo = &*TTI;
1746 }
1747 
1748 /// If TimingInfo is enabled then start pass timer.
1750  if (TheTimeInfo)
1751  return TheTimeInfo->getPassTimer(P);
1752  return nullptr;
1753 }
1754 
1755 //===----------------------------------------------------------------------===//
1756 // PMStack implementation
1757 //
1758 
1759 // Pop Pass Manager from the stack and clear its analysis info.
1761 
1762  PMDataManager *Top = this->top();
1763  Top->initializeAnalysisInfo();
1764 
1765  S.pop_back();
1766 }
1767 
1768 // Push PM on the stack and set its top level manager.
1770  assert(PM && "Unable to push. Pass Manager expected");
1771  assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1772 
1773  if (!this->empty()) {
1774  assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1775  && "pushing bad pass manager to PMStack");
1776  PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1777 
1778  assert(TPM && "Unable to find top level manager");
1779  TPM->addIndirectPassManager(PM);
1780  PM->setTopLevelManager(TPM);
1781  PM->setDepth(this->top()->getDepth()+1);
1782  } else {
1785  && "pushing bad pass manager to PMStack");
1786  PM->setDepth(1);
1787  }
1788 
1789  S.push_back(PM);
1790 }
1791 
1792 // Dump content of the pass manager stack.
1794  for (PMDataManager *Manager : S)
1795  dbgs() << Manager->getAsPass()->getPassName() << ' ';
1796 
1797  if (!S.empty())
1798  dbgs() << '\n';
1799 }
1800 
1801 /// Find appropriate Module Pass Manager in the PM Stack and
1802 /// add self into that manager.
1804  PassManagerType PreferredType) {
1805  // Find Module Pass Manager
1806  while (!PMS.empty()) {
1807  PassManagerType TopPMType = PMS.top()->getPassManagerType();
1808  if (TopPMType == PreferredType)
1809  break; // We found desired pass manager
1810  else if (TopPMType > PMT_ModulePassManager)
1811  PMS.pop(); // Pop children pass managers
1812  else
1813  break;
1814  }
1815  assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1816  PMS.top()->add(this);
1817 }
1818 
1819 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1820 /// in the PM Stack and add self into that manager.
1822  PassManagerType PreferredType) {
1823 
1824  // Find Function Pass Manager
1825  while (!PMS.empty()) {
1827  PMS.pop();
1828  else
1829  break;
1830  }
1831 
1832  // Create new Function Pass Manager if needed.
1833  FPPassManager *FPP;
1835  FPP = (FPPassManager *)PMS.top();
1836  } else {
1837  assert(!PMS.empty() && "Unable to create Function Pass Manager");
1838  PMDataManager *PMD = PMS.top();
1839 
1840  // [1] Create new Function Pass Manager
1841  FPP = new FPPassManager();
1842  FPP->populateInheritedAnalysis(PMS);
1843 
1844  // [2] Set up new manager's top level manager
1845  PMTopLevelManager *TPM = PMD->getTopLevelManager();
1846  TPM->addIndirectPassManager(FPP);
1847 
1848  // [3] Assign manager to manage this new manager. This may create
1849  // and push new managers into PMS
1850  FPP->assignPassManager(PMS, PMD->getPassManagerType());
1851 
1852  // [4] Push new manager into PMS
1853  PMS.push(FPP);
1854  }
1855 
1856  // Assign FPP as the manager of this pass.
1857  FPP->add(this);
1858 }
1859 
1860 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1861 /// in the PM Stack and add self into that manager.
1863  PassManagerType PreferredType) {
1864  BBPassManager *BBP;
1865 
1866  // Basic Pass Manager is a leaf pass manager. It does not handle
1867  // any other pass manager.
1868  if (!PMS.empty() &&
1870  BBP = (BBPassManager *)PMS.top();
1871  } else {
1872  // If leaf manager is not Basic Block Pass manager then create new
1873  // basic Block Pass manager.
1874  assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1875  PMDataManager *PMD = PMS.top();
1876 
1877  // [1] Create new Basic Block Manager
1878  BBP = new BBPassManager();
1879 
1880  // [2] Set up new manager's top level manager
1881  // Basic Block Pass Manager does not live by itself
1882  PMTopLevelManager *TPM = PMD->getTopLevelManager();
1883  TPM->addIndirectPassManager(BBP);
1884 
1885  // [3] Assign manager to manage this new manager. This may create
1886  // and push new managers into PMS
1887  BBP->assignPassManager(PMS, PreferredType);
1888 
1889  // [4] Push new manager into PMS
1890  PMS.push(BBP);
1891  }
1892 
1893  // Assign BBP as the manager of this pass.
1894  BBP->add(this);
1895 }
1896 
MachineLoop * L
PMTopLevelManager * TPM
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:81
bool preserveHigherLevelAnalysis(Pass *P)
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:241
PassManagerType
Different types of internal pass managers.
Definition: Pass.h:54
static TimingInfo * TheTimeInfo
BBPassManager.
Definition: Pass.h:61
virtual Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const =0
createPrinterPass - Get a Pass appropriate to print the IR this pass operates on (Module, Function or MachineFunction).
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:226
Pass * findAnalysisPass(AnalysisID AID, bool Direction)
Find the pass that implements Analysis AID.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
size_t i
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:450
static cl::opt< bool, true > EnableTiming("time-passes", cl::location(TimePassesIsEnabled), cl::desc("Time each pass, printing elapsed time for each on exit"))
virtual PMDataManager * getAsPMDataManager()
Definition: Pass.cpp:104
void dumpLastUses(Pass *P, unsigned Offset) const
virtual void dumpPassStructure(unsigned Offset=0)
Definition: Pass.cpp:59
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
const std::vector< const PassInfo * > & getInterfacesImplemented() const
getInterfacesImplemented - Return a list of all of the analysis group interfaces implemented by this ...
Definition: PassInfo.h:134
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
FunctionPassManagerImpl manages FPPassManagers.
bool doInitialization(Module &M) override
doInitialization - Run all of the initializers for the function passes.
AnalysisID getPassID() const
getPassID - Return the PassID number that corresponds to this pass.
Definition: Pass.h:103
virtual void releaseMemory()
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: Pass.cpp:88
void dump() const
iterator end()
Definition: Function.h:537
void assignPassManager(PMStack &PMS, PassManagerType T) override
Find appropriate Function Pass Manager or Call Graph Pass Manager in the PM Stack and add self into t...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:84
FunctionPass * createPrintFunctionPass(raw_ostream &OS, const std::string &Banner="")
Create and return a pass that prints functions to the specified raw_ostream as they are processed...
unsigned getNumContainedManagers() const
virtual bool doInitialization(Function &)
doInitialization - Virtual method overridden by BasicBlockPass subclasses to do any necessary per-fun...
Definition: Pass.cpp:170
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
static cl::list< std::string > PrintFuncsList("filter-print-funcs", cl::value_desc("function names"), cl::desc("Only print IR for functions whose name ""match this for all print-[before|after][-all] ""options"), cl::CommaSeparated)
static sys::Mutex Lock
PMDataManager * getAsPMDataManager() override
static PassOptionList PrintBefore("print-before", llvm::cl::desc("Print IR before specified passes"), cl::Hidden)
static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI, PassOptionList &PassesToPrint)
This is a helper to determine whether to print IR before or after a pass.
const VectorType & getPreservedSet() const
const_iterator begin(StringRef path)
Get begin iterator over path.
Definition: Path.cpp:233
void dumpRequiredSet(const Pass *P) const
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:67
void yield()
Calls the yield callback (if applicable).
PMTopLevelManager(PMDataManager *PMDM)
Initialize top level manager. Create first pass manager.
void dumpUsedSet(const Pass *P) const
virtual void preparePassManager(PMStack &)
Check if available pass managers are suitable for this pass or not.
Definition: Pass.cpp:75
Base class for error info classes.
Definition: Support/Error.h:46
void dumpPassInfo(Pass *P, enum PassDebuggingString S1, enum PassDebuggingString S2, StringRef Msg)
virtual void initializePass()
initializePass - This method may be overriden by immutable passes to allow them to perform various in...
Definition: Pass.cpp:132
virtual PassManagerType getPassManagerType() const
bool isAnalysis() const
Definition: PassInfo.h:87
void setResolver(AnalysisResolver *AR)
Definition: Pass.cpp:108
Pass * createPass() const
createPass() - Use this method to create an instance of this pass.
Definition: PassInfo.h:115
DenseMap< AnalysisID, Pass * > * InheritedAnalysis[PMT_Last]
PMTopLevelManager manages LastUser info and collects common APIs used by top level pass managers...
Timer * getPassTimer(Pass *)
If TimingInfo is enabled then start pass timer.
void setDepth(unsigned newDepth)
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
bool doFinalization(Module &M) override
doFinalization - Run all of the finalizers for the function passes.
The TimeRegion class is used as a helper class to call the startTimer() and stopTimer() methods of th...
Definition: Timer.h:140
void schedulePass(Pass *P)
Schedule pass P for execution.
void add(Pass *P) override
Add a pass to the queue of passes to run.
void freePass(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove P.
void dumpPassStructure(unsigned Offset) override
Print passes managed by this manager.
bool isPassDebuggingExecutionsOrMore() const
isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions or higher is specified...
virtual ~PMTopLevelManager()
Destructor.
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Definition: Pass.h:115
void verifyPreservedAnalysis(Pass *P)
verifyPreservedAnalysis – Verify analysis presreved by pass P.
void initializeAnalysisInfo()
Initialize available analysis information.
MPPassManager.
Definition: Pass.h:56
virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass)
Add RequiredPass into list of lower level passes required by pass P.
void populateInheritedAnalysis(PMStack &PMS)
FPPassManager manages BBPassManagers and FunctionPasses.
PMStack - This class implements a stack data structure of PMDataManager pointers. ...
void initializeAnalysisImpl(Pass *P)
All Required analyses should be available to the pass as it runs! Here we fill in the AnalysisImpls m...
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:193
#define clEnumVal(ENUMVAL, DESC)
Definition: CommandLine.h:588
PassManagerPrettyStackEntry - This is used to print informative information about what pass is runnin...
unsigned getDepth() const
void assignPassManager(PMStack &PMS, PassManagerType T) override
Find appropriate Module Pass Manager in the PM Stack and add self into that manager.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
#define F(x, y, z)
Definition: MD5.cpp:51
This class is used to track the amount of time spent between invocations of its startTimer()/stopTime...
Definition: Timer.h:76
PassManagerType getTopLevelPassManagerType() override
Pass * getAnalysisIfAvailable(AnalysisID ID, bool Direction) const
Return analysis result or null if it doesn't exist.
#define T
void add(Pass *P, bool ProcessAnalysis=true)
Add pass P into the PassVector.
StringRef getPassArgument() const
getPassArgument - Return the command line option that may be passed to 'opt' that will cause this pas...
Definition: PassInfo.h:74
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Function Alias Analysis false
unsigned getNumContainedPasses() const
PassManagerType getTopLevelPassManagerType() override
void add(Pass *P) override
Add a pass to the queue of passes to run.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
virtual Pass * getAsPass()=0
bool doFinalization(Module &M) override
doFinalization - Run all of the finalizers for the function passes.
virtual bool doFinalization(Function &)
doFinalization - Virtual method overriden by BasicBlockPass subclasses to do any post processing need...
Definition: Pass.cpp:175
iterator begin()
Definition: Function.h:535
bool run(Function &F)
run - Execute all of the passes scheduled for execution.
virtual ImmutablePass * getAsImmutablePass()
Definition: Pass.cpp:100
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition: Pass.h:110
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:615
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition: FoldingSet.h:316
static PassOptionList PrintAfter("print-after", llvm::cl::desc("Print IR after specified passes"), cl::Hidden)
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
void assignPassManager(PMStack &PMS, PassManagerType T) override
Find appropriate Basic Pass Manager or Call Graph Pass Manager in the PM Stack and add self into that...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
FPPassManager * getContainedManager(unsigned N)
void dumpPreservedSet(const Pass *P) const
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
const VectorType & getRequiredTransitiveSet() const
void addIndirectPassManager(PMDataManager *Manager)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:368
void collectLastUses(SmallVectorImpl< Pass * > &LastUses, Pass *P)
Collect passes whose last user is P.
AnalysisResolver * getResolver() const
Definition: Pass.h:144
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
Represent the analysis usage information of a pass.
uint32_t Offset
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
PassManagerImpl manages MPPassManagers.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
static cl::opt< bool > PrintBeforeAll("print-before-all", llvm::cl::desc("Print IR before each pass"), cl::init(false))
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
void getAnalysisUsage(AnalysisUsage &Info) const override
Pass Manager itself does not invalidate any analysis info.
SmallVectorImpl< ImmutablePass * > & getImmutablePasses()
const VectorType & getUsedSet() const
Error materialize()
Make sure this GlobalValue is fully read.
Definition: Globals.cpp:50
PassInfo class - An instance of this class exists for every pass known by the system, and can be obtained from a live Pass by calling its getPassInfo() method.
Definition: PassInfo.h:32
bool doInitialization(Module &M) override
doInitialization - Run all of the initializers for the function passes.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BasicBlockPass class - This class is used to implement most local optimizations.
Definition: Pass.h:335
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
void getAnalysisUsage(AnalysisUsage &Info) const override
Pass Manager itself does not invalidate any analysis info.
void addImmutablePass(ImmutablePass *P)
Add immutable pass and initialize it.
void setLastUser(ArrayRef< Pass * > AnalysisPasses, Pass *P)
Set pass P as the last user of the given analysis passes.
static bool ShouldPrintBeforePass(const PassInfo *PI)
This is a utility to check whether a pass should have IR dumped before it.
Iterator for intrusive lists based on ilist_node.
bool empty() const
void collectRequiredAndUsedAnalyses(SmallVectorImpl< Pass * > &UsedPasses, SmallVectorImpl< AnalysisID > &ReqPassNotAvailable, Pass *P)
Populate UsedPasses with analysis pass that are used or required by pass P and are available...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:425
static bool ShouldPrintAfterPass(const PassInfo *PI)
This is a utility to check whether a pass should have IR dumped after it.
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:266
void recordAvailableAnalysis(Pass *P)
Augment AvailableAnalysis by adding analysis made available by pass P.
FPPassManager.
Definition: Pass.h:58
bool getPreservesAll() const
Determine whether a pass said it does not transform its input at all.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
void removeNotPreservedAnalysis(Pass *P)
Remove Analysis that is not preserved by the pass.
Module.h This file contains the declarations for the Module class.
PMDataManager * getAsPMDataManager() override
void addAnalysisImplsPair(AnalysisID PI, Pass *P)
bool runOnFunction(Function &F)
run - Execute all of the passes scheduled for execution.
bool doFinalization()
doFinalization - Run all of the finalizers for the function passes.
void removeDeadPasses(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove dead passes used by P.
virtual Pass * getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F)
bool isFunctionInPrintList(StringRef FunctionName)
isFunctionInPrintList - returns true if a function should be printed via
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
SmallVector< Pass *, 16 > PassVector
PMDataManager * top() const
void clearAnalysisImpls()
Clear cache that is used to connect a pass to the the analysis (PassInfo).
Pass * findImplPass(AnalysisID PI)
Find pass that is implementing PI.
void setPreservesAll()
Set by analyses that do not transform their input at all.
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
Definition: PassManager.h:477
AnalysisUsage * findAnalysisUsage(Pass *P)
Find analysis usage information for the pass P.
void add(Pass *P)
Add a pass to the queue of passes to run.
const PassInfo * findAnalysisPassInfo(AnalysisID AID) const
Retrieve the PassInfo for an analysis.
void setTopLevelManager(PMTopLevelManager *T)
SmallVector< PMDataManager *, 8 > PassManagers
Collection of pass managers.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
const VectorType & getRequiredSet() const
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:389
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:188
PMDataManager & getPMDataManager()
FunctionPass * getContainedPass(unsigned N)
void cleanup()
cleanup - After running all passes, clean up pass manager cache.
static cl::opt< bool > PrintAfterAll("print-after-all", llvm::cl::desc("Print IR after each pass"), cl::init(false))
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
The TimerGroup class is used to group together related timers into a single report that is printed wh...
Definition: Timer.h:170
PassDebugLevel
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
StringRef getPassName() const
getPassName - Return the friendly name for the pass, never returns null
Definition: PassInfo.h:68
iterator find(const KeyT &Val)
Definition: DenseMap.h:127
const void * AnalysisID
Definition: Pass.h:46
void push(PMDataManager *PM)
PMDataManager provides the common place to manage the analysis data used by pass managers.
ModulePass * createPrintModulePass(raw_ostream &OS, const std::string &Banner="", bool ShouldPreserveUseListOrder=false)
Create and return a pass that writes the module to the specified raw_ostream.
const PassInfo * getPassInfo(const void *TI) const
getPassInfo - Look up a pass' corresponding PassInfo, indexed by the pass' type identifier (&MyPass::...
This file defines passes to print out IR in various granularities.
Pass * findAnalysisPass(AnalysisID AID)
Find the pass that implements Analysis AID.
void add(Pass *P)
Add a pass to the queue of passes to run.
static cl::opt< enum PassDebugLevel > PassDebugging("debug-pass", cl::Hidden, cl::desc("Print PassManager debugging information"), cl::values(clEnumVal(Disabled,"disable debug output"), clEnumVal(Arguments,"print pass arguments to pass to 'opt'"), clEnumVal(Structure,"print pass structure before run()"), clEnumVal(Executions,"print pass name before it is executed"), clEnumVal(Details,"print pass details when it is executed")))
void dumpPassArguments() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool run(Function &F)
run - Execute all of the passes scheduled for execution.
MPPassManager * getContainedManager(unsigned N)
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
virtual bool runOnBasicBlock(BasicBlock &BB)=0
runOnBasicBlock - Virtual method overriden by subclasses to do the per-basicblock processing of the p...
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
bool doInitialization()
doInitialization - Run all of the initializers for the function passes.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const override
createPrinterPass - Get a module printer pass.
PassManager()
Create new pass manager.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:63
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: IRReader.cpp:26
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:411
Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const override
createPrinterPass - Get a function printer pass.
virtual PassManagerType getPotentialPassManagerType() const
Return what kind of Pass Manager can manage this pass.
Definition: Pass.cpp:79
virtual void assignPassManager(PMStack &, PassManagerType)
Each pass is responsible for assigning a pass manager to itself.
Definition: Pass.h:134
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:222
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:783