LegacyPassManager.cpp 62 KB

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