LegacyPassManager.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  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. #include "llvm/IR/LegacyPassManager.h"
  13. #include "llvm/ADT/MapVector.h"
  14. #include "llvm/IR/DiagnosticInfo.h"
  15. #include "llvm/IR/IRPrintingPasses.h"
  16. #include "llvm/IR/LLVMContext.h"
  17. #include "llvm/IR/LegacyPassManagers.h"
  18. #include "llvm/IR/Module.h"
  19. #include "llvm/IR/PassTimingInfo.h"
  20. #include "llvm/IR/PrintPasses.h"
  21. #include "llvm/Support/Chrono.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/Error.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/TimeProfiler.h"
  27. #include "llvm/Support/Timer.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <algorithm>
  30. #ifdef EXPENSIVE_CHECKS
  31. #include "llvm/IR/StructuralHash.h"
  32. #endif
  33. using namespace llvm;
  34. // See PassManagers.h for Pass Manager infrastructure overview.
  35. //===----------------------------------------------------------------------===//
  36. // Pass debugging information. Often it is useful to find out what pass is
  37. // running when a crash occurs in a utility. When this library is compiled with
  38. // debugging on, a command line option (--debug-pass) is enabled that causes the
  39. // pass name to be printed before it executes.
  40. //
  41. namespace {
  42. // Different debug levels that can be enabled...
  43. enum PassDebugLevel {
  44. Disabled, Arguments, Structure, Executions, Details
  45. };
  46. } // namespace
  47. static cl::opt<enum PassDebugLevel> PassDebugging(
  48. "debug-pass", cl::Hidden,
  49. cl::desc("Print legacy PassManager debugging information"),
  50. cl::values(clEnumVal(Disabled, "disable debug output"),
  51. clEnumVal(Arguments, "print pass arguments to pass to 'opt'"),
  52. clEnumVal(Structure, "print pass structure before run()"),
  53. clEnumVal(Executions, "print pass name before it is executed"),
  54. clEnumVal(Details, "print pass details when it is executed")));
  55. /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
  56. /// or higher is specified.
  57. bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
  58. return PassDebugging >= Executions;
  59. }
  60. unsigned PMDataManager::initSizeRemarkInfo(
  61. Module &M, StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount) {
  62. // Only calculate getInstructionCount if the size-info remark is requested.
  63. unsigned InstrCount = 0;
  64. // Collect instruction counts for every function. We'll use this to emit
  65. // per-function size remarks later.
  66. for (Function &F : M) {
  67. unsigned FCount = F.getInstructionCount();
  68. // Insert a record into FunctionToInstrCount keeping track of the current
  69. // size of the function as the first member of a pair. Set the second
  70. // member to 0; if the function is deleted by the pass, then when we get
  71. // here, we'll be able to let the user know that F no longer contributes to
  72. // the module.
  73. FunctionToInstrCount[F.getName().str()] =
  74. std::pair<unsigned, unsigned>(FCount, 0);
  75. InstrCount += FCount;
  76. }
  77. return InstrCount;
  78. }
  79. void PMDataManager::emitInstrCountChangedRemark(
  80. Pass *P, Module &M, int64_t Delta, unsigned CountBefore,
  81. StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,
  82. Function *F) {
  83. // If it's a pass manager, don't emit a remark. (This hinges on the assumption
  84. // that the only passes that return non-null with getAsPMDataManager are pass
  85. // managers.) The reason we have to do this is to avoid emitting remarks for
  86. // CGSCC passes.
  87. if (P->getAsPMDataManager())
  88. return;
  89. // Set to true if this isn't a module pass or CGSCC pass.
  90. bool CouldOnlyImpactOneFunction = (F != nullptr);
  91. // Helper lambda that updates the changes to the size of some function.
  92. auto UpdateFunctionChanges =
  93. [&FunctionToInstrCount](Function &MaybeChangedFn) {
  94. // Update the total module count.
  95. unsigned FnSize = MaybeChangedFn.getInstructionCount();
  96. auto It = FunctionToInstrCount.find(MaybeChangedFn.getName());
  97. // If we created a new function, then we need to add it to the map and
  98. // say that it changed from 0 instructions to FnSize.
  99. if (It == FunctionToInstrCount.end()) {
  100. FunctionToInstrCount[MaybeChangedFn.getName()] =
  101. std::pair<unsigned, unsigned>(0, FnSize);
  102. return;
  103. }
  104. // Insert the new function size into the second member of the pair. This
  105. // tells us whether or not this function changed in size.
  106. It->second.second = FnSize;
  107. };
  108. // We need to initially update all of the function sizes.
  109. // If no function was passed in, then we're either a module pass or an
  110. // CGSCC pass.
  111. if (!CouldOnlyImpactOneFunction)
  112. std::for_each(M.begin(), M.end(), UpdateFunctionChanges);
  113. else
  114. UpdateFunctionChanges(*F);
  115. // Do we have a function we can use to emit a remark?
  116. if (!CouldOnlyImpactOneFunction) {
  117. // We need a function containing at least one basic block in order to output
  118. // remarks. Since it's possible that the first function in the module
  119. // doesn't actually contain a basic block, we have to go and find one that's
  120. // suitable for emitting remarks.
  121. auto It = llvm::find_if(M, [](const Function &Fn) { return !Fn.empty(); });
  122. // Didn't find a function. Quit.
  123. if (It == M.end())
  124. return;
  125. // We found a function containing at least one basic block.
  126. F = &*It;
  127. }
  128. int64_t CountAfter = static_cast<int64_t>(CountBefore) + Delta;
  129. BasicBlock &BB = *F->begin();
  130. OptimizationRemarkAnalysis R("size-info", "IRSizeChange",
  131. DiagnosticLocation(), &BB);
  132. // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
  133. // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
  134. R << DiagnosticInfoOptimizationBase::Argument("Pass", P->getPassName())
  135. << ": IR instruction count changed from "
  136. << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)
  137. << " to "
  138. << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)
  139. << "; Delta: "
  140. << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);
  141. F->getContext().diagnose(R); // Not using ORE for layering reasons.
  142. // Emit per-function size change remarks separately.
  143. std::string PassName = P->getPassName().str();
  144. // Helper lambda that emits a remark when the size of a function has changed.
  145. auto EmitFunctionSizeChangedRemark = [&FunctionToInstrCount, &F, &BB,
  146. &PassName](StringRef Fname) {
  147. unsigned FnCountBefore, FnCountAfter;
  148. std::pair<unsigned, unsigned> &Change = FunctionToInstrCount[Fname];
  149. std::tie(FnCountBefore, FnCountAfter) = Change;
  150. int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
  151. static_cast<int64_t>(FnCountBefore);
  152. if (FnDelta == 0)
  153. return;
  154. // FIXME: We shouldn't use BB for the location here. Unfortunately, because
  155. // the function that we're looking at could have been deleted, we can't use
  156. // it for the source location. We *want* remarks when a function is deleted
  157. // though, so we're kind of stuck here as is. (This remark, along with the
  158. // whole-module size change remarks really ought not to have source
  159. // locations at all.)
  160. OptimizationRemarkAnalysis FR("size-info", "FunctionIRSizeChange",
  161. DiagnosticLocation(), &BB);
  162. FR << DiagnosticInfoOptimizationBase::Argument("Pass", PassName)
  163. << ": Function: "
  164. << DiagnosticInfoOptimizationBase::Argument("Function", Fname)
  165. << ": IR instruction count changed from "
  166. << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore",
  167. FnCountBefore)
  168. << " to "
  169. << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter",
  170. FnCountAfter)
  171. << "; Delta: "
  172. << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta);
  173. F->getContext().diagnose(FR);
  174. // Update the function size.
  175. Change.first = FnCountAfter;
  176. };
  177. // Are we looking at more than one function? If so, emit remarks for all of
  178. // the functions in the module. Otherwise, only emit one remark.
  179. if (!CouldOnlyImpactOneFunction)
  180. std::for_each(FunctionToInstrCount.keys().begin(),
  181. FunctionToInstrCount.keys().end(),
  182. EmitFunctionSizeChangedRemark);
  183. else
  184. EmitFunctionSizeChangedRemark(F->getName().str());
  185. }
  186. void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
  187. if (!V && !M)
  188. OS << "Releasing pass '";
  189. else
  190. OS << "Running pass '";
  191. OS << P->getPassName() << "'";
  192. if (M) {
  193. OS << " on module '" << M->getModuleIdentifier() << "'.\n";
  194. return;
  195. }
  196. if (!V) {
  197. OS << '\n';
  198. return;
  199. }
  200. OS << " on ";
  201. if (isa<Function>(V))
  202. OS << "function";
  203. else if (isa<BasicBlock>(V))
  204. OS << "basic block";
  205. else
  206. OS << "value";
  207. OS << " '";
  208. V->printAsOperand(OS, /*PrintType=*/false, M);
  209. OS << "'\n";
  210. }
  211. namespace llvm {
  212. namespace legacy {
  213. bool debugPassSpecified() { return PassDebugging != Disabled; }
  214. //===----------------------------------------------------------------------===//
  215. // FunctionPassManagerImpl
  216. //
  217. /// FunctionPassManagerImpl manages FPPassManagers
  218. class FunctionPassManagerImpl : public Pass,
  219. public PMDataManager,
  220. public PMTopLevelManager {
  221. virtual void anchor();
  222. private:
  223. bool wasRun;
  224. public:
  225. static char ID;
  226. explicit FunctionPassManagerImpl()
  227. : Pass(PT_PassManager, ID), PMTopLevelManager(new FPPassManager()),
  228. wasRun(false) {}
  229. /// \copydoc FunctionPassManager::add()
  230. void add(Pass *P) {
  231. schedulePass(P);
  232. }
  233. /// createPrinterPass - Get a function printer pass.
  234. Pass *createPrinterPass(raw_ostream &O,
  235. const std::string &Banner) const override {
  236. return createPrintFunctionPass(O, Banner);
  237. }
  238. // Prepare for running an on the fly pass, freeing memory if needed
  239. // from a previous run.
  240. void releaseMemoryOnTheFly();
  241. /// run - Execute all of the passes scheduled for execution. Keep track of
  242. /// whether any of the passes modifies the module, and if so, return true.
  243. bool run(Function &F);
  244. /// doInitialization - Run all of the initializers for the function passes.
  245. ///
  246. bool doInitialization(Module &M) override;
  247. /// doFinalization - Run all of the finalizers for the function passes.
  248. ///
  249. bool doFinalization(Module &M) override;
  250. PMDataManager *getAsPMDataManager() override { return this; }
  251. Pass *getAsPass() override { return this; }
  252. PassManagerType getTopLevelPassManagerType() override {
  253. return PMT_FunctionPassManager;
  254. }
  255. /// Pass Manager itself does not invalidate any analysis info.
  256. void getAnalysisUsage(AnalysisUsage &Info) const override {
  257. Info.setPreservesAll();
  258. }
  259. FPPassManager *getContainedManager(unsigned N) {
  260. assert(N < PassManagers.size() && "Pass number out of range!");
  261. FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
  262. return FP;
  263. }
  264. void dumpPassStructure(unsigned Offset) override {
  265. for (unsigned I = 0; I < getNumContainedManagers(); ++I)
  266. getContainedManager(I)->dumpPassStructure(Offset);
  267. }
  268. };
  269. void FunctionPassManagerImpl::anchor() {}
  270. char FunctionPassManagerImpl::ID = 0;
  271. //===----------------------------------------------------------------------===//
  272. // FunctionPassManagerImpl implementation
  273. //
  274. bool FunctionPassManagerImpl::doInitialization(Module &M) {
  275. bool Changed = false;
  276. dumpArguments();
  277. dumpPasses();
  278. for (ImmutablePass *ImPass : getImmutablePasses())
  279. Changed |= ImPass->doInitialization(M);
  280. for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
  281. Changed |= getContainedManager(Index)->doInitialization(M);
  282. return Changed;
  283. }
  284. bool FunctionPassManagerImpl::doFinalization(Module &M) {
  285. bool Changed = false;
  286. for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
  287. Changed |= getContainedManager(Index)->doFinalization(M);
  288. for (ImmutablePass *ImPass : getImmutablePasses())
  289. Changed |= ImPass->doFinalization(M);
  290. return Changed;
  291. }
  292. void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
  293. if (!wasRun)
  294. return;
  295. for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
  296. FPPassManager *FPPM = getContainedManager(Index);
  297. for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
  298. FPPM->getContainedPass(Index)->releaseMemory();
  299. }
  300. }
  301. wasRun = false;
  302. }
  303. // Execute all the passes managed by this top level manager.
  304. // Return true if any function is modified by a pass.
  305. bool FunctionPassManagerImpl::run(Function &F) {
  306. bool Changed = false;
  307. initializeAllAnalysisInfo();
  308. for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
  309. Changed |= getContainedManager(Index)->runOnFunction(F);
  310. F.getContext().yield();
  311. }
  312. for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
  313. getContainedManager(Index)->cleanup();
  314. wasRun = true;
  315. return Changed;
  316. }
  317. } // namespace legacy
  318. } // namespace llvm
  319. namespace {
  320. //===----------------------------------------------------------------------===//
  321. // MPPassManager
  322. //
  323. /// MPPassManager manages ModulePasses and function pass managers.
  324. /// It batches all Module passes and function pass managers together and
  325. /// sequences them to process one module.
  326. class MPPassManager : public Pass, public PMDataManager {
  327. public:
  328. static char ID;
  329. explicit MPPassManager() : Pass(PT_PassManager, ID) {}
  330. // Delete on the fly managers.
  331. ~MPPassManager() override {
  332. for (auto &OnTheFlyManager : OnTheFlyManagers) {
  333. legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
  334. delete FPP;
  335. }
  336. }
  337. /// createPrinterPass - Get a module printer pass.
  338. Pass *createPrinterPass(raw_ostream &O,
  339. const std::string &Banner) const override {
  340. return createPrintModulePass(O, Banner);
  341. }
  342. /// run - Execute all of the passes scheduled for execution. Keep track of
  343. /// whether any of the passes modifies the module, and if so, return true.
  344. bool runOnModule(Module &M);
  345. using llvm::Pass::doInitialization;
  346. using llvm::Pass::doFinalization;
  347. /// Pass Manager itself does not invalidate any analysis info.
  348. void getAnalysisUsage(AnalysisUsage &Info) const override {
  349. Info.setPreservesAll();
  350. }
  351. /// Add RequiredPass into list of lower level passes required by pass P.
  352. /// RequiredPass is run on the fly by Pass Manager when P requests it
  353. /// through getAnalysis interface.
  354. void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
  355. /// Return function pass corresponding to PassInfo PI, that is
  356. /// required by module pass MP. Instantiate analysis pass, by using
  357. /// its runOnFunction() for function F.
  358. std::tuple<Pass *, bool> getOnTheFlyPass(Pass *MP, AnalysisID PI,
  359. Function &F) override;
  360. StringRef getPassName() const override { return "Module Pass Manager"; }
  361. PMDataManager *getAsPMDataManager() override { return this; }
  362. Pass *getAsPass() override { return this; }
  363. // Print passes managed by this manager
  364. void dumpPassStructure(unsigned Offset) override {
  365. dbgs().indent(Offset*2) << "ModulePass Manager\n";
  366. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  367. ModulePass *MP = getContainedPass(Index);
  368. MP->dumpPassStructure(Offset + 1);
  369. MapVector<Pass *, legacy::FunctionPassManagerImpl *>::const_iterator I =
  370. OnTheFlyManagers.find(MP);
  371. if (I != OnTheFlyManagers.end())
  372. I->second->dumpPassStructure(Offset + 2);
  373. dumpLastUses(MP, Offset+1);
  374. }
  375. }
  376. ModulePass *getContainedPass(unsigned N) {
  377. assert(N < PassVector.size() && "Pass number out of range!");
  378. return static_cast<ModulePass *>(PassVector[N]);
  379. }
  380. PassManagerType getPassManagerType() const override {
  381. return PMT_ModulePassManager;
  382. }
  383. private:
  384. /// Collection of on the fly FPPassManagers. These managers manage
  385. /// function passes that are required by module passes.
  386. MapVector<Pass *, legacy::FunctionPassManagerImpl *> OnTheFlyManagers;
  387. };
  388. char MPPassManager::ID = 0;
  389. } // End anonymous namespace
  390. namespace llvm {
  391. namespace legacy {
  392. //===----------------------------------------------------------------------===//
  393. // PassManagerImpl
  394. //
  395. /// PassManagerImpl manages MPPassManagers
  396. class PassManagerImpl : public Pass,
  397. public PMDataManager,
  398. public PMTopLevelManager {
  399. virtual void anchor();
  400. public:
  401. static char ID;
  402. explicit PassManagerImpl()
  403. : Pass(PT_PassManager, ID), PMTopLevelManager(new MPPassManager()) {}
  404. /// \copydoc PassManager::add()
  405. void add(Pass *P) {
  406. schedulePass(P);
  407. }
  408. /// createPrinterPass - Get a module printer pass.
  409. Pass *createPrinterPass(raw_ostream &O,
  410. const std::string &Banner) const override {
  411. return createPrintModulePass(O, Banner);
  412. }
  413. /// run - Execute all of the passes scheduled for execution. Keep track of
  414. /// whether any of the passes modifies the module, and if so, return true.
  415. bool run(Module &M);
  416. using llvm::Pass::doInitialization;
  417. using llvm::Pass::doFinalization;
  418. /// Pass Manager itself does not invalidate any analysis info.
  419. void getAnalysisUsage(AnalysisUsage &Info) const override {
  420. Info.setPreservesAll();
  421. }
  422. PMDataManager *getAsPMDataManager() override { return this; }
  423. Pass *getAsPass() override { return this; }
  424. PassManagerType getTopLevelPassManagerType() override {
  425. return PMT_ModulePassManager;
  426. }
  427. MPPassManager *getContainedManager(unsigned N) {
  428. assert(N < PassManagers.size() && "Pass number out of range!");
  429. MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
  430. return MP;
  431. }
  432. };
  433. void PassManagerImpl::anchor() {}
  434. char PassManagerImpl::ID = 0;
  435. //===----------------------------------------------------------------------===//
  436. // PassManagerImpl implementation
  437. //
  438. /// run - Execute all of the passes scheduled for execution. Keep track of
  439. /// whether any of the passes modifies the module, and if so, return true.
  440. bool PassManagerImpl::run(Module &M) {
  441. bool Changed = false;
  442. dumpArguments();
  443. dumpPasses();
  444. for (ImmutablePass *ImPass : getImmutablePasses())
  445. Changed |= ImPass->doInitialization(M);
  446. initializeAllAnalysisInfo();
  447. for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
  448. Changed |= getContainedManager(Index)->runOnModule(M);
  449. M.getContext().yield();
  450. }
  451. for (ImmutablePass *ImPass : getImmutablePasses())
  452. Changed |= ImPass->doFinalization(M);
  453. return Changed;
  454. }
  455. } // namespace legacy
  456. } // namespace llvm
  457. //===----------------------------------------------------------------------===//
  458. // PMTopLevelManager implementation
  459. /// Initialize top level manager. Create first pass manager.
  460. PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
  461. PMDM->setTopLevelManager(this);
  462. addPassManager(PMDM);
  463. activeStack.push(PMDM);
  464. }
  465. /// Set pass P as the last user of the given analysis passes.
  466. void
  467. PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
  468. unsigned PDepth = 0;
  469. if (P->getResolver())
  470. PDepth = P->getResolver()->getPMDataManager().getDepth();
  471. for (Pass *AP : AnalysisPasses) {
  472. // Record P as the new last user of AP.
  473. auto &LastUserOfAP = LastUser[AP];
  474. if (LastUserOfAP)
  475. InversedLastUser[LastUserOfAP].erase(AP);
  476. LastUserOfAP = P;
  477. InversedLastUser[P].insert(AP);
  478. if (P == AP)
  479. continue;
  480. // Update the last users of passes that are required transitive by AP.
  481. AnalysisUsage *AnUsage = findAnalysisUsage(AP);
  482. const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
  483. SmallVector<Pass *, 12> LastUses;
  484. SmallVector<Pass *, 12> LastPMUses;
  485. for (AnalysisID ID : IDs) {
  486. Pass *AnalysisPass = findAnalysisPass(ID);
  487. assert(AnalysisPass && "Expected analysis pass to exist.");
  488. AnalysisResolver *AR = AnalysisPass->getResolver();
  489. assert(AR && "Expected analysis resolver to exist.");
  490. unsigned APDepth = AR->getPMDataManager().getDepth();
  491. if (PDepth == APDepth)
  492. LastUses.push_back(AnalysisPass);
  493. else if (PDepth > APDepth)
  494. LastPMUses.push_back(AnalysisPass);
  495. }
  496. setLastUser(LastUses, P);
  497. // If this pass has a corresponding pass manager, push higher level
  498. // analysis to this pass manager.
  499. if (P->getResolver())
  500. setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
  501. // If AP is the last user of other passes then make P last user of
  502. // such passes.
  503. auto &LastUsedByAP = InversedLastUser[AP];
  504. for (Pass *L : LastUsedByAP)
  505. LastUser[L] = P;
  506. InversedLastUser[P].insert(LastUsedByAP.begin(), LastUsedByAP.end());
  507. LastUsedByAP.clear();
  508. }
  509. }
  510. /// Collect passes whose last user is P
  511. void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
  512. Pass *P) {
  513. auto DMI = InversedLastUser.find(P);
  514. if (DMI == InversedLastUser.end())
  515. return;
  516. auto &LU = DMI->second;
  517. LastUses.append(LU.begin(), LU.end());
  518. }
  519. AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
  520. AnalysisUsage *AnUsage = nullptr;
  521. auto DMI = AnUsageMap.find(P);
  522. if (DMI != AnUsageMap.end())
  523. AnUsage = DMI->second;
  524. else {
  525. // Look up the analysis usage from the pass instance (different instances
  526. // of the same pass can produce different results), but unique the
  527. // resulting object to reduce memory usage. This helps to greatly reduce
  528. // memory usage when we have many instances of only a few pass types
  529. // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
  530. // of dependencies.
  531. AnalysisUsage AU;
  532. P->getAnalysisUsage(AU);
  533. AUFoldingSetNode* Node = nullptr;
  534. FoldingSetNodeID ID;
  535. AUFoldingSetNode::Profile(ID, AU);
  536. void *IP = nullptr;
  537. if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
  538. Node = N;
  539. else {
  540. Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
  541. UniqueAnalysisUsages.InsertNode(Node, IP);
  542. }
  543. assert(Node && "cached analysis usage must be non null");
  544. AnUsageMap[P] = &Node->AU;
  545. AnUsage = &Node->AU;
  546. }
  547. return AnUsage;
  548. }
  549. /// Schedule pass P for execution. Make sure that passes required by
  550. /// P are run before P is run. Update analysis info maintained by
  551. /// the manager. Remove dead passes. This is a recursive function.
  552. void PMTopLevelManager::schedulePass(Pass *P) {
  553. // TODO : Allocate function manager for this pass, other wise required set
  554. // may be inserted into previous function manager
  555. // Give pass a chance to prepare the stage.
  556. P->preparePassManager(activeStack);
  557. // If P is an analysis pass and it is available then do not
  558. // generate the analysis again. Stale analysis info should not be
  559. // available at this point.
  560. const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
  561. if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
  562. // Remove any cached AnalysisUsage information.
  563. AnUsageMap.erase(P);
  564. delete P;
  565. return;
  566. }
  567. AnalysisUsage *AnUsage = findAnalysisUsage(P);
  568. bool checkAnalysis = true;
  569. while (checkAnalysis) {
  570. checkAnalysis = false;
  571. const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
  572. for (const AnalysisID ID : RequiredSet) {
  573. Pass *AnalysisPass = findAnalysisPass(ID);
  574. if (!AnalysisPass) {
  575. const PassInfo *PI = findAnalysisPassInfo(ID);
  576. if (!PI) {
  577. // Pass P is not in the global PassRegistry
  578. dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
  579. dbgs() << "Verify if there is a pass dependency cycle." << "\n";
  580. dbgs() << "Required Passes:" << "\n";
  581. for (const AnalysisID ID2 : RequiredSet) {
  582. if (ID == ID2)
  583. break;
  584. Pass *AnalysisPass2 = findAnalysisPass(ID2);
  585. if (AnalysisPass2) {
  586. dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
  587. } else {
  588. dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
  589. dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
  590. dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
  591. }
  592. }
  593. }
  594. assert(PI && "Expected required passes to be initialized");
  595. AnalysisPass = PI->createPass();
  596. if (P->getPotentialPassManagerType () ==
  597. AnalysisPass->getPotentialPassManagerType())
  598. // Schedule analysis pass that is managed by the same pass manager.
  599. schedulePass(AnalysisPass);
  600. else if (P->getPotentialPassManagerType () >
  601. AnalysisPass->getPotentialPassManagerType()) {
  602. // Schedule analysis pass that is managed by a new manager.
  603. schedulePass(AnalysisPass);
  604. // Recheck analysis passes to ensure that required analyses that
  605. // are already checked are still available.
  606. checkAnalysis = true;
  607. } else
  608. // Do not schedule this analysis. Lower level analysis
  609. // passes are run on the fly.
  610. delete AnalysisPass;
  611. }
  612. }
  613. }
  614. // Now all required passes are available.
  615. if (ImmutablePass *IP = P->getAsImmutablePass()) {
  616. // P is a immutable pass and it will be managed by this
  617. // top level manager. Set up analysis resolver to connect them.
  618. PMDataManager *DM = getAsPMDataManager();
  619. AnalysisResolver *AR = new AnalysisResolver(*DM);
  620. P->setResolver(AR);
  621. DM->initializeAnalysisImpl(P);
  622. addImmutablePass(IP);
  623. DM->recordAvailableAnalysis(IP);
  624. return;
  625. }
  626. if (PI && !PI->isAnalysis() && shouldPrintBeforePass(PI->getPassArgument())) {
  627. Pass *PP =
  628. P->createPrinterPass(dbgs(), ("*** IR Dump Before " + P->getPassName() +
  629. " (" + PI->getPassArgument() + ") ***")
  630. .str());
  631. PP->assignPassManager(activeStack, getTopLevelPassManagerType());
  632. }
  633. // Add the requested pass to the best available pass manager.
  634. P->assignPassManager(activeStack, getTopLevelPassManagerType());
  635. if (PI && !PI->isAnalysis() && shouldPrintAfterPass(PI->getPassArgument())) {
  636. Pass *PP =
  637. P->createPrinterPass(dbgs(), ("*** IR Dump After " + P->getPassName() +
  638. " (" + PI->getPassArgument() + ") ***")
  639. .str());
  640. PP->assignPassManager(activeStack, getTopLevelPassManagerType());
  641. }
  642. }
  643. /// Find the pass that implements Analysis AID. Search immutable
  644. /// passes and all pass managers. If desired pass is not found
  645. /// then return NULL.
  646. Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
  647. // For immutable passes we have a direct mapping from ID to pass, so check
  648. // that first.
  649. if (Pass *P = ImmutablePassMap.lookup(AID))
  650. return P;
  651. // Check pass managers
  652. for (PMDataManager *PassManager : PassManagers)
  653. if (Pass *P = PassManager->findAnalysisPass(AID, false))
  654. return P;
  655. // Check other pass managers
  656. for (PMDataManager *IndirectPassManager : IndirectPassManagers)
  657. if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
  658. return P;
  659. return nullptr;
  660. }
  661. const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
  662. const PassInfo *&PI = AnalysisPassInfos[AID];
  663. if (!PI)
  664. PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
  665. else
  666. assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
  667. "The pass info pointer changed for an analysis ID!");
  668. return PI;
  669. }
  670. void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
  671. P->initializePass();
  672. ImmutablePasses.push_back(P);
  673. // Add this pass to the map from its analysis ID. We clobber any prior runs
  674. // of the pass in the map so that the last one added is the one found when
  675. // doing lookups.
  676. AnalysisID AID = P->getPassID();
  677. ImmutablePassMap[AID] = P;
  678. // Also add any interfaces implemented by the immutable pass to the map for
  679. // fast lookup.
  680. const PassInfo *PassInf = findAnalysisPassInfo(AID);
  681. assert(PassInf && "Expected all immutable passes to be initialized");
  682. for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
  683. ImmutablePassMap[ImmPI->getTypeInfo()] = P;
  684. }
  685. // Print passes managed by this top level manager.
  686. void PMTopLevelManager::dumpPasses() const {
  687. if (PassDebugging < Structure)
  688. return;
  689. // Print out the immutable passes
  690. for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
  691. ImmutablePasses[i]->dumpPassStructure(0);
  692. }
  693. // Every class that derives from PMDataManager also derives from Pass
  694. // (sometimes indirectly), but there's no inheritance relationship
  695. // between PMDataManager and Pass, so we have to getAsPass to get
  696. // from a PMDataManager* to a Pass*.
  697. for (PMDataManager *Manager : PassManagers)
  698. Manager->getAsPass()->dumpPassStructure(1);
  699. }
  700. void PMTopLevelManager::dumpArguments() const {
  701. if (PassDebugging < Arguments)
  702. return;
  703. dbgs() << "Pass Arguments: ";
  704. for (ImmutablePass *P : ImmutablePasses)
  705. if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
  706. assert(PI && "Expected all immutable passes to be initialized");
  707. if (!PI->isAnalysisGroup())
  708. dbgs() << " -" << PI->getPassArgument();
  709. }
  710. for (PMDataManager *PM : PassManagers)
  711. PM->dumpPassArguments();
  712. dbgs() << "\n";
  713. }
  714. void PMTopLevelManager::initializeAllAnalysisInfo() {
  715. for (PMDataManager *PM : PassManagers)
  716. PM->initializeAnalysisInfo();
  717. // Initailize other pass managers
  718. for (PMDataManager *IPM : IndirectPassManagers)
  719. IPM->initializeAnalysisInfo();
  720. }
  721. /// Destructor
  722. PMTopLevelManager::~PMTopLevelManager() {
  723. for (PMDataManager *PM : PassManagers)
  724. delete PM;
  725. for (ImmutablePass *P : ImmutablePasses)
  726. delete P;
  727. }
  728. //===----------------------------------------------------------------------===//
  729. // PMDataManager implementation
  730. /// Augement AvailableAnalysis by adding analysis made available by pass P.
  731. void PMDataManager::recordAvailableAnalysis(Pass *P) {
  732. AnalysisID PI = P->getPassID();
  733. AvailableAnalysis[PI] = P;
  734. assert(!AvailableAnalysis.empty());
  735. // This pass is the current implementation of all of the interfaces it
  736. // implements as well.
  737. const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
  738. if (!PInf) return;
  739. for (const PassInfo *PI : PInf->getInterfacesImplemented())
  740. AvailableAnalysis[PI->getTypeInfo()] = P;
  741. }
  742. // Return true if P preserves high level analysis used by other
  743. // passes managed by this manager
  744. bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
  745. AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
  746. if (AnUsage->getPreservesAll())
  747. return true;
  748. const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
  749. for (Pass *P1 : HigherLevelAnalysis) {
  750. if (P1->getAsImmutablePass() == nullptr &&
  751. !is_contained(PreservedSet, P1->getPassID()))
  752. return false;
  753. }
  754. return true;
  755. }
  756. /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
  757. void PMDataManager::verifyPreservedAnalysis(Pass *P) {
  758. // Don't do this unless assertions are enabled.
  759. #ifdef NDEBUG
  760. return;
  761. #endif
  762. AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
  763. const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
  764. // Verify preserved analysis
  765. for (AnalysisID AID : PreservedSet) {
  766. if (Pass *AP = findAnalysisPass(AID, true)) {
  767. TimeRegion PassTimer(getPassTimer(AP));
  768. AP->verifyAnalysis();
  769. }
  770. }
  771. }
  772. /// Remove Analysis not preserved by Pass P
  773. void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
  774. AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
  775. if (AnUsage->getPreservesAll())
  776. return;
  777. const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
  778. for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
  779. E = AvailableAnalysis.end(); I != E; ) {
  780. DenseMap<AnalysisID, Pass*>::iterator Info = I++;
  781. if (Info->second->getAsImmutablePass() == nullptr &&
  782. !is_contained(PreservedSet, Info->first)) {
  783. // Remove this analysis
  784. if (PassDebugging >= Details) {
  785. Pass *S = Info->second;
  786. dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
  787. dbgs() << S->getPassName() << "'\n";
  788. }
  789. AvailableAnalysis.erase(Info);
  790. }
  791. }
  792. // Check inherited analysis also. If P is not preserving analysis
  793. // provided by parent manager then remove it here.
  794. for (DenseMap<AnalysisID, Pass *> *IA : InheritedAnalysis) {
  795. if (!IA)
  796. continue;
  797. for (DenseMap<AnalysisID, Pass *>::iterator I = IA->begin(),
  798. E = IA->end();
  799. I != E;) {
  800. DenseMap<AnalysisID, Pass *>::iterator Info = I++;
  801. if (Info->second->getAsImmutablePass() == nullptr &&
  802. !is_contained(PreservedSet, Info->first)) {
  803. // Remove this analysis
  804. if (PassDebugging >= Details) {
  805. Pass *S = Info->second;
  806. dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
  807. dbgs() << S->getPassName() << "'\n";
  808. }
  809. IA->erase(Info);
  810. }
  811. }
  812. }
  813. }
  814. /// Remove analysis passes that are not used any longer
  815. void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
  816. enum PassDebuggingString DBG_STR) {
  817. SmallVector<Pass *, 12> DeadPasses;
  818. // If this is a on the fly manager then it does not have TPM.
  819. if (!TPM)
  820. return;
  821. TPM->collectLastUses(DeadPasses, P);
  822. if (PassDebugging >= Details && !DeadPasses.empty()) {
  823. dbgs() << " -*- '" << P->getPassName();
  824. dbgs() << "' is the last user of following pass instances.";
  825. dbgs() << " Free these instances\n";
  826. }
  827. for (Pass *P : DeadPasses)
  828. freePass(P, Msg, DBG_STR);
  829. }
  830. void PMDataManager::freePass(Pass *P, StringRef Msg,
  831. enum PassDebuggingString DBG_STR) {
  832. dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
  833. {
  834. // If the pass crashes releasing memory, remember this.
  835. PassManagerPrettyStackEntry X(P);
  836. TimeRegion PassTimer(getPassTimer(P));
  837. P->releaseMemory();
  838. }
  839. AnalysisID PI = P->getPassID();
  840. if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
  841. // Remove the pass itself (if it is not already removed).
  842. AvailableAnalysis.erase(PI);
  843. // Remove all interfaces this pass implements, for which it is also
  844. // listed as the available implementation.
  845. for (const PassInfo *PI : PInf->getInterfacesImplemented()) {
  846. DenseMap<AnalysisID, Pass *>::iterator Pos =
  847. AvailableAnalysis.find(PI->getTypeInfo());
  848. if (Pos != AvailableAnalysis.end() && Pos->second == P)
  849. AvailableAnalysis.erase(Pos);
  850. }
  851. }
  852. }
  853. /// Add pass P into the PassVector. Update
  854. /// AvailableAnalysis appropriately if ProcessAnalysis is true.
  855. void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
  856. // This manager is going to manage pass P. Set up analysis resolver
  857. // to connect them.
  858. AnalysisResolver *AR = new AnalysisResolver(*this);
  859. P->setResolver(AR);
  860. // If a FunctionPass F is the last user of ModulePass info M
  861. // then the F's manager, not F, records itself as a last user of M.
  862. SmallVector<Pass *, 12> TransferLastUses;
  863. if (!ProcessAnalysis) {
  864. // Add pass
  865. PassVector.push_back(P);
  866. return;
  867. }
  868. // At the moment, this pass is the last user of all required passes.
  869. SmallVector<Pass *, 12> LastUses;
  870. SmallVector<Pass *, 8> UsedPasses;
  871. SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
  872. unsigned PDepth = this->getDepth();
  873. collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
  874. for (Pass *PUsed : UsedPasses) {
  875. unsigned RDepth = 0;
  876. assert(PUsed->getResolver() && "Analysis Resolver is not set");
  877. PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
  878. RDepth = DM.getDepth();
  879. if (PDepth == RDepth)
  880. LastUses.push_back(PUsed);
  881. else if (PDepth > RDepth) {
  882. // Let the parent claim responsibility of last use
  883. TransferLastUses.push_back(PUsed);
  884. // Keep track of higher level analysis used by this manager.
  885. HigherLevelAnalysis.push_back(PUsed);
  886. } else
  887. llvm_unreachable("Unable to accommodate Used Pass");
  888. }
  889. // Set P as P's last user until someone starts using P.
  890. // However, if P is a Pass Manager then it does not need
  891. // to record its last user.
  892. if (!P->getAsPMDataManager())
  893. LastUses.push_back(P);
  894. TPM->setLastUser(LastUses, P);
  895. if (!TransferLastUses.empty()) {
  896. Pass *My_PM = getAsPass();
  897. TPM->setLastUser(TransferLastUses, My_PM);
  898. TransferLastUses.clear();
  899. }
  900. // Now, take care of required analyses that are not available.
  901. for (AnalysisID ID : ReqAnalysisNotAvailable) {
  902. const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
  903. Pass *AnalysisPass = PI->createPass();
  904. this->addLowerLevelRequiredPass(P, AnalysisPass);
  905. }
  906. // Take a note of analysis required and made available by this pass.
  907. // Remove the analysis not preserved by this pass
  908. removeNotPreservedAnalysis(P);
  909. recordAvailableAnalysis(P);
  910. // Add pass
  911. PassVector.push_back(P);
  912. }
  913. /// Populate UP with analysis pass that are used or required by
  914. /// pass P and are available. Populate RP_NotAvail with analysis
  915. /// pass that are required by pass P but are not available.
  916. void PMDataManager::collectRequiredAndUsedAnalyses(
  917. SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
  918. Pass *P) {
  919. AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
  920. for (const auto &UsedID : AnUsage->getUsedSet())
  921. if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
  922. UP.push_back(AnalysisPass);
  923. for (const auto &RequiredID : AnUsage->getRequiredSet())
  924. if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
  925. UP.push_back(AnalysisPass);
  926. else
  927. RP_NotAvail.push_back(RequiredID);
  928. }
  929. // All Required analyses should be available to the pass as it runs! Here
  930. // we fill in the AnalysisImpls member of the pass so that it can
  931. // successfully use the getAnalysis() method to retrieve the
  932. // implementations it needs.
  933. //
  934. void PMDataManager::initializeAnalysisImpl(Pass *P) {
  935. AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
  936. for (const AnalysisID ID : AnUsage->getRequiredSet()) {
  937. Pass *Impl = findAnalysisPass(ID, true);
  938. if (!Impl)
  939. // This may be analysis pass that is initialized on the fly.
  940. // If that is not the case then it will raise an assert when it is used.
  941. continue;
  942. AnalysisResolver *AR = P->getResolver();
  943. assert(AR && "Analysis Resolver is not set");
  944. AR->addAnalysisImplsPair(ID, Impl);
  945. }
  946. }
  947. /// Find the pass that implements Analysis AID. If desired pass is not found
  948. /// then return NULL.
  949. Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
  950. // Check if AvailableAnalysis map has one entry.
  951. DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
  952. if (I != AvailableAnalysis.end())
  953. return I->second;
  954. // Search Parents through TopLevelManager
  955. if (SearchParent)
  956. return TPM->findAnalysisPass(AID);
  957. return nullptr;
  958. }
  959. // Print list of passes that are last used by P.
  960. void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
  961. if (PassDebugging < Details)
  962. return;
  963. SmallVector<Pass *, 12> LUses;
  964. // If this is a on the fly manager then it does not have TPM.
  965. if (!TPM)
  966. return;
  967. TPM->collectLastUses(LUses, P);
  968. for (Pass *P : LUses) {
  969. dbgs() << "--" << std::string(Offset*2, ' ');
  970. P->dumpPassStructure(0);
  971. }
  972. }
  973. void PMDataManager::dumpPassArguments() const {
  974. for (Pass *P : PassVector) {
  975. if (PMDataManager *PMD = P->getAsPMDataManager())
  976. PMD->dumpPassArguments();
  977. else
  978. if (const PassInfo *PI =
  979. TPM->findAnalysisPassInfo(P->getPassID()))
  980. if (!PI->isAnalysisGroup())
  981. dbgs() << " -" << PI->getPassArgument();
  982. }
  983. }
  984. void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
  985. enum PassDebuggingString S2,
  986. StringRef Msg) {
  987. if (PassDebugging < Executions)
  988. return;
  989. dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
  990. << std::string(getDepth() * 2 + 1, ' ');
  991. switch (S1) {
  992. case EXECUTION_MSG:
  993. dbgs() << "Executing Pass '" << P->getPassName();
  994. break;
  995. case MODIFICATION_MSG:
  996. dbgs() << "Made Modification '" << P->getPassName();
  997. break;
  998. case FREEING_MSG:
  999. dbgs() << " Freeing Pass '" << P->getPassName();
  1000. break;
  1001. default:
  1002. break;
  1003. }
  1004. switch (S2) {
  1005. case ON_FUNCTION_MSG:
  1006. dbgs() << "' on Function '" << Msg << "'...\n";
  1007. break;
  1008. case ON_MODULE_MSG:
  1009. dbgs() << "' on Module '" << Msg << "'...\n";
  1010. break;
  1011. case ON_REGION_MSG:
  1012. dbgs() << "' on Region '" << Msg << "'...\n";
  1013. break;
  1014. case ON_LOOP_MSG:
  1015. dbgs() << "' on Loop '" << Msg << "'...\n";
  1016. break;
  1017. case ON_CG_MSG:
  1018. dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
  1019. break;
  1020. default:
  1021. break;
  1022. }
  1023. }
  1024. void PMDataManager::dumpRequiredSet(const Pass *P) const {
  1025. if (PassDebugging < Details)
  1026. return;
  1027. AnalysisUsage analysisUsage;
  1028. P->getAnalysisUsage(analysisUsage);
  1029. dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
  1030. }
  1031. void PMDataManager::dumpPreservedSet(const Pass *P) const {
  1032. if (PassDebugging < Details)
  1033. return;
  1034. AnalysisUsage analysisUsage;
  1035. P->getAnalysisUsage(analysisUsage);
  1036. dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
  1037. }
  1038. void PMDataManager::dumpUsedSet(const Pass *P) const {
  1039. if (PassDebugging < Details)
  1040. return;
  1041. AnalysisUsage analysisUsage;
  1042. P->getAnalysisUsage(analysisUsage);
  1043. dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
  1044. }
  1045. void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
  1046. const AnalysisUsage::VectorType &Set) const {
  1047. assert(PassDebugging >= Details);
  1048. if (Set.empty())
  1049. return;
  1050. dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
  1051. for (unsigned i = 0; i != Set.size(); ++i) {
  1052. if (i) dbgs() << ',';
  1053. const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
  1054. if (!PInf) {
  1055. // Some preserved passes, such as AliasAnalysis, may not be initialized by
  1056. // all drivers.
  1057. dbgs() << " Uninitialized Pass";
  1058. continue;
  1059. }
  1060. dbgs() << ' ' << PInf->getPassName();
  1061. }
  1062. dbgs() << '\n';
  1063. }
  1064. /// Add RequiredPass into list of lower level passes required by pass P.
  1065. /// RequiredPass is run on the fly by Pass Manager when P requests it
  1066. /// through getAnalysis interface.
  1067. /// This should be handled by specific pass manager.
  1068. void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
  1069. if (TPM) {
  1070. TPM->dumpArguments();
  1071. TPM->dumpPasses();
  1072. }
  1073. // Module Level pass may required Function Level analysis info
  1074. // (e.g. dominator info). Pass manager uses on the fly function pass manager
  1075. // to provide this on demand. In that case, in Pass manager terminology,
  1076. // module level pass is requiring lower level analysis info managed by
  1077. // lower level pass manager.
  1078. // When Pass manager is not able to order required analysis info, Pass manager
  1079. // checks whether any lower level manager will be able to provide this
  1080. // analysis info on demand or not.
  1081. #ifndef NDEBUG
  1082. dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
  1083. dbgs() << "' required by '" << P->getPassName() << "'\n";
  1084. #endif
  1085. llvm_unreachable("Unable to schedule pass");
  1086. }
  1087. std::tuple<Pass *, bool> PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI,
  1088. Function &F) {
  1089. llvm_unreachable("Unable to find on the fly pass");
  1090. }
  1091. // Destructor
  1092. PMDataManager::~PMDataManager() {
  1093. for (Pass *P : PassVector)
  1094. delete P;
  1095. }
  1096. //===----------------------------------------------------------------------===//
  1097. // NOTE: Is this the right place to define this method ?
  1098. // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
  1099. Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID) const {
  1100. return PM.findAnalysisPass(ID, true);
  1101. }
  1102. std::tuple<Pass *, bool>
  1103. AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI, Function &F) {
  1104. return PM.getOnTheFlyPass(P, AnalysisPI, F);
  1105. }
  1106. namespace llvm {
  1107. namespace legacy {
  1108. //===----------------------------------------------------------------------===//
  1109. // FunctionPassManager implementation
  1110. /// Create new Function pass manager
  1111. FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
  1112. FPM = new legacy::FunctionPassManagerImpl();
  1113. // FPM is the top level manager.
  1114. FPM->setTopLevelManager(FPM);
  1115. AnalysisResolver *AR = new AnalysisResolver(*FPM);
  1116. FPM->setResolver(AR);
  1117. }
  1118. FunctionPassManager::~FunctionPassManager() {
  1119. delete FPM;
  1120. }
  1121. void FunctionPassManager::add(Pass *P) {
  1122. FPM->add(P);
  1123. }
  1124. /// run - Execute all of the passes scheduled for execution. Keep
  1125. /// track of whether any of the passes modifies the function, and if
  1126. /// so, return true.
  1127. ///
  1128. bool FunctionPassManager::run(Function &F) {
  1129. handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
  1130. report_fatal_error(Twine("Error reading bitcode file: ") + EIB.message());
  1131. });
  1132. return FPM->run(F);
  1133. }
  1134. /// doInitialization - Run all of the initializers for the function passes.
  1135. ///
  1136. bool FunctionPassManager::doInitialization() {
  1137. return FPM->doInitialization(*M);
  1138. }
  1139. /// doFinalization - Run all of the finalizers for the function passes.
  1140. ///
  1141. bool FunctionPassManager::doFinalization() {
  1142. return FPM->doFinalization(*M);
  1143. }
  1144. } // namespace legacy
  1145. } // namespace llvm
  1146. /// cleanup - After running all passes, clean up pass manager cache.
  1147. void FPPassManager::cleanup() {
  1148. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  1149. FunctionPass *FP = getContainedPass(Index);
  1150. AnalysisResolver *AR = FP->getResolver();
  1151. assert(AR && "Analysis Resolver is not set");
  1152. AR->clearAnalysisImpls();
  1153. }
  1154. }
  1155. //===----------------------------------------------------------------------===//
  1156. // FPPassManager implementation
  1157. char FPPassManager::ID = 0;
  1158. /// Print passes managed by this manager
  1159. void FPPassManager::dumpPassStructure(unsigned Offset) {
  1160. dbgs().indent(Offset*2) << "FunctionPass Manager\n";
  1161. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  1162. FunctionPass *FP = getContainedPass(Index);
  1163. FP->dumpPassStructure(Offset + 1);
  1164. dumpLastUses(FP, Offset+1);
  1165. }
  1166. }
  1167. /// Execute all of the passes scheduled for execution by invoking
  1168. /// runOnFunction method. Keep track of whether any of the passes modifies
  1169. /// the function, and if so, return true.
  1170. bool FPPassManager::runOnFunction(Function &F) {
  1171. if (F.isDeclaration())
  1172. return false;
  1173. bool Changed = false;
  1174. Module &M = *F.getParent();
  1175. // Collect inherited analysis from Module level pass manager.
  1176. populateInheritedAnalysis(TPM->activeStack);
  1177. unsigned InstrCount, FunctionSize = 0;
  1178. StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
  1179. bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
  1180. // Collect the initial size of the module.
  1181. if (EmitICRemark) {
  1182. InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
  1183. FunctionSize = F.getInstructionCount();
  1184. }
  1185. llvm::TimeTraceScope FunctionScope("OptFunction", F.getName());
  1186. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  1187. FunctionPass *FP = getContainedPass(Index);
  1188. bool LocalChanged = false;
  1189. llvm::TimeTraceScope PassScope("RunPass", FP->getPassName());
  1190. dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
  1191. dumpRequiredSet(FP);
  1192. initializeAnalysisImpl(FP);
  1193. {
  1194. PassManagerPrettyStackEntry X(FP, F);
  1195. TimeRegion PassTimer(getPassTimer(FP));
  1196. #ifdef EXPENSIVE_CHECKS
  1197. uint64_t RefHash = StructuralHash(F);
  1198. #endif
  1199. LocalChanged |= FP->runOnFunction(F);
  1200. #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
  1201. if (!LocalChanged && (RefHash != StructuralHash(F))) {
  1202. llvm::errs() << "Pass modifies its input and doesn't report it: "
  1203. << FP->getPassName() << "\n";
  1204. llvm_unreachable("Pass modifies its input and doesn't report it");
  1205. }
  1206. #endif
  1207. if (EmitICRemark) {
  1208. unsigned NewSize = F.getInstructionCount();
  1209. // Update the size of the function, emit a remark, and update the size
  1210. // of the module.
  1211. if (NewSize != FunctionSize) {
  1212. int64_t Delta = static_cast<int64_t>(NewSize) -
  1213. static_cast<int64_t>(FunctionSize);
  1214. emitInstrCountChangedRemark(FP, M, Delta, InstrCount,
  1215. FunctionToInstrCount, &F);
  1216. InstrCount = static_cast<int64_t>(InstrCount) + Delta;
  1217. FunctionSize = NewSize;
  1218. }
  1219. }
  1220. }
  1221. Changed |= LocalChanged;
  1222. if (LocalChanged)
  1223. dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
  1224. dumpPreservedSet(FP);
  1225. dumpUsedSet(FP);
  1226. verifyPreservedAnalysis(FP);
  1227. if (LocalChanged)
  1228. removeNotPreservedAnalysis(FP);
  1229. recordAvailableAnalysis(FP);
  1230. removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
  1231. }
  1232. return Changed;
  1233. }
  1234. bool FPPassManager::runOnModule(Module &M) {
  1235. bool Changed = false;
  1236. for (Function &F : M)
  1237. Changed |= runOnFunction(F);
  1238. return Changed;
  1239. }
  1240. bool FPPassManager::doInitialization(Module &M) {
  1241. bool Changed = false;
  1242. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
  1243. Changed |= getContainedPass(Index)->doInitialization(M);
  1244. return Changed;
  1245. }
  1246. bool FPPassManager::doFinalization(Module &M) {
  1247. bool Changed = false;
  1248. for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
  1249. Changed |= getContainedPass(Index)->doFinalization(M);
  1250. return Changed;
  1251. }
  1252. //===----------------------------------------------------------------------===//
  1253. // MPPassManager implementation
  1254. /// Execute all of the passes scheduled for execution by invoking
  1255. /// runOnModule method. Keep track of whether any of the passes modifies
  1256. /// the module, and if so, return true.
  1257. bool
  1258. MPPassManager::runOnModule(Module &M) {
  1259. llvm::TimeTraceScope TimeScope("OptModule", M.getName());
  1260. bool Changed = false;
  1261. // Initialize on-the-fly passes
  1262. for (auto &OnTheFlyManager : OnTheFlyManagers) {
  1263. legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
  1264. Changed |= FPP->doInitialization(M);
  1265. }
  1266. // Initialize module passes
  1267. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
  1268. Changed |= getContainedPass(Index)->doInitialization(M);
  1269. unsigned InstrCount;
  1270. StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
  1271. bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
  1272. // Collect the initial size of the module.
  1273. if (EmitICRemark)
  1274. InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
  1275. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  1276. ModulePass *MP = getContainedPass(Index);
  1277. bool LocalChanged = false;
  1278. dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
  1279. dumpRequiredSet(MP);
  1280. initializeAnalysisImpl(MP);
  1281. {
  1282. PassManagerPrettyStackEntry X(MP, M);
  1283. TimeRegion PassTimer(getPassTimer(MP));
  1284. #ifdef EXPENSIVE_CHECKS
  1285. uint64_t RefHash = StructuralHash(M);
  1286. #endif
  1287. LocalChanged |= MP->runOnModule(M);
  1288. #ifdef EXPENSIVE_CHECKS
  1289. assert((LocalChanged || (RefHash == StructuralHash(M))) &&
  1290. "Pass modifies its input and doesn't report it.");
  1291. #endif
  1292. if (EmitICRemark) {
  1293. // Update the size of the module.
  1294. unsigned ModuleCount = M.getInstructionCount();
  1295. if (ModuleCount != InstrCount) {
  1296. int64_t Delta = static_cast<int64_t>(ModuleCount) -
  1297. static_cast<int64_t>(InstrCount);
  1298. emitInstrCountChangedRemark(MP, M, Delta, InstrCount,
  1299. FunctionToInstrCount);
  1300. InstrCount = ModuleCount;
  1301. }
  1302. }
  1303. }
  1304. Changed |= LocalChanged;
  1305. if (LocalChanged)
  1306. dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
  1307. M.getModuleIdentifier());
  1308. dumpPreservedSet(MP);
  1309. dumpUsedSet(MP);
  1310. verifyPreservedAnalysis(MP);
  1311. if (LocalChanged)
  1312. removeNotPreservedAnalysis(MP);
  1313. recordAvailableAnalysis(MP);
  1314. removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
  1315. }
  1316. // Finalize module passes
  1317. for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
  1318. Changed |= getContainedPass(Index)->doFinalization(M);
  1319. // Finalize on-the-fly passes
  1320. for (auto &OnTheFlyManager : OnTheFlyManagers) {
  1321. legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
  1322. // We don't know when is the last time an on-the-fly pass is run,
  1323. // so we need to releaseMemory / finalize here
  1324. FPP->releaseMemoryOnTheFly();
  1325. Changed |= FPP->doFinalization(M);
  1326. }
  1327. return Changed;
  1328. }
  1329. /// Add RequiredPass into list of lower level passes required by pass P.
  1330. /// RequiredPass is run on the fly by Pass Manager when P requests it
  1331. /// through getAnalysis interface.
  1332. void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
  1333. assert(RequiredPass && "No required pass?");
  1334. assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
  1335. "Unable to handle Pass that requires lower level Analysis pass");
  1336. assert((P->getPotentialPassManagerType() <
  1337. RequiredPass->getPotentialPassManagerType()) &&
  1338. "Unable to handle Pass that requires lower level Analysis pass");
  1339. legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
  1340. if (!FPP) {
  1341. FPP = new legacy::FunctionPassManagerImpl();
  1342. // FPP is the top level manager.
  1343. FPP->setTopLevelManager(FPP);
  1344. OnTheFlyManagers[P] = FPP;
  1345. }
  1346. const PassInfo *RequiredPassPI =
  1347. TPM->findAnalysisPassInfo(RequiredPass->getPassID());
  1348. Pass *FoundPass = nullptr;
  1349. if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
  1350. FoundPass =
  1351. ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
  1352. }
  1353. if (!FoundPass) {
  1354. FoundPass = RequiredPass;
  1355. // This should be guaranteed to add RequiredPass to the passmanager given
  1356. // that we checked for an available analysis above.
  1357. FPP->add(RequiredPass);
  1358. }
  1359. // Register P as the last user of FoundPass or RequiredPass.
  1360. SmallVector<Pass *, 1> LU;
  1361. LU.push_back(FoundPass);
  1362. FPP->setLastUser(LU, P);
  1363. }
  1364. /// Return function pass corresponding to PassInfo PI, that is
  1365. /// required by module pass MP. Instantiate analysis pass, by using
  1366. /// its runOnFunction() for function F.
  1367. std::tuple<Pass *, bool> MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI,
  1368. Function &F) {
  1369. legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
  1370. assert(FPP && "Unable to find on the fly pass");
  1371. FPP->releaseMemoryOnTheFly();
  1372. bool Changed = FPP->run(F);
  1373. return std::make_tuple(((PMTopLevelManager *)FPP)->findAnalysisPass(PI),
  1374. Changed);
  1375. }
  1376. namespace llvm {
  1377. namespace legacy {
  1378. //===----------------------------------------------------------------------===//
  1379. // PassManager implementation
  1380. /// Create new pass manager
  1381. PassManager::PassManager() {
  1382. PM = new PassManagerImpl();
  1383. // PM is the top level manager
  1384. PM->setTopLevelManager(PM);
  1385. }
  1386. PassManager::~PassManager() {
  1387. delete PM;
  1388. }
  1389. void PassManager::add(Pass *P) {
  1390. PM->add(P);
  1391. }
  1392. /// run - Execute all of the passes scheduled for execution. Keep track of
  1393. /// whether any of the passes modifies the module, and if so, return true.
  1394. bool PassManager::run(Module &M) {
  1395. return PM->run(M);
  1396. }
  1397. } // namespace legacy
  1398. } // namespace llvm
  1399. //===----------------------------------------------------------------------===//
  1400. // PMStack implementation
  1401. //
  1402. // Pop Pass Manager from the stack and clear its analysis info.
  1403. void PMStack::pop() {
  1404. PMDataManager *Top = this->top();
  1405. Top->initializeAnalysisInfo();
  1406. S.pop_back();
  1407. }
  1408. // Push PM on the stack and set its top level manager.
  1409. void PMStack::push(PMDataManager *PM) {
  1410. assert(PM && "Unable to push. Pass Manager expected");
  1411. assert(PM->getDepth()==0 && "Pass Manager depth set too early");
  1412. if (!this->empty()) {
  1413. assert(PM->getPassManagerType() > this->top()->getPassManagerType()
  1414. && "pushing bad pass manager to PMStack");
  1415. PMTopLevelManager *TPM = this->top()->getTopLevelManager();
  1416. assert(TPM && "Unable to find top level manager");
  1417. TPM->addIndirectPassManager(PM);
  1418. PM->setTopLevelManager(TPM);
  1419. PM->setDepth(this->top()->getDepth()+1);
  1420. } else {
  1421. assert((PM->getPassManagerType() == PMT_ModulePassManager
  1422. || PM->getPassManagerType() == PMT_FunctionPassManager)
  1423. && "pushing bad pass manager to PMStack");
  1424. PM->setDepth(1);
  1425. }
  1426. S.push_back(PM);
  1427. }
  1428. // Dump content of the pass manager stack.
  1429. LLVM_DUMP_METHOD void PMStack::dump() const {
  1430. for (PMDataManager *Manager : S)
  1431. dbgs() << Manager->getAsPass()->getPassName() << ' ';
  1432. if (!S.empty())
  1433. dbgs() << '\n';
  1434. }
  1435. /// Find appropriate Module Pass Manager in the PM Stack and
  1436. /// add self into that manager.
  1437. void ModulePass::assignPassManager(PMStack &PMS,
  1438. PassManagerType PreferredType) {
  1439. // Find Module Pass Manager
  1440. PassManagerType T;
  1441. while ((T = PMS.top()->getPassManagerType()) > PMT_ModulePassManager &&
  1442. T != PreferredType)
  1443. PMS.pop();
  1444. PMS.top()->add(this);
  1445. }
  1446. /// Find appropriate Function Pass Manager or Call Graph Pass Manager
  1447. /// in the PM Stack and add self into that manager.
  1448. void FunctionPass::assignPassManager(PMStack &PMS,
  1449. PassManagerType /*PreferredType*/) {
  1450. // Find Function Pass Manager
  1451. PMDataManager *PM;
  1452. while (PM = PMS.top(), PM->getPassManagerType() > PMT_FunctionPassManager)
  1453. PMS.pop();
  1454. // Create new Function Pass Manager if needed.
  1455. if (PM->getPassManagerType() != PMT_FunctionPassManager) {
  1456. // [1] Create new Function Pass Manager
  1457. auto *FPP = new FPPassManager;
  1458. FPP->populateInheritedAnalysis(PMS);
  1459. // [2] Set up new manager's top level manager
  1460. PM->getTopLevelManager()->addIndirectPassManager(FPP);
  1461. // [3] Assign manager to manage this new manager. This may create
  1462. // and push new managers into PMS
  1463. FPP->assignPassManager(PMS, PM->getPassManagerType());
  1464. // [4] Push new manager into PMS
  1465. PMS.push(FPP);
  1466. PM = FPP;
  1467. }
  1468. // Assign FPP as the manager of this pass.
  1469. PM->add(this);
  1470. }
  1471. legacy::PassManagerBase::~PassManagerBase() {}