LegacyPassManager.cpp 66 KB

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