LLVM  9.0.0svn
LegacyPassManager.cpp
Go to the documentation of this file.
1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the legacy LLVM Pass Manager infrastructure.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/ADT/MapVector.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/IR/DiagnosticInfo.h"
18 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/PassTimingInfo.h"
23 #include "llvm/Support/Chrono.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Error.h"
29 #include "llvm/Support/Mutex.h"
30 #include "llvm/Support/Timer.h"
32 #include <algorithm>
33 #include <unordered_set>
34 using namespace llvm;
35 using namespace llvm::legacy;
36 
37 // See PassManagers.h for Pass Manager infrastructure overview.
38 
39 //===----------------------------------------------------------------------===//
40 // Pass debugging information. Often it is useful to find out what pass is
41 // running when a crash occurs in a utility. When this library is compiled with
42 // debugging on, a command line option (--debug-pass) is enabled that causes the
43 // pass name to be printed before it executes.
44 //
45 
46 namespace {
47 // Different debug levels that can be enabled...
49  Disabled, Arguments, Structure, Executions, Details
50 };
51 }
52 
54 PassDebugging("debug-pass", cl::Hidden,
55  cl::desc("Print PassManager debugging information"),
56  cl::values(
57  clEnumVal(Disabled , "disable debug output"),
58  clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
59  clEnumVal(Structure , "print pass structure before run()"),
60  clEnumVal(Executions, "print pass name before it is executed"),
61  clEnumVal(Details , "print pass details when it is executed")));
62 
63 namespace {
65 PassOptionList;
66 }
67 
68 // Print IR out before/after specified passes.
69 static PassOptionList
70 PrintBefore("print-before",
71  llvm::cl::desc("Print IR before specified passes"),
72  cl::Hidden);
73 
74 static PassOptionList
75 PrintAfter("print-after",
76  llvm::cl::desc("Print IR after specified passes"),
77  cl::Hidden);
78 
79 static cl::opt<bool> PrintBeforeAll("print-before-all",
80  llvm::cl::desc("Print IR before each pass"),
81  cl::init(false), cl::Hidden);
82 static cl::opt<bool> PrintAfterAll("print-after-all",
83  llvm::cl::desc("Print IR after each pass"),
84  cl::init(false), cl::Hidden);
85 
86 static cl::opt<bool>
87  PrintModuleScope("print-module-scope",
88  cl::desc("When printing IR for print-[before|after]{-all} "
89  "always print a module IR"),
90  cl::init(false), cl::Hidden);
91 
93  PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
94  cl::desc("Only print IR for functions whose name "
95  "match this for all print-[before|after][-all] "
96  "options"),
98 
99 /// This is a helper to determine whether to print IR before or
100 /// after a pass.
101 
103  return PrintBeforeAll || !PrintBefore.empty();
104 }
105 
107  return PrintAfterAll || !PrintAfter.empty();
108 }
109 
111  PassOptionList &PassesToPrint) {
112  for (auto *PassInf : PassesToPrint) {
113  if (PassInf)
114  if (PassInf->getPassArgument() == PassID) {
115  return true;
116  }
117  }
118  return false;
119 }
120 
122  return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
123 }
124 
126  return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
127 }
128 
130 
132  static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
133  PrintFuncsList.end());
134  return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
135 }
136 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
137 /// or higher is specified.
139  return PassDebugging >= Executions;
140 }
141 
143  Module &M, StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount) {
144  // Only calculate getInstructionCount if the size-info remark is requested.
145  unsigned InstrCount = 0;
146 
147  // Collect instruction counts for every function. We'll use this to emit
148  // per-function size remarks later.
149  for (Function &F : M) {
150  unsigned FCount = F.getInstructionCount();
151 
152  // Insert a record into FunctionToInstrCount keeping track of the current
153  // size of the function as the first member of a pair. Set the second
154  // member to 0; if the function is deleted by the pass, then when we get
155  // here, we'll be able to let the user know that F no longer contributes to
156  // the module.
157  FunctionToInstrCount[F.getName().str()] =
158  std::pair<unsigned, unsigned>(FCount, 0);
159  InstrCount += FCount;
160  }
161  return InstrCount;
162 }
163 
165  Pass *P, Module &M, int64_t Delta, unsigned CountBefore,
166  StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,
167  Function *F) {
168  // If it's a pass manager, don't emit a remark. (This hinges on the assumption
169  // that the only passes that return non-null with getAsPMDataManager are pass
170  // managers.) The reason we have to do this is to avoid emitting remarks for
171  // CGSCC passes.
172  if (P->getAsPMDataManager())
173  return;
174 
175  // Set to true if this isn't a module pass or CGSCC pass.
176  bool CouldOnlyImpactOneFunction = (F != nullptr);
177 
178  // Helper lambda that updates the changes to the size of some function.
179  auto UpdateFunctionChanges =
180  [&FunctionToInstrCount](Function &MaybeChangedFn) {
181  // Update the total module count.
182  unsigned FnSize = MaybeChangedFn.getInstructionCount();
183  auto It = FunctionToInstrCount.find(MaybeChangedFn.getName());
184 
185  // If we created a new function, then we need to add it to the map and
186  // say that it changed from 0 instructions to FnSize.
187  if (It == FunctionToInstrCount.end()) {
188  FunctionToInstrCount[MaybeChangedFn.getName()] =
189  std::pair<unsigned, unsigned>(0, FnSize);
190  return;
191  }
192  // Insert the new function size into the second member of the pair. This
193  // tells us whether or not this function changed in size.
194  It->second.second = FnSize;
195  };
196 
197  // We need to initially update all of the function sizes.
198  // If no function was passed in, then we're either a module pass or an
199  // CGSCC pass.
200  if (!CouldOnlyImpactOneFunction)
201  std::for_each(M.begin(), M.end(), UpdateFunctionChanges);
202  else
203  UpdateFunctionChanges(*F);
204 
205  // Do we have a function we can use to emit a remark?
206  if (!CouldOnlyImpactOneFunction) {
207  // We need a function containing at least one basic block in order to output
208  // remarks. Since it's possible that the first function in the module
209  // doesn't actually contain a basic block, we have to go and find one that's
210  // suitable for emitting remarks.
211  auto It = std::find_if(M.begin(), M.end(),
212  [](const Function &Fn) { return !Fn.empty(); });
213 
214  // Didn't find a function. Quit.
215  if (It == M.end())
216  return;
217 
218  // We found a function containing at least one basic block.
219  F = &*It;
220  }
221  int64_t CountAfter = static_cast<int64_t>(CountBefore) + Delta;
222  BasicBlock &BB = *F->begin();
223  OptimizationRemarkAnalysis R("size-info", "IRSizeChange",
224  DiagnosticLocation(), &BB);
225  // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
226  // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
228  << ": IR instruction count changed from "
229  << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)
230  << " to "
231  << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)
232  << "; Delta: "
233  << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);
234  F->getContext().diagnose(R); // Not using ORE for layering reasons.
235 
236  // Emit per-function size change remarks separately.
237  std::string PassName = P->getPassName().str();
238 
239  // Helper lambda that emits a remark when the size of a function has changed.
240  auto EmitFunctionSizeChangedRemark = [&FunctionToInstrCount, &F, &BB,
241  &PassName](const std::string &Fname) {
242  unsigned FnCountBefore, FnCountAfter;
243  std::pair<unsigned, unsigned> &Change = FunctionToInstrCount[Fname];
244  std::tie(FnCountBefore, FnCountAfter) = Change;
245  int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
246  static_cast<int64_t>(FnCountBefore);
247 
248  if (FnDelta == 0)
249  return;
250 
251  // FIXME: We shouldn't use BB for the location here. Unfortunately, because
252  // the function that we're looking at could have been deleted, we can't use
253  // it for the source location. We *want* remarks when a function is deleted
254  // though, so we're kind of stuck here as is. (This remark, along with the
255  // whole-module size change remarks really ought not to have source
256  // locations at all.)
257  OptimizationRemarkAnalysis FR("size-info", "FunctionIRSizeChange",
258  DiagnosticLocation(), &BB);
259  FR << DiagnosticInfoOptimizationBase::Argument("Pass", PassName)
260  << ": Function: "
261  << DiagnosticInfoOptimizationBase::Argument("Function", Fname)
262  << ": IR instruction count changed from "
263  << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore",
264  FnCountBefore)
265  << " to "
266  << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter",
267  FnCountAfter)
268  << "; Delta: "
269  << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta);
270  F->getContext().diagnose(FR);
271 
272  // Update the function size.
273  Change.first = FnCountAfter;
274  };
275 
276  // Are we looking at more than one function? If so, emit remarks for all of
277  // the functions in the module. Otherwise, only emit one remark.
278  if (!CouldOnlyImpactOneFunction)
279  std::for_each(FunctionToInstrCount.keys().begin(),
280  FunctionToInstrCount.keys().end(),
281  EmitFunctionSizeChangedRemark);
282  else
283  EmitFunctionSizeChangedRemark(F->getName().str());
284 }
285 
287  if (!V && !M)
288  OS << "Releasing pass '";
289  else
290  OS << "Running pass '";
291 
292  OS << P->getPassName() << "'";
293 
294  if (M) {
295  OS << " on module '" << M->getModuleIdentifier() << "'.\n";
296  return;
297  }
298  if (!V) {
299  OS << '\n';
300  return;
301  }
302 
303  OS << " on ";
304  if (isa<Function>(V))
305  OS << "function";
306  else if (isa<BasicBlock>(V))
307  OS << "basic block";
308  else
309  OS << "value";
310 
311  OS << " '";
312  V->printAsOperand(OS, /*PrintTy=*/false, M);
313  OS << "'\n";
314 }
315 
316 
317 namespace {
318 //===----------------------------------------------------------------------===//
319 // BBPassManager
320 //
321 /// BBPassManager manages BasicBlockPass. It batches all the
322 /// pass together and sequence them to process one basic block before
323 /// processing next basic block.
324 class BBPassManager : public PMDataManager, public FunctionPass {
325 
326 public:
327  static char ID;
328  explicit BBPassManager()
329  : PMDataManager(), FunctionPass(ID) {}
330 
331  /// Execute all of the passes scheduled for execution. Keep track of
332  /// whether any of the passes modifies the function, and if so, return true.
333  bool runOnFunction(Function &F) override;
334 
335  /// Pass Manager itself does not invalidate any analysis info.
336  void getAnalysisUsage(AnalysisUsage &Info) const override {
337  Info.setPreservesAll();
338  }
339 
340  bool doInitialization(Module &M) override;
341  bool doInitialization(Function &F);
342  bool doFinalization(Module &M) override;
343  bool doFinalization(Function &F);
344 
345  PMDataManager *getAsPMDataManager() override { return this; }
346  Pass *getAsPass() override { return this; }
347 
348  StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
349 
350  // Print passes managed by this manager
351  void dumpPassStructure(unsigned Offset) override {
352  dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
353  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
354  BasicBlockPass *BP = getContainedPass(Index);
355  BP->dumpPassStructure(Offset + 1);
356  dumpLastUses(BP, Offset+1);
357  }
358  }
359 
360  BasicBlockPass *getContainedPass(unsigned N) {
361  assert(N < PassVector.size() && "Pass number out of range!");
362  BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
363  return BP;
364  }
365 
366  PassManagerType getPassManagerType() const override {
368  }
369 };
370 
371 char BBPassManager::ID = 0;
372 } // End anonymous namespace
373 
374 namespace llvm {
375 namespace legacy {
376 //===----------------------------------------------------------------------===//
377 // FunctionPassManagerImpl
378 //
379 /// FunctionPassManagerImpl manages FPPassManagers
381  public PMDataManager,
382  public PMTopLevelManager {
383  virtual void anchor();
384 private:
385  bool wasRun;
386 public:
387  static char ID;
390  PMTopLevelManager(new FPPassManager()), wasRun(false) {}
391 
392  /// \copydoc FunctionPassManager::add()
393  void add(Pass *P) {
394  schedulePass(P);
395  }
396 
397  /// createPrinterPass - Get a function printer pass.
399  const std::string &Banner) const override {
400  return createPrintFunctionPass(O, Banner);
401  }
402 
403  // Prepare for running an on the fly pass, freeing memory if needed
404  // from a previous run.
405  void releaseMemoryOnTheFly();
406 
407  /// run - Execute all of the passes scheduled for execution. Keep track of
408  /// whether any of the passes modifies the module, and if so, return true.
409  bool run(Function &F);
410 
411  /// doInitialization - Run all of the initializers for the function passes.
412  ///
413  bool doInitialization(Module &M) override;
414 
415  /// doFinalization - Run all of the finalizers for the function passes.
416  ///
417  bool doFinalization(Module &M) override;
418 
419 
420  PMDataManager *getAsPMDataManager() override { return this; }
421  Pass *getAsPass() override { return this; }
424  }
425 
426  /// Pass Manager itself does not invalidate any analysis info.
427  void getAnalysisUsage(AnalysisUsage &Info) const override {
428  Info.setPreservesAll();
429  }
430 
432  assert(N < PassManagers.size() && "Pass number out of range!");
433  FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
434  return FP;
435  }
436 };
437 
438 void FunctionPassManagerImpl::anchor() {}
439 
441 } // End of legacy namespace
442 } // End of llvm namespace
443 
444 namespace {
445 //===----------------------------------------------------------------------===//
446 // MPPassManager
447 //
448 /// MPPassManager manages ModulePasses and function pass managers.
449 /// It batches all Module passes and function pass managers together and
450 /// sequences them to process one module.
451 class MPPassManager : public Pass, public PMDataManager {
452 public:
453  static char ID;
454  explicit MPPassManager() :
455  Pass(PT_PassManager, ID), PMDataManager() { }
456 
457  // Delete on the fly managers.
458  ~MPPassManager() override {
459  for (auto &OnTheFlyManager : OnTheFlyManagers) {
460  FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
461  delete FPP;
462  }
463  }
464 
465  /// createPrinterPass - Get a module printer pass.
466  Pass *createPrinterPass(raw_ostream &O,
467  const std::string &Banner) const override {
468  return createPrintModulePass(O, Banner);
469  }
470 
471  /// run - Execute all of the passes scheduled for execution. Keep track of
472  /// whether any of the passes modifies the module, and if so, return true.
473  bool runOnModule(Module &M);
474 
477 
478  /// Pass Manager itself does not invalidate any analysis info.
479  void getAnalysisUsage(AnalysisUsage &Info) const override {
480  Info.setPreservesAll();
481  }
482 
483  /// Add RequiredPass into list of lower level passes required by pass P.
484  /// RequiredPass is run on the fly by Pass Manager when P requests it
485  /// through getAnalysis interface.
486  void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
487 
488  /// Return function pass corresponding to PassInfo PI, that is
489  /// required by module pass MP. Instantiate analysis pass, by using
490  /// its runOnFunction() for function F.
491  Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
492 
493  StringRef getPassName() const override { return "Module Pass Manager"; }
494 
495  PMDataManager *getAsPMDataManager() override { return this; }
496  Pass *getAsPass() override { return this; }
497 
498  // Print passes managed by this manager
499  void dumpPassStructure(unsigned Offset) override {
500  dbgs().indent(Offset*2) << "ModulePass Manager\n";
501  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
502  ModulePass *MP = getContainedPass(Index);
503  MP->dumpPassStructure(Offset + 1);
505  OnTheFlyManagers.find(MP);
506  if (I != OnTheFlyManagers.end())
507  I->second->dumpPassStructure(Offset + 2);
508  dumpLastUses(MP, Offset+1);
509  }
510  }
511 
512  ModulePass *getContainedPass(unsigned N) {
513  assert(N < PassVector.size() && "Pass number out of range!");
514  return static_cast<ModulePass *>(PassVector[N]);
515  }
516 
517  PassManagerType getPassManagerType() const override {
518  return PMT_ModulePassManager;
519  }
520 
521  private:
522  /// Collection of on the fly FPPassManagers. These managers manage
523  /// function passes that are required by module passes.
525 };
526 
527 char MPPassManager::ID = 0;
528 } // End anonymous namespace
529 
530 namespace llvm {
531 namespace legacy {
532 //===----------------------------------------------------------------------===//
533 // PassManagerImpl
534 //
535 
536 /// PassManagerImpl manages MPPassManagers
537 class PassManagerImpl : public Pass,
538  public PMDataManager,
539  public PMTopLevelManager {
540  virtual void anchor();
541 
542 public:
543  static char ID;
544  explicit PassManagerImpl() :
546  PMTopLevelManager(new MPPassManager()) {}
547 
548  /// \copydoc PassManager::add()
549  void add(Pass *P) {
550  schedulePass(P);
551  }
552 
553  /// createPrinterPass - Get a module printer pass.
555  const std::string &Banner) const override {
556  return createPrintModulePass(O, Banner);
557  }
558 
559  /// run - Execute all of the passes scheduled for execution. Keep track of
560  /// whether any of the passes modifies the module, and if so, return true.
561  bool run(Module &M);
562 
565 
566  /// Pass Manager itself does not invalidate any analysis info.
567  void getAnalysisUsage(AnalysisUsage &Info) const override {
568  Info.setPreservesAll();
569  }
570 
571  PMDataManager *getAsPMDataManager() override { return this; }
572  Pass *getAsPass() override { return this; }
574  return PMT_ModulePassManager;
575  }
576 
577  MPPassManager *getContainedManager(unsigned N) {
578  assert(N < PassManagers.size() && "Pass number out of range!");
579  MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
580  return MP;
581  }
582 };
583 
584 void PassManagerImpl::anchor() {}
585 
586 char PassManagerImpl::ID = 0;
587 } // End of legacy namespace
588 } // End of llvm namespace
589 
590 //===----------------------------------------------------------------------===//
591 // PMTopLevelManager implementation
592 
593 /// Initialize top level manager. Create first pass manager.
595  PMDM->setTopLevelManager(this);
596  addPassManager(PMDM);
597  activeStack.push(PMDM);
598 }
599 
600 /// Set pass P as the last user of the given analysis passes.
601 void
603  unsigned PDepth = 0;
604  if (P->getResolver())
605  PDepth = P->getResolver()->getPMDataManager().getDepth();
606 
607  for (Pass *AP : AnalysisPasses) {
608  LastUser[AP] = P;
609 
610  if (P == AP)
611  continue;
612 
613  // Update the last users of passes that are required transitive by AP.
614  AnalysisUsage *AnUsage = findAnalysisUsage(AP);
615  const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
616  SmallVector<Pass *, 12> LastUses;
617  SmallVector<Pass *, 12> LastPMUses;
618  for (AnalysisID ID : IDs) {
619  Pass *AnalysisPass = findAnalysisPass(ID);
620  assert(AnalysisPass && "Expected analysis pass to exist.");
621  AnalysisResolver *AR = AnalysisPass->getResolver();
622  assert(AR && "Expected analysis resolver to exist.");
623  unsigned APDepth = AR->getPMDataManager().getDepth();
624 
625  if (PDepth == APDepth)
626  LastUses.push_back(AnalysisPass);
627  else if (PDepth > APDepth)
628  LastPMUses.push_back(AnalysisPass);
629  }
630 
631  setLastUser(LastUses, P);
632 
633  // If this pass has a corresponding pass manager, push higher level
634  // analysis to this pass manager.
635  if (P->getResolver())
636  setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
637 
638 
639  // If AP is the last user of other passes then make P last user of
640  // such passes.
641  for (auto LU : LastUser) {
642  if (LU.second == AP)
643  // DenseMap iterator is not invalidated here because
644  // this is just updating existing entries.
645  LastUser[LU.first] = P;
646  }
647  }
648 }
649 
650 /// Collect passes whose last user is P
652  Pass *P) {
654  InversedLastUser.find(P);
655  if (DMI == InversedLastUser.end())
656  return;
657 
658  SmallPtrSet<Pass *, 8> &LU = DMI->second;
659  for (Pass *LUP : LU) {
660  LastUses.push_back(LUP);
661  }
662 
663 }
664 
666  AnalysisUsage *AnUsage = nullptr;
667  auto DMI = AnUsageMap.find(P);
668  if (DMI != AnUsageMap.end())
669  AnUsage = DMI->second;
670  else {
671  // Look up the analysis usage from the pass instance (different instances
672  // of the same pass can produce different results), but unique the
673  // resulting object to reduce memory usage. This helps to greatly reduce
674  // memory usage when we have many instances of only a few pass types
675  // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
676  // of dependencies.
677  AnalysisUsage AU;
678  P->getAnalysisUsage(AU);
679 
680  AUFoldingSetNode* Node = nullptr;
682  AUFoldingSetNode::Profile(ID, AU);
683  void *IP = nullptr;
684  if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
685  Node = N;
686  else {
687  Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
688  UniqueAnalysisUsages.InsertNode(Node, IP);
689  }
690  assert(Node && "cached analysis usage must be non null");
691 
692  AnUsageMap[P] = &Node->AU;
693  AnUsage = &Node->AU;
694  }
695  return AnUsage;
696 }
697 
698 /// Schedule pass P for execution. Make sure that passes required by
699 /// P are run before P is run. Update analysis info maintained by
700 /// the manager. Remove dead passes. This is a recursive function.
702 
703  // TODO : Allocate function manager for this pass, other wise required set
704  // may be inserted into previous function manager
705 
706  // Give pass a chance to prepare the stage.
707  P->preparePassManager(activeStack);
708 
709  // If P is an analysis pass and it is available then do not
710  // generate the analysis again. Stale analysis info should not be
711  // available at this point.
712  const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
713  if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
714  // Remove any cached AnalysisUsage information.
715  AnUsageMap.erase(P);
716  delete P;
717  return;
718  }
719 
720  AnalysisUsage *AnUsage = findAnalysisUsage(P);
721 
722  bool checkAnalysis = true;
723  while (checkAnalysis) {
724  checkAnalysis = false;
725 
726  const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
727  for (const AnalysisID ID : RequiredSet) {
728 
729  Pass *AnalysisPass = findAnalysisPass(ID);
730  if (!AnalysisPass) {
731  const PassInfo *PI = findAnalysisPassInfo(ID);
732 
733  if (!PI) {
734  // Pass P is not in the global PassRegistry
735  dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
736  dbgs() << "Verify if there is a pass dependency cycle." << "\n";
737  dbgs() << "Required Passes:" << "\n";
738  for (const AnalysisID ID2 : RequiredSet) {
739  if (ID == ID2)
740  break;
741  Pass *AnalysisPass2 = findAnalysisPass(ID2);
742  if (AnalysisPass2) {
743  dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
744  } else {
745  dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
746  dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
747  dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
748  }
749  }
750  }
751 
752  assert(PI && "Expected required passes to be initialized");
753  AnalysisPass = PI->createPass();
754  if (P->getPotentialPassManagerType () ==
755  AnalysisPass->getPotentialPassManagerType())
756  // Schedule analysis pass that is managed by the same pass manager.
757  schedulePass(AnalysisPass);
758  else if (P->getPotentialPassManagerType () >
759  AnalysisPass->getPotentialPassManagerType()) {
760  // Schedule analysis pass that is managed by a new manager.
761  schedulePass(AnalysisPass);
762  // Recheck analysis passes to ensure that required analyses that
763  // are already checked are still available.
764  checkAnalysis = true;
765  } else
766  // Do not schedule this analysis. Lower level analysis
767  // passes are run on the fly.
768  delete AnalysisPass;
769  }
770  }
771  }
772 
773  // Now all required passes are available.
774  if (ImmutablePass *IP = P->getAsImmutablePass()) {
775  // P is a immutable pass and it will be managed by this
776  // top level manager. Set up analysis resolver to connect them.
777  PMDataManager *DM = getAsPMDataManager();
778  AnalysisResolver *AR = new AnalysisResolver(*DM);
779  P->setResolver(AR);
780  DM->initializeAnalysisImpl(P);
781  addImmutablePass(IP);
782  DM->recordAvailableAnalysis(IP);
783  return;
784  }
785 
786  if (PI && !PI->isAnalysis() && shouldPrintBeforePass(PI->getPassArgument())) {
787  Pass *PP = P->createPrinterPass(
788  dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
789  PP->assignPassManager(activeStack, getTopLevelPassManagerType());
790  }
791 
792  // Add the requested pass to the best available pass manager.
793  P->assignPassManager(activeStack, getTopLevelPassManagerType());
794 
795  if (PI && !PI->isAnalysis() && shouldPrintAfterPass(PI->getPassArgument())) {
796  Pass *PP = P->createPrinterPass(
797  dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
798  PP->assignPassManager(activeStack, getTopLevelPassManagerType());
799  }
800 }
801 
802 /// Find the pass that implements Analysis AID. Search immutable
803 /// passes and all pass managers. If desired pass is not found
804 /// then return NULL.
806  // For immutable passes we have a direct mapping from ID to pass, so check
807  // that first.
808  if (Pass *P = ImmutablePassMap.lookup(AID))
809  return P;
810 
811  // Check pass managers
812  for (PMDataManager *PassManager : PassManagers)
813  if (Pass *P = PassManager->findAnalysisPass(AID, false))
814  return P;
815 
816  // Check other pass managers
817  for (PMDataManager *IndirectPassManager : IndirectPassManagers)
818  if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
819  return P;
820 
821  return nullptr;
822 }
823 
825  const PassInfo *&PI = AnalysisPassInfos[AID];
826  if (!PI)
828  else
830  "The pass info pointer changed for an analysis ID!");
831 
832  return PI;
833 }
834 
836  P->initializePass();
837  ImmutablePasses.push_back(P);
838 
839  // Add this pass to the map from its analysis ID. We clobber any prior runs
840  // of the pass in the map so that the last one added is the one found when
841  // doing lookups.
842  AnalysisID AID = P->getPassID();
843  ImmutablePassMap[AID] = P;
844 
845  // Also add any interfaces implemented by the immutable pass to the map for
846  // fast lookup.
847  const PassInfo *PassInf = findAnalysisPassInfo(AID);
848  assert(PassInf && "Expected all immutable passes to be initialized");
849  for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
850  ImmutablePassMap[ImmPI->getTypeInfo()] = P;
851 }
852 
853 // Print passes managed by this top level manager.
855 
856  if (PassDebugging < Structure)
857  return;
858 
859  // Print out the immutable passes
860  for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
861  ImmutablePasses[i]->dumpPassStructure(0);
862  }
863 
864  // Every class that derives from PMDataManager also derives from Pass
865  // (sometimes indirectly), but there's no inheritance relationship
866  // between PMDataManager and Pass, so we have to getAsPass to get
867  // from a PMDataManager* to a Pass*.
868  for (PMDataManager *Manager : PassManagers)
869  Manager->getAsPass()->dumpPassStructure(1);
870 }
871 
873 
874  if (PassDebugging < Arguments)
875  return;
876 
877  dbgs() << "Pass Arguments: ";
878  for (ImmutablePass *P : ImmutablePasses)
879  if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
880  assert(PI && "Expected all immutable passes to be initialized");
881  if (!PI->isAnalysisGroup())
882  dbgs() << " -" << PI->getPassArgument();
883  }
884  for (PMDataManager *PM : PassManagers)
885  PM->dumpPassArguments();
886  dbgs() << "\n";
887 }
888 
890  for (PMDataManager *PM : PassManagers)
891  PM->initializeAnalysisInfo();
892 
893  // Initailize other pass managers
894  for (PMDataManager *IPM : IndirectPassManagers)
895  IPM->initializeAnalysisInfo();
896 
897  for (auto LU : LastUser) {
898  SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
899  L.insert(LU.first);
900  }
901 }
902 
903 /// Destructor
905  for (PMDataManager *PM : PassManagers)
906  delete PM;
907 
908  for (ImmutablePass *P : ImmutablePasses)
909  delete P;
910 }
911 
912 //===----------------------------------------------------------------------===//
913 // PMDataManager implementation
914 
915 /// Augement AvailableAnalysis by adding analysis made available by pass P.
917  AnalysisID PI = P->getPassID();
918 
919  AvailableAnalysis[PI] = P;
920 
921  assert(!AvailableAnalysis.empty());
922 
923  // This pass is the current implementation of all of the interfaces it
924  // implements as well.
925  const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
926  if (!PInf) return;
927  const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
928  for (unsigned i = 0, e = II.size(); i != e; ++i)
929  AvailableAnalysis[II[i]->getTypeInfo()] = P;
930 }
931 
932 // Return true if P preserves high level analysis used by other
933 // passes managed by this manager
935  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
936  if (AnUsage->getPreservesAll())
937  return true;
938 
939  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
940  for (Pass *P1 : HigherLevelAnalysis) {
941  if (P1->getAsImmutablePass() == nullptr &&
942  !is_contained(PreservedSet, P1->getPassID()))
943  return false;
944  }
945 
946  return true;
947 }
948 
949 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
951  // Don't do this unless assertions are enabled.
952 #ifdef NDEBUG
953  return;
954 #endif
955  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
956  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
957 
958  // Verify preserved analysis
959  for (AnalysisID AID : PreservedSet) {
960  if (Pass *AP = findAnalysisPass(AID, true)) {
961  TimeRegion PassTimer(getPassTimer(AP));
962  AP->verifyAnalysis();
963  }
964  }
965 }
966 
967 /// Remove Analysis not preserved by Pass P
969  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
970  if (AnUsage->getPreservesAll())
971  return;
972 
973  const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
974  for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
975  E = AvailableAnalysis.end(); I != E; ) {
977  if (Info->second->getAsImmutablePass() == nullptr &&
978  !is_contained(PreservedSet, Info->first)) {
979  // Remove this analysis
980  if (PassDebugging >= Details) {
981  Pass *S = Info->second;
982  dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
983  dbgs() << S->getPassName() << "'\n";
984  }
985  AvailableAnalysis.erase(Info);
986  }
987  }
988 
989  // Check inherited analysis also. If P is not preserving analysis
990  // provided by parent manager then remove it here.
991  for (unsigned Index = 0; Index < PMT_Last; ++Index) {
992 
993  if (!InheritedAnalysis[Index])
994  continue;
995 
997  I = InheritedAnalysis[Index]->begin(),
998  E = InheritedAnalysis[Index]->end(); I != E; ) {
1000  if (Info->second->getAsImmutablePass() == nullptr &&
1001  !is_contained(PreservedSet, Info->first)) {
1002  // Remove this analysis
1003  if (PassDebugging >= Details) {
1004  Pass *S = Info->second;
1005  dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
1006  dbgs() << S->getPassName() << "'\n";
1007  }
1008  InheritedAnalysis[Index]->erase(Info);
1009  }
1010  }
1011  }
1012 }
1013 
1014 /// Remove analysis passes that are not used any longer
1016  enum PassDebuggingString DBG_STR) {
1017 
1018  SmallVector<Pass *, 12> DeadPasses;
1019 
1020  // If this is a on the fly manager then it does not have TPM.
1021  if (!TPM)
1022  return;
1023 
1024  TPM->collectLastUses(DeadPasses, P);
1025 
1026  if (PassDebugging >= Details && !DeadPasses.empty()) {
1027  dbgs() << " -*- '" << P->getPassName();
1028  dbgs() << "' is the last user of following pass instances.";
1029  dbgs() << " Free these instances\n";
1030  }
1031 
1032  for (Pass *P : DeadPasses)
1033  freePass(P, Msg, DBG_STR);
1034 }
1035 
1037  enum PassDebuggingString DBG_STR) {
1038  dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
1039 
1040  {
1041  // If the pass crashes releasing memory, remember this.
1043  TimeRegion PassTimer(getPassTimer(P));
1044 
1045  P->releaseMemory();
1046  }
1047 
1048  AnalysisID PI = P->getPassID();
1049  if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
1050  // Remove the pass itself (if it is not already removed).
1051  AvailableAnalysis.erase(PI);
1052 
1053  // Remove all interfaces this pass implements, for which it is also
1054  // listed as the available implementation.
1055  const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
1056  for (unsigned i = 0, e = II.size(); i != e; ++i) {
1058  AvailableAnalysis.find(II[i]->getTypeInfo());
1059  if (Pos != AvailableAnalysis.end() && Pos->second == P)
1060  AvailableAnalysis.erase(Pos);
1061  }
1062  }
1063 }
1064 
1065 /// Add pass P into the PassVector. Update
1066 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
1067 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
1068  // This manager is going to manage pass P. Set up analysis resolver
1069  // to connect them.
1070  AnalysisResolver *AR = new AnalysisResolver(*this);
1071  P->setResolver(AR);
1072 
1073  // If a FunctionPass F is the last user of ModulePass info M
1074  // then the F's manager, not F, records itself as a last user of M.
1075  SmallVector<Pass *, 12> TransferLastUses;
1076 
1077  if (!ProcessAnalysis) {
1078  // Add pass
1079  PassVector.push_back(P);
1080  return;
1081  }
1082 
1083  // At the moment, this pass is the last user of all required passes.
1084  SmallVector<Pass *, 12> LastUses;
1085  SmallVector<Pass *, 8> UsedPasses;
1086  SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1087 
1088  unsigned PDepth = this->getDepth();
1089 
1090  collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
1091  for (Pass *PUsed : UsedPasses) {
1092  unsigned RDepth = 0;
1093 
1094  assert(PUsed->getResolver() && "Analysis Resolver is not set");
1095  PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1096  RDepth = DM.getDepth();
1097 
1098  if (PDepth == RDepth)
1099  LastUses.push_back(PUsed);
1100  else if (PDepth > RDepth) {
1101  // Let the parent claim responsibility of last use
1102  TransferLastUses.push_back(PUsed);
1103  // Keep track of higher level analysis used by this manager.
1104  HigherLevelAnalysis.push_back(PUsed);
1105  } else
1106  llvm_unreachable("Unable to accommodate Used Pass");
1107  }
1108 
1109  // Set P as P's last user until someone starts using P.
1110  // However, if P is a Pass Manager then it does not need
1111  // to record its last user.
1112  if (!P->getAsPMDataManager())
1113  LastUses.push_back(P);
1114  TPM->setLastUser(LastUses, P);
1115 
1116  if (!TransferLastUses.empty()) {
1117  Pass *My_PM = getAsPass();
1118  TPM->setLastUser(TransferLastUses, My_PM);
1119  TransferLastUses.clear();
1120  }
1121 
1122  // Now, take care of required analyses that are not available.
1123  for (AnalysisID ID : ReqAnalysisNotAvailable) {
1124  const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1125  Pass *AnalysisPass = PI->createPass();
1126  this->addLowerLevelRequiredPass(P, AnalysisPass);
1127  }
1128 
1129  // Take a note of analysis required and made available by this pass.
1130  // Remove the analysis not preserved by this pass
1131  removeNotPreservedAnalysis(P);
1132  recordAvailableAnalysis(P);
1133 
1134  // Add pass
1135  PassVector.push_back(P);
1136 }
1137 
1138 
1139 /// Populate UP with analysis pass that are used or required by
1140 /// pass P and are available. Populate RP_NotAvail with analysis
1141 /// pass that are required by pass P but are not available.
1144  Pass *P) {
1145  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1146 
1147  for (const auto &UsedID : AnUsage->getUsedSet())
1148  if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1149  UP.push_back(AnalysisPass);
1150 
1151  for (const auto &RequiredID : AnUsage->getRequiredSet())
1152  if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1153  UP.push_back(AnalysisPass);
1154  else
1155  RP_NotAvail.push_back(RequiredID);
1156 
1157  for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1158  if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1159  UP.push_back(AnalysisPass);
1160  else
1161  RP_NotAvail.push_back(RequiredID);
1162 }
1163 
1164 // All Required analyses should be available to the pass as it runs! Here
1165 // we fill in the AnalysisImpls member of the pass so that it can
1166 // successfully use the getAnalysis() method to retrieve the
1167 // implementations it needs.
1168 //
1170  AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1171 
1172  for (const AnalysisID ID : AnUsage->getRequiredSet()) {
1173  Pass *Impl = findAnalysisPass(ID, true);
1174  if (!Impl)
1175  // This may be analysis pass that is initialized on the fly.
1176  // If that is not the case then it will raise an assert when it is used.
1177  continue;
1178  AnalysisResolver *AR = P->getResolver();
1179  assert(AR && "Analysis Resolver is not set");
1180  AR->addAnalysisImplsPair(ID, Impl);
1181  }
1182 }
1183 
1184 /// Find the pass that implements Analysis AID. If desired pass is not found
1185 /// then return NULL.
1187 
1188  // Check if AvailableAnalysis map has one entry.
1189  DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1190 
1191  if (I != AvailableAnalysis.end())
1192  return I->second;
1193 
1194  // Search Parents through TopLevelManager
1195  if (SearchParent)
1196  return TPM->findAnalysisPass(AID);
1197 
1198  return nullptr;
1199 }
1200 
1201 // Print list of passes that are last used by P.
1202 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1203 
1205 
1206  // If this is a on the fly manager then it does not have TPM.
1207  if (!TPM)
1208  return;
1209 
1210  TPM->collectLastUses(LUses, P);
1211 
1212  for (Pass *P : LUses) {
1213  dbgs() << "--" << std::string(Offset*2, ' ');
1214  P->dumpPassStructure(0);
1215  }
1216 }
1217 
1219  for (Pass *P : PassVector) {
1220  if (PMDataManager *PMD = P->getAsPMDataManager())
1221  PMD->dumpPassArguments();
1222  else
1223  if (const PassInfo *PI =
1224  TPM->findAnalysisPassInfo(P->getPassID()))
1225  if (!PI->isAnalysisGroup())
1226  dbgs() << " -" << PI->getPassArgument();
1227  }
1228 }
1229 
1231  enum PassDebuggingString S2,
1232  StringRef Msg) {
1233  if (PassDebugging < Executions)
1234  return;
1235  dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1236  << std::string(getDepth() * 2 + 1, ' ');
1237  switch (S1) {
1238  case EXECUTION_MSG:
1239  dbgs() << "Executing Pass '" << P->getPassName();
1240  break;
1241  case MODIFICATION_MSG:
1242  dbgs() << "Made Modification '" << P->getPassName();
1243  break;
1244  case FREEING_MSG:
1245  dbgs() << " Freeing Pass '" << P->getPassName();
1246  break;
1247  default:
1248  break;
1249  }
1250  switch (S2) {
1251  case ON_BASICBLOCK_MSG:
1252  dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1253  break;
1254  case ON_FUNCTION_MSG:
1255  dbgs() << "' on Function '" << Msg << "'...\n";
1256  break;
1257  case ON_MODULE_MSG:
1258  dbgs() << "' on Module '" << Msg << "'...\n";
1259  break;
1260  case ON_REGION_MSG:
1261  dbgs() << "' on Region '" << Msg << "'...\n";
1262  break;
1263  case ON_LOOP_MSG:
1264  dbgs() << "' on Loop '" << Msg << "'...\n";
1265  break;
1266  case ON_CG_MSG:
1267  dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1268  break;
1269  default:
1270  break;
1271  }
1272 }
1273 
1275  if (PassDebugging < Details)
1276  return;
1277 
1278  AnalysisUsage analysisUsage;
1279  P->getAnalysisUsage(analysisUsage);
1280  dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1281 }
1282 
1284  if (PassDebugging < Details)
1285  return;
1286 
1287  AnalysisUsage analysisUsage;
1288  P->getAnalysisUsage(analysisUsage);
1289  dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1290 }
1291 
1292 void PMDataManager::dumpUsedSet(const Pass *P) const {
1293  if (PassDebugging < Details)
1294  return;
1295 
1296  AnalysisUsage analysisUsage;
1297  P->getAnalysisUsage(analysisUsage);
1298  dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1299 }
1300 
1301 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1302  const AnalysisUsage::VectorType &Set) const {
1303  assert(PassDebugging >= Details);
1304  if (Set.empty())
1305  return;
1306  dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1307  for (unsigned i = 0; i != Set.size(); ++i) {
1308  if (i) dbgs() << ',';
1309  const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1310  if (!PInf) {
1311  // Some preserved passes, such as AliasAnalysis, may not be initialized by
1312  // all drivers.
1313  dbgs() << " Uninitialized Pass";
1314  continue;
1315  }
1316  dbgs() << ' ' << PInf->getPassName();
1317  }
1318  dbgs() << '\n';
1319 }
1320 
1321 /// Add RequiredPass into list of lower level passes required by pass P.
1322 /// RequiredPass is run on the fly by Pass Manager when P requests it
1323 /// through getAnalysis interface.
1324 /// This should be handled by specific pass manager.
1326  if (TPM) {
1327  TPM->dumpArguments();
1328  TPM->dumpPasses();
1329  }
1330 
1331  // Module Level pass may required Function Level analysis info
1332  // (e.g. dominator info). Pass manager uses on the fly function pass manager
1333  // to provide this on demand. In that case, in Pass manager terminology,
1334  // module level pass is requiring lower level analysis info managed by
1335  // lower level pass manager.
1336 
1337  // When Pass manager is not able to order required analysis info, Pass manager
1338  // checks whether any lower level manager will be able to provide this
1339  // analysis info on demand or not.
1340 #ifndef NDEBUG
1341  dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1342  dbgs() << "' required by '" << P->getPassName() << "'\n";
1343 #endif
1344  llvm_unreachable("Unable to schedule pass");
1345 }
1346 
1348  llvm_unreachable("Unable to find on the fly pass");
1349 }
1350 
1351 // Destructor
1353  for (Pass *P : PassVector)
1354  delete P;
1355 }
1356 
1357 //===----------------------------------------------------------------------===//
1358 // NOTE: Is this the right place to define this method ?
1359 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1361  return PM.findAnalysisPass(ID, dir);
1362 }
1363 
1365  Function &F) {
1366  return PM.getOnTheFlyPass(P, AnalysisPI, F);
1367 }
1368 
1369 //===----------------------------------------------------------------------===//
1370 // BBPassManager implementation
1371 
1372 /// Execute all of the passes scheduled for execution by invoking
1373 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1374 /// the function, and if so, return true.
1376  if (F.isDeclaration())
1377  return false;
1378 
1379  bool Changed = doInitialization(F);
1380  Module &M = *F.getParent();
1381 
1382  unsigned InstrCount, BBSize = 0;
1383  StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1384  bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1385  if (EmitICRemark)
1386  InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1387 
1388  for (BasicBlock &BB : F) {
1389  // Collect the initial size of the basic block.
1390  if (EmitICRemark)
1391  BBSize = BB.size();
1392  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1393  BasicBlockPass *BP = getContainedPass(Index);
1394  bool LocalChanged = false;
1395 
1396  dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, BB.getName());
1397  dumpRequiredSet(BP);
1398 
1399  initializeAnalysisImpl(BP);
1400 
1401  {
1402  // If the pass crashes, remember this.
1404  TimeRegion PassTimer(getPassTimer(BP));
1405  LocalChanged |= BP->runOnBasicBlock(BB);
1406  if (EmitICRemark) {
1407  unsigned NewSize = BB.size();
1408  // Update the size of the basic block, emit a remark, and update the
1409  // size of the module.
1410  if (NewSize != BBSize) {
1411  int64_t Delta =
1412  static_cast<int64_t>(NewSize) - static_cast<int64_t>(BBSize);
1413  emitInstrCountChangedRemark(BP, M, Delta, InstrCount,
1414  FunctionToInstrCount, &F);
1415  InstrCount = static_cast<int64_t>(InstrCount) + Delta;
1416  BBSize = NewSize;
1417  }
1418  }
1419  }
1420 
1421  Changed |= LocalChanged;
1422  if (LocalChanged)
1423  dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1424  BB.getName());
1425  dumpPreservedSet(BP);
1426  dumpUsedSet(BP);
1427 
1428  verifyPreservedAnalysis(BP);
1429  removeNotPreservedAnalysis(BP);
1430  recordAvailableAnalysis(BP);
1431  removeDeadPasses(BP, BB.getName(), ON_BASICBLOCK_MSG);
1432  }
1433  }
1434 
1435  return doFinalization(F) || Changed;
1436 }
1437 
1438 // Implement doInitialization and doFinalization
1439 bool BBPassManager::doInitialization(Module &M) {
1440  bool Changed = false;
1441 
1442  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1443  Changed |= getContainedPass(Index)->doInitialization(M);
1444 
1445  return Changed;
1446 }
1447 
1448 bool BBPassManager::doFinalization(Module &M) {
1449  bool Changed = false;
1450 
1451  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1452  Changed |= getContainedPass(Index)->doFinalization(M);
1453 
1454  return Changed;
1455 }
1456 
1457 bool BBPassManager::doInitialization(Function &F) {
1458  bool Changed = false;
1459 
1460  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1461  BasicBlockPass *BP = getContainedPass(Index);
1462  Changed |= BP->doInitialization(F);
1463  }
1464 
1465  return Changed;
1466 }
1467 
1468 bool BBPassManager::doFinalization(Function &F) {
1469  bool Changed = false;
1470 
1471  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1472  BasicBlockPass *BP = getContainedPass(Index);
1473  Changed |= BP->doFinalization(F);
1474  }
1475 
1476  return Changed;
1477 }
1478 
1479 
1480 //===----------------------------------------------------------------------===//
1481 // FunctionPassManager implementation
1482 
1483 /// Create new Function pass manager
1485  FPM = new FunctionPassManagerImpl();
1486  // FPM is the top level manager.
1487  FPM->setTopLevelManager(FPM);
1488 
1489  AnalysisResolver *AR = new AnalysisResolver(*FPM);
1490  FPM->setResolver(AR);
1491 }
1492 
1494  delete FPM;
1495 }
1496 
1498  FPM->add(P);
1499 }
1500 
1501 /// run - Execute all of the passes scheduled for execution. Keep
1502 /// track of whether any of the passes modifies the function, and if
1503 /// so, return true.
1504 ///
1506  handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1507  report_fatal_error("Error reading bitcode file: " + EIB.message());
1508  });
1509  return FPM->run(F);
1510 }
1511 
1512 
1513 /// doInitialization - Run all of the initializers for the function passes.
1514 ///
1516  return FPM->doInitialization(*M);
1517 }
1518 
1519 /// doFinalization - Run all of the finalizers for the function passes.
1520 ///
1522  return FPM->doFinalization(*M);
1523 }
1524 
1525 //===----------------------------------------------------------------------===//
1526 // FunctionPassManagerImpl implementation
1527 //
1529  bool Changed = false;
1530 
1531  dumpArguments();
1532  dumpPasses();
1533 
1534  for (ImmutablePass *ImPass : getImmutablePasses())
1535  Changed |= ImPass->doInitialization(M);
1536 
1537  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1538  Changed |= getContainedManager(Index)->doInitialization(M);
1539 
1540  return Changed;
1541 }
1542 
1544  bool Changed = false;
1545 
1546  for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1547  Changed |= getContainedManager(Index)->doFinalization(M);
1548 
1549  for (ImmutablePass *ImPass : getImmutablePasses())
1550  Changed |= ImPass->doFinalization(M);
1551 
1552  return Changed;
1553 }
1554 
1555 /// cleanup - After running all passes, clean up pass manager cache.
1557  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1558  FunctionPass *FP = getContainedPass(Index);
1559  AnalysisResolver *AR = FP->getResolver();
1560  assert(AR && "Analysis Resolver is not set");
1561  AR->clearAnalysisImpls();
1562  }
1563 }
1564 
1566  if (!wasRun)
1567  return;
1568  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1569  FPPassManager *FPPM = getContainedManager(Index);
1570  for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1572  }
1573  }
1574  wasRun = false;
1575 }
1576 
1577 // Execute all the passes managed by this top level manager.
1578 // Return true if any function is modified by a pass.
1580  bool Changed = false;
1581 
1582  initializeAllAnalysisInfo();
1583  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1584  Changed |= getContainedManager(Index)->runOnFunction(F);
1585  F.getContext().yield();
1586  }
1587 
1588  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1589  getContainedManager(Index)->cleanup();
1590 
1591  wasRun = true;
1592  return Changed;
1593 }
1594 
1595 //===----------------------------------------------------------------------===//
1596 // FPPassManager implementation
1597 
1598 char FPPassManager::ID = 0;
1599 /// Print passes managed by this manager
1601  dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1602  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1603  FunctionPass *FP = getContainedPass(Index);
1604  FP->dumpPassStructure(Offset + 1);
1605  dumpLastUses(FP, Offset+1);
1606  }
1607 }
1608 
1609 
1610 /// Execute all of the passes scheduled for execution by invoking
1611 /// runOnFunction method. Keep track of whether any of the passes modifies
1612 /// the function, and if so, return true.
1614  if (F.isDeclaration())
1615  return false;
1616 
1617  bool Changed = false;
1618  Module &M = *F.getParent();
1619  // Collect inherited analysis from Module level pass manager.
1620  populateInheritedAnalysis(TPM->activeStack);
1621 
1622  unsigned InstrCount, FunctionSize = 0;
1623  StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1624  bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1625  // Collect the initial size of the module.
1626  if (EmitICRemark) {
1627  InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1628  FunctionSize = F.getInstructionCount();
1629  }
1630 
1631  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1632  FunctionPass *FP = getContainedPass(Index);
1633  bool LocalChanged = false;
1634 
1635  dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1636  dumpRequiredSet(FP);
1637 
1638  initializeAnalysisImpl(FP);
1639 
1640  {
1642  TimeRegion PassTimer(getPassTimer(FP));
1643  LocalChanged |= FP->runOnFunction(F);
1644  if (EmitICRemark) {
1645  unsigned NewSize = F.getInstructionCount();
1646 
1647  // Update the size of the function, emit a remark, and update the size
1648  // of the module.
1649  if (NewSize != FunctionSize) {
1650  int64_t Delta = static_cast<int64_t>(NewSize) -
1651  static_cast<int64_t>(FunctionSize);
1652  emitInstrCountChangedRemark(FP, M, Delta, InstrCount,
1653  FunctionToInstrCount, &F);
1654  InstrCount = static_cast<int64_t>(InstrCount) + Delta;
1655  FunctionSize = NewSize;
1656  }
1657  }
1658  }
1659 
1660  Changed |= LocalChanged;
1661  if (LocalChanged)
1662  dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1663  dumpPreservedSet(FP);
1664  dumpUsedSet(FP);
1665 
1666  verifyPreservedAnalysis(FP);
1667  removeNotPreservedAnalysis(FP);
1668  recordAvailableAnalysis(FP);
1669  removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1670  }
1671  return Changed;
1672 }
1673 
1675  bool Changed = false;
1676 
1677  for (Function &F : M)
1678  Changed |= runOnFunction(F);
1679 
1680  return Changed;
1681 }
1682 
1684  bool Changed = false;
1685 
1686  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1687  Changed |= getContainedPass(Index)->doInitialization(M);
1688 
1689  return Changed;
1690 }
1691 
1693  bool Changed = false;
1694 
1695  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1696  Changed |= getContainedPass(Index)->doFinalization(M);
1697 
1698  return Changed;
1699 }
1700 
1701 //===----------------------------------------------------------------------===//
1702 // MPPassManager implementation
1703 
1704 /// Execute all of the passes scheduled for execution by invoking
1705 /// runOnModule method. Keep track of whether any of the passes modifies
1706 /// the module, and if so, return true.
1707 bool
1708 MPPassManager::runOnModule(Module &M) {
1709  bool Changed = false;
1710 
1711  // Initialize on-the-fly passes
1712  for (auto &OnTheFlyManager : OnTheFlyManagers) {
1713  FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1714  Changed |= FPP->doInitialization(M);
1715  }
1716 
1717  // Initialize module passes
1718  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1719  Changed |= getContainedPass(Index)->doInitialization(M);
1720 
1721  unsigned InstrCount, ModuleCount = 0;
1722  StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1723  bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1724  // Collect the initial size of the module.
1725  if (EmitICRemark) {
1726  InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1727  ModuleCount = InstrCount;
1728  }
1729 
1730  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1731  ModulePass *MP = getContainedPass(Index);
1732  bool LocalChanged = false;
1733 
1734  dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1735  dumpRequiredSet(MP);
1736 
1737  initializeAnalysisImpl(MP);
1738 
1739  {
1741  TimeRegion PassTimer(getPassTimer(MP));
1742 
1743  LocalChanged |= MP->runOnModule(M);
1744  if (EmitICRemark) {
1745  // Update the size of the module.
1746  ModuleCount = M.getInstructionCount();
1747  if (ModuleCount != InstrCount) {
1748  int64_t Delta = static_cast<int64_t>(ModuleCount) -
1749  static_cast<int64_t>(InstrCount);
1750  emitInstrCountChangedRemark(MP, M, Delta, InstrCount,
1751  FunctionToInstrCount);
1752  InstrCount = ModuleCount;
1753  }
1754  }
1755  }
1756 
1757  Changed |= LocalChanged;
1758  if (LocalChanged)
1759  dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1760  M.getModuleIdentifier());
1761  dumpPreservedSet(MP);
1762  dumpUsedSet(MP);
1763 
1764  verifyPreservedAnalysis(MP);
1765  removeNotPreservedAnalysis(MP);
1766  recordAvailableAnalysis(MP);
1767  removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1768  }
1769 
1770  // Finalize module passes
1771  for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1772  Changed |= getContainedPass(Index)->doFinalization(M);
1773 
1774  // Finalize on-the-fly passes
1775  for (auto &OnTheFlyManager : OnTheFlyManagers) {
1776  FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1777  // We don't know when is the last time an on-the-fly pass is run,
1778  // so we need to releaseMemory / finalize here
1779  FPP->releaseMemoryOnTheFly();
1780  Changed |= FPP->doFinalization(M);
1781  }
1782 
1783  return Changed;
1784 }
1785 
1786 /// Add RequiredPass into list of lower level passes required by pass P.
1787 /// RequiredPass is run on the fly by Pass Manager when P requests it
1788 /// through getAnalysis interface.
1789 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1791  "Unable to handle Pass that requires lower level Analysis pass");
1793  RequiredPass->getPotentialPassManagerType()) &&
1794  "Unable to handle Pass that requires lower level Analysis pass");
1795  if (!RequiredPass)
1796  return;
1797 
1798  FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1799  if (!FPP) {
1800  FPP = new FunctionPassManagerImpl();
1801  // FPP is the top level manager.
1802  FPP->setTopLevelManager(FPP);
1803 
1804  OnTheFlyManagers[P] = FPP;
1805  }
1806  const PassInfo *RequiredPassPI =
1807  TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1808 
1809  Pass *FoundPass = nullptr;
1810  if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1811  FoundPass =
1812  ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1813  }
1814  if (!FoundPass) {
1815  FoundPass = RequiredPass;
1816  // This should be guaranteed to add RequiredPass to the passmanager given
1817  // that we checked for an available analysis above.
1818  FPP->add(RequiredPass);
1819  }
1820  // Register P as the last user of FoundPass or RequiredPass.
1822  LU.push_back(FoundPass);
1823  FPP->setLastUser(LU, P);
1824 }
1825 
1826 /// Return function pass corresponding to PassInfo PI, that is
1827 /// required by module pass MP. Instantiate analysis pass, by using
1828 /// its runOnFunction() for function F.
1829 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1830  FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1831  assert(FPP && "Unable to find on the fly pass");
1832 
1833  FPP->releaseMemoryOnTheFly();
1834  FPP->run(F);
1835  return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1836 }
1837 
1838 
1839 //===----------------------------------------------------------------------===//
1840 // PassManagerImpl implementation
1841 
1842 //
1843 /// run - Execute all of the passes scheduled for execution. Keep track of
1844 /// whether any of the passes modifies the module, and if so, return true.
1846  bool Changed = false;
1847 
1848  dumpArguments();
1849  dumpPasses();
1850 
1851  for (ImmutablePass *ImPass : getImmutablePasses())
1852  Changed |= ImPass->doInitialization(M);
1853 
1854  initializeAllAnalysisInfo();
1855  for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1856  Changed |= getContainedManager(Index)->runOnModule(M);
1857  M.getContext().yield();
1858  }
1859 
1860  for (ImmutablePass *ImPass : getImmutablePasses())
1861  Changed |= ImPass->doFinalization(M);
1862 
1863  return Changed;
1864 }
1865 
1866 //===----------------------------------------------------------------------===//
1867 // PassManager implementation
1868 
1869 /// Create new pass manager
1871  PM = new PassManagerImpl();
1872  // PM is the top level manager
1873  PM->setTopLevelManager(PM);
1874 }
1875 
1877  delete PM;
1878 }
1879 
1881  PM->add(P);
1882 }
1883 
1884 /// run - Execute all of the passes scheduled for execution. Keep track of
1885 /// whether any of the passes modifies the module, and if so, return true.
1887  return PM->run(M);
1888 }
1889 
1890 //===----------------------------------------------------------------------===//
1891 // PMStack implementation
1892 //
1893 
1894 // Pop Pass Manager from the stack and clear its analysis info.
1896 
1897  PMDataManager *Top = this->top();
1898  Top->initializeAnalysisInfo();
1899 
1900  S.pop_back();
1901 }
1902 
1903 // Push PM on the stack and set its top level manager.
1905  assert(PM && "Unable to push. Pass Manager expected");
1906  assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1907 
1908  if (!this->empty()) {
1909  assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1910  && "pushing bad pass manager to PMStack");
1911  PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1912 
1913  assert(TPM && "Unable to find top level manager");
1914  TPM->addIndirectPassManager(PM);
1915  PM->setTopLevelManager(TPM);
1916  PM->setDepth(this->top()->getDepth()+1);
1917  } else {
1920  && "pushing bad pass manager to PMStack");
1921  PM->setDepth(1);
1922  }
1923 
1924  S.push_back(PM);
1925 }
1926 
1927 // Dump content of the pass manager stack.
1929  for (PMDataManager *Manager : S)
1930  dbgs() << Manager->getAsPass()->getPassName() << ' ';
1931 
1932  if (!S.empty())
1933  dbgs() << '\n';
1934 }
1935 
1936 /// Find appropriate Module Pass Manager in the PM Stack and
1937 /// add self into that manager.
1939  PassManagerType PreferredType) {
1940  // Find Module Pass Manager
1941  while (!PMS.empty()) {
1942  PassManagerType TopPMType = PMS.top()->getPassManagerType();
1943  if (TopPMType == PreferredType)
1944  break; // We found desired pass manager
1945  else if (TopPMType > PMT_ModulePassManager)
1946  PMS.pop(); // Pop children pass managers
1947  else
1948  break;
1949  }
1950  assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1951  PMS.top()->add(this);
1952 }
1953 
1954 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1955 /// in the PM Stack and add self into that manager.
1957  PassManagerType PreferredType) {
1958 
1959  // Find Function Pass Manager
1960  while (!PMS.empty()) {
1962  PMS.pop();
1963  else
1964  break;
1965  }
1966 
1967  // Create new Function Pass Manager if needed.
1968  FPPassManager *FPP;
1970  FPP = (FPPassManager *)PMS.top();
1971  } else {
1972  assert(!PMS.empty() && "Unable to create Function Pass Manager");
1973  PMDataManager *PMD = PMS.top();
1974 
1975  // [1] Create new Function Pass Manager
1976  FPP = new FPPassManager();
1977  FPP->populateInheritedAnalysis(PMS);
1978 
1979  // [2] Set up new manager's top level manager
1980  PMTopLevelManager *TPM = PMD->getTopLevelManager();
1981  TPM->addIndirectPassManager(FPP);
1982 
1983  // [3] Assign manager to manage this new manager. This may create
1984  // and push new managers into PMS
1985  FPP->assignPassManager(PMS, PMD->getPassManagerType());
1986 
1987  // [4] Push new manager into PMS
1988  PMS.push(FPP);
1989  }
1990 
1991  // Assign FPP as the manager of this pass.
1992  FPP->add(this);
1993 }
1994 
1995 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1996 /// in the PM Stack and add self into that manager.
1998  PassManagerType PreferredType) {
1999  BBPassManager *BBP;
2000 
2001  // Basic Pass Manager is a leaf pass manager. It does not handle
2002  // any other pass manager.
2003  if (!PMS.empty() &&
2005  BBP = (BBPassManager *)PMS.top();
2006  } else {
2007  // If leaf manager is not Basic Block Pass manager then create new
2008  // basic Block Pass manager.
2009  assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
2010  PMDataManager *PMD = PMS.top();
2011 
2012  // [1] Create new Basic Block Manager
2013  BBP = new BBPassManager();
2014 
2015  // [2] Set up new manager's top level manager
2016  // Basic Block Pass Manager does not live by itself
2017  PMTopLevelManager *TPM = PMD->getTopLevelManager();
2018  TPM->addIndirectPassManager(BBP);
2019 
2020  // [3] Assign manager to manage this new manager. This may create
2021  // and push new managers into PMS
2022  BBP->assignPassManager(PMS, PreferredType);
2023 
2024  // [4] Push new manager into PMS
2025  PMS.push(BBP);
2026  }
2027 
2028  // Assign BBP as the manager of this pass.
2029  BBP->add(this);
2030 }
2031 
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:80
const PassInfo * getPassInfo(const void *TI) const
getPassInfo - Look up a pass&#39; corresponding PassInfo, indexed by the pass&#39; type identifier (&MyPass::...
bool preserveHigherLevelAnalysis(Pass *P)
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:258
PassManagerType
Different types of internal pass managers.
Definition: Pass.h:53
BBPassManager.
Definition: Pass.h:60
bool shouldPrintAfterPass()
bool forcePrintModuleIR()
forcePrintModuleIR - returns true if IR printing passes should
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:218
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:249
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.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:464
virtual PMDataManager * getAsPMDataManager()
Definition: Pass.cpp:111
virtual void dumpPassStructure(unsigned Offset=0)
Definition: Pass.cpp:67
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
void dumpLastUses(Pass *P, unsigned Offset) const
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
FunctionPassManagerImpl manages FPPassManagers.
bool doInitialization(Module &M) override
doInitialization - Run all of the initializers for the function passes.
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:95
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...
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in this function.
Definition: Function.cpp:196
bool shouldPrintBeforePass()
This is a helper to determine whether to print IR before or after a pass.
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")))
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...
virtual bool doInitialization(Function &)
doInitialization - Virtual method overridden by BasicBlockPass subclasses to do any necessary per-fun...
Definition: Pass.cpp:178
raw_ostream & indent(unsigned NumSpaces)
indent - Insert &#39;NumSpaces&#39; spaces.
PMDataManager * getAsPMDataManager() override
static PassOptionList PrintBefore("print-before", llvm::cl::desc("Print IR before specified passes"), cl::Hidden)
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...
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:37
F(f)
const VectorType & getUsedSet() const
void yield()
Calls the yield callback (if applicable).
static unsigned InstrCount
const VectorType & getRequiredSet() const
PMTopLevelManager(PMDataManager *PMDM)
Initialize top level manager. Create first pass manager.
AnalysisResolver * getResolver() const
Definition: Pass.h:139
virtual void preparePassManager(PMStack &)
Check if available pass managers are suitable for this pass or not.
Definition: Pass.cpp:82
Base class for error info classes.
Definition: Error.h:48
void dumpPassInfo(Pass *P, enum PassDebuggingString S1, enum PassDebuggingString S2, StringRef Msg)
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:74
virtual void initializePass()
initializePass - This method may be overriden by immutable passes to allow them to perform various in...
Definition: Pass.cpp:140
void setResolver(AnalysisResolver *AR)
Definition: Pass.cpp:115
PMTopLevelManager manages LastUser info and collects common APIs used by top level pass managers...
Timer * getPassTimer(Pass *)
Request the timer for this legacy-pass-manager&#39;s pass instance.
void setDepth(unsigned newDepth)
bool doFinalization(Module &M) override
doFinalization - Run all of the finalizers for the function passes.
AnalysisResolver - Simple interface used by Pass objects to pull all analysis information out of pass...
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.
virtual PassManagerType getPotentialPassManagerType() const
Return what kind of Pass Manager can manage this pass.
Definition: Pass.cpp:86
void freePass(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove P.
void dumpPassStructure(unsigned Offset) override
Print passes managed by this manager.
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:243
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:109
unsigned getInstructionCount()
Returns the number of non-debug IR instructions in the module.
Definition: Module.cpp:475
Diagnostic information for optimization analysis remarks.
void verifyPreservedAnalysis(Pass *P)
verifyPreservedAnalysis – Verify analysis presreved by pass P.
static const PassInfo * getPassInfo(StringRef PassName)
void initializeAnalysisInfo()
Initialize available analysis information.
static cl::opt< bool > PrintModuleScope("print-module-scope", cl::desc("When printing IR for print-[before|after]{-all} " "always print a module IR"), cl::init(false), cl::Hidden)
MPPassManager.
Definition: Pass.h:55
virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass)
Add RequiredPass into list of lower level passes required by pass P.
const VectorType & getPreservedSet() const
void populateInheritedAnalysis(PMStack &PMS)
This header defines classes/functions to handle pass execution timing information with interfaces for...
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...
#define clEnumVal(ENUMVAL, DESC)
Definition: CommandLine.h:615
PassManagerPrettyStackEntry - This is used to print informative information about what pass is runnin...
void assignPassManager(PMStack &PMS, PassManagerType T) override
Find appropriate Module Pass Manager in the PM Stack and add self into that manager.
bool isPassDebuggingExecutionsOrMore() const
isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions or higher is specified...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:91
PassManagerType getTopLevelPassManagerType() override
void add(Pass *P, bool ProcessAnalysis=true)
Add pass P into the PassVector.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
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:32
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:183
iterator begin()
Definition: Function.h:655
bool run(Function &F)
run - Execute all of the passes scheduled for execution.
virtual ImmutablePass * getAsImmutablePass()
Definition: Pass.cpp:107
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition: Pass.h:105
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:176
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition: FoldingSet.h:305
void dumpUsedSet(const Pass *P) const
static PassOptionList PrintAfter("print-after", llvm::cl::desc("Print IR after specified passes"), cl::Hidden)
static bool runOnFunction(Function &F, bool PostInlining)
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
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)
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
AnalysisID getPassID() const
getPassID - Return the PassID number that corresponds to this pass.
Definition: Pass.h:99
bool shouldEmitInstrCountChangedRemark()
Return true if size-info optimization remark is enabled, false otherwise.
Definition: Module.h:262
void addIndirectPassManager(PMDataManager *Manager)
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:642
virtual PassManagerType getPassManagerType() const
void collectLastUses(SmallVectorImpl< Pass *> &LastUses, Pass *P)
Collect passes whose last user is P.
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:370
AMDGPU Lower Kernel Arguments
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
const PassInfo * findAnalysisPassInfo(AnalysisID AID) const
Retrieve the PassInfo for an analysis.
Represent the analysis usage information of a pass.
PassManagerImpl manages MPPassManagers.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
void getAnalysisUsage(AnalysisUsage &Info) const override
Pass Manager itself does not invalidate any analysis info.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1213
Pass * getAnalysisIfAvailable(AnalysisID ID, bool Direction) const
Return analysis result or null if it doesn&#39;t exist.
Error materialize()
Make sure this GlobalValue is fully read.
Definition: Globals.cpp:49
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:192
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:30
Used in the streaming interface as the general argument type.
bool doInitialization(Module &M) override
doInitialization - Run all of the initializers for the function passes.
size_t size() const
Definition: SmallVector.h:52
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:209
#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:318
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:209
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 handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:904
print lazy value Lazy Value Info Printer Pass
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:255
void recordAvailableAnalysis(Pass *P)
Augment AvailableAnalysis by adding analysis made available by pass P.
FPPassManager.
Definition: Pass.h:57
FunctionPassManager(Module *M)
FunctionPassManager ctor - This initializes the pass manager.
void dumpRequiredSet(const Pass *P) const
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
void removeNotPreservedAnalysis(Pass *P)
Remove Analysis that is not preserved by the pass.
Module.h This file contains the declarations for the Module class.
static unsigned getDepth(const SmallVectorImpl< const MachineBasicBlock *> &Stack, const MachineBasicBlock *MBB)
typename VectorType::const_iterator const_iterator
Definition: MapVector.h:50
unsigned initSizeRemarkInfo(Module &M, StringMap< std::pair< unsigned, unsigned >> &FunctionToInstrCount)
Set the initial size of the module if the user has specified that they want remarks for size...
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
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:219
const void * AnalysisID
Definition: Pass.h:48
static bool ShouldPrintBeforeOrAfterPass(StringRef PassID, PassOptionList &PassesToPrint)
void clearAnalysisImpls()
Clear cache that is used to connect a pass to the analysis (PassInfo).
Pass * createPass() const
createPass() - Use this method to create an instance of this pass.
Definition: PassInfo.h:96
Pass * findImplPass(AnalysisID PI)
Find pass that is implementing PI.
void setPreservesAll()
Set by analyses that do not transform their input at all.
const VectorType & getRequiredTransitiveSet() const
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.
void setTopLevelManager(PMTopLevelManager *T)
void setLastUser(ArrayRef< Pass *> AnalysisPasses, Pass *P)
Set pass P as the last user of the given analysis passes.
iterator end()
Definition: Module.h:599
Manages a sequence of passes over a particular unit of IR.
Definition: PassManager.h:457
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
PMDataManager & getPMDataManager()
FunctionPass * getContainedPass(unsigned N)
static cl::opt< bool > PrintBeforeAll("print-before-all", llvm::cl::desc("Print IR before each pass"), cl::init(false), cl::Hidden)
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
StringRef getPassName() const
getPassName - Return the friendly name for the pass, never returns null
Definition: PassInfo.h:62
void cleanup()
cleanup - After running all passes, clean up pass manager cache.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
PassDebugLevel
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
iterator begin()
Definition: Module.h:597
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
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.
This file defines passes to print out IR in various granularities.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:205
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.
iterator end()
Definition: MapVector.h:71
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
PMDataManager * top() const
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
virtual Pass * createPrinterPass(raw_ostream &OS, const std::string &Banner) const =0
createPrinterPass - Get a Pass appropriate to print the IR this pass operates on (Module, Function or MachineFunction).
bool run(Function &F)
run - Execute all of the passes scheduled for execution.
MPPassManager * getContainedManager(unsigned N)
bool isAnalysis() const
Definition: PassInfo.h:79
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
const std::vector< const PassInfo * > & getInterfacesImplemented() const
getInterfacesImplemented - Return a list of all of the analysis group interfaces implemented by this ...
Definition: PassInfo.h:113
virtual bool runOnBasicBlock(BasicBlock &BB)=0
runOnBasicBlock - Virtual method overriden by subclasses to do the per-basicblock processing of the p...
unsigned getNumContainedPasses() const
bool empty() const
StringRef getPassArgument() const
getPassArgument - Return the command line option that may be passed to &#39;opt&#39; that will cause this pas...
Definition: PassInfo.h:67
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
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:48
Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const override
createPrinterPass - Get a module printer pass.
PassManager()
Create new pass manager.
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, cl::Hidden)
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1178
static cl::opt< bool > PrintAfterAll("print-after-all", llvm::cl::desc("Print IR after each pass"), cl::init(false), cl::Hidden)
unsigned getDepth() const
bool getPreservesAll() const
Determine whether a pass said it does not transform its input at all.
void dumpPreservedSet(const Pass *P) const
Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const override
createPrinterPass - Get a function printer pass.
void emitInstrCountChangedRemark(Pass *P, Module &M, int64_t Delta, unsigned CountBefore, StringMap< std::pair< unsigned, unsigned >> &FunctionToInstrCount, Function *F=nullptr)
Emit a remark signifying that the number of IR instructions in the module changed.
virtual void assignPassManager(PMStack &, PassManagerType)
Each pass is responsible for assigning a pass manager to itself.
Definition: Pass.h:128
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:1244