LegacyPassManager.cpp 63 KB

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