LegacyPassManager.cpp 60 KB

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