NewPMDriver.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. //===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===//
  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. /// \file
  9. ///
  10. /// This file is just a split of the code that logically belongs in opt.cpp but
  11. /// that includes the new pass manager headers.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "NewPMDriver.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Analysis/AliasAnalysis.h"
  18. #include "llvm/Analysis/CGSCCPassManager.h"
  19. #include "llvm/Analysis/TargetLibraryInfo.h"
  20. #include "llvm/Bitcode/BitcodeWriterPass.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/IR/Dominators.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/PassManager.h"
  26. #include "llvm/IR/Verifier.h"
  27. #include "llvm/IRPrinter/IRPrintingPasses.h"
  28. #include "llvm/Passes/PassBuilder.h"
  29. #include "llvm/Passes/PassPlugin.h"
  30. #include "llvm/Passes/StandardInstrumentations.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/ToolOutputFile.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/Target/TargetMachine.h"
  35. #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
  36. #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
  37. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  38. #include "llvm/Transforms/Utils/Debugify.h"
  39. using namespace llvm;
  40. using namespace opt_tool;
  41. namespace llvm {
  42. cl::opt<bool> DebugifyEach(
  43. "debugify-each",
  44. cl::desc("Start each pass with debugify and end it with check-debugify"));
  45. cl::opt<std::string>
  46. DebugifyExport("debugify-export",
  47. cl::desc("Export per-pass debugify statistics to this file"),
  48. cl::value_desc("filename"));
  49. cl::opt<bool> VerifyEachDebugInfoPreserve(
  50. "verify-each-debuginfo-preserve",
  51. cl::desc("Start each pass with collecting and end it with checking of "
  52. "debug info preservation."));
  53. cl::opt<std::string>
  54. VerifyDIPreserveExport("verify-di-preserve-export",
  55. cl::desc("Export debug info preservation failures into "
  56. "specified (JSON) file (should be abs path as we use"
  57. " append mode to insert new JSON objects)"),
  58. cl::value_desc("filename"), cl::init(""));
  59. } // namespace llvm
  60. enum class DebugLogging { None, Normal, Verbose, Quiet };
  61. static cl::opt<DebugLogging> DebugPM(
  62. "debug-pass-manager", cl::Hidden, cl::ValueOptional,
  63. cl::desc("Print pass management debugging information"),
  64. cl::init(DebugLogging::None),
  65. cl::values(
  66. clEnumValN(DebugLogging::Normal, "", ""),
  67. clEnumValN(DebugLogging::Quiet, "quiet",
  68. "Skip printing info about analyses"),
  69. clEnumValN(
  70. DebugLogging::Verbose, "verbose",
  71. "Print extra information about adaptors and pass managers")));
  72. // This flag specifies a textual description of the alias analysis pipeline to
  73. // use when querying for aliasing information. It only works in concert with
  74. // the "passes" flag above.
  75. static cl::opt<std::string>
  76. AAPipeline("aa-pipeline",
  77. cl::desc("A textual description of the alias analysis "
  78. "pipeline for handling managed aliasing queries"),
  79. cl::Hidden, cl::init("default"));
  80. /// {{@ These options accept textual pipeline descriptions which will be
  81. /// inserted into default pipelines at the respective extension points
  82. static cl::opt<std::string> PeepholeEPPipeline(
  83. "passes-ep-peephole",
  84. cl::desc("A textual description of the function pass pipeline inserted at "
  85. "the Peephole extension points into default pipelines"),
  86. cl::Hidden);
  87. static cl::opt<std::string> LateLoopOptimizationsEPPipeline(
  88. "passes-ep-late-loop-optimizations",
  89. cl::desc(
  90. "A textual description of the loop pass pipeline inserted at "
  91. "the LateLoopOptimizations extension point into default pipelines"),
  92. cl::Hidden);
  93. static cl::opt<std::string> LoopOptimizerEndEPPipeline(
  94. "passes-ep-loop-optimizer-end",
  95. cl::desc("A textual description of the loop pass pipeline inserted at "
  96. "the LoopOptimizerEnd extension point into default pipelines"),
  97. cl::Hidden);
  98. static cl::opt<std::string> ScalarOptimizerLateEPPipeline(
  99. "passes-ep-scalar-optimizer-late",
  100. cl::desc("A textual description of the function pass pipeline inserted at "
  101. "the ScalarOptimizerLate extension point into default pipelines"),
  102. cl::Hidden);
  103. static cl::opt<std::string> CGSCCOptimizerLateEPPipeline(
  104. "passes-ep-cgscc-optimizer-late",
  105. cl::desc("A textual description of the cgscc pass pipeline inserted at "
  106. "the CGSCCOptimizerLate extension point into default pipelines"),
  107. cl::Hidden);
  108. static cl::opt<std::string> VectorizerStartEPPipeline(
  109. "passes-ep-vectorizer-start",
  110. cl::desc("A textual description of the function pass pipeline inserted at "
  111. "the VectorizerStart extension point into default pipelines"),
  112. cl::Hidden);
  113. static cl::opt<std::string> PipelineStartEPPipeline(
  114. "passes-ep-pipeline-start",
  115. cl::desc("A textual description of the module pass pipeline inserted at "
  116. "the PipelineStart extension point into default pipelines"),
  117. cl::Hidden);
  118. static cl::opt<std::string> PipelineEarlySimplificationEPPipeline(
  119. "passes-ep-pipeline-early-simplification",
  120. cl::desc("A textual description of the module pass pipeline inserted at "
  121. "the EarlySimplification extension point into default pipelines"),
  122. cl::Hidden);
  123. static cl::opt<std::string> OptimizerEarlyEPPipeline(
  124. "passes-ep-optimizer-early",
  125. cl::desc("A textual description of the module pass pipeline inserted at "
  126. "the OptimizerEarly extension point into default pipelines"),
  127. cl::Hidden);
  128. static cl::opt<std::string> OptimizerLastEPPipeline(
  129. "passes-ep-optimizer-last",
  130. cl::desc("A textual description of the module pass pipeline inserted at "
  131. "the OptimizerLast extension point into default pipelines"),
  132. cl::Hidden);
  133. static cl::opt<std::string> FullLinkTimeOptimizationEarlyEPPipeline(
  134. "passes-ep-full-link-time-optimization-early",
  135. cl::desc("A textual description of the module pass pipeline inserted at "
  136. "the FullLinkTimeOptimizationEarly extension point into default "
  137. "pipelines"),
  138. cl::Hidden);
  139. static cl::opt<std::string> FullLinkTimeOptimizationLastEPPipeline(
  140. "passes-ep-full-link-time-optimization-last",
  141. cl::desc("A textual description of the module pass pipeline inserted at "
  142. "the FullLinkTimeOptimizationLast extension point into default "
  143. "pipelines"),
  144. cl::Hidden);
  145. /// @}}
  146. static cl::opt<bool> DisablePipelineVerification(
  147. "disable-pipeline-verification",
  148. cl::desc("Only has an effect when specified with -print-pipeline-passes. "
  149. "Disables verifying that the textual pipeline generated by "
  150. "-print-pipeline-passes can be used to create a pipeline."),
  151. cl::Hidden);
  152. static cl::opt<PGOKind>
  153. PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
  154. cl::desc("The kind of profile guided optimization"),
  155. cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
  156. clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
  157. "Instrument the IR to generate profile."),
  158. clEnumValN(InstrUse, "pgo-instr-use-pipeline",
  159. "Use instrumented profile to guide PGO."),
  160. clEnumValN(SampleUse, "pgo-sample-use-pipeline",
  161. "Use sampled profile to guide PGO.")));
  162. static cl::opt<std::string> ProfileFile("profile-file",
  163. cl::desc("Path to the profile."), cl::Hidden);
  164. static cl::opt<CSPGOKind> CSPGOKindFlag(
  165. "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
  166. cl::desc("The kind of context sensitive profile guided optimization"),
  167. cl::values(
  168. clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
  169. clEnumValN(
  170. CSInstrGen, "cspgo-instr-gen-pipeline",
  171. "Instrument (context sensitive) the IR to generate profile."),
  172. clEnumValN(
  173. CSInstrUse, "cspgo-instr-use-pipeline",
  174. "Use instrumented (context sensitive) profile to guide PGO.")));
  175. static cl::opt<std::string> CSProfileGenFile(
  176. "cs-profilegen-file",
  177. cl::desc("Path to the instrumented context sensitive profile."),
  178. cl::Hidden);
  179. static cl::opt<std::string>
  180. ProfileRemappingFile("profile-remapping-file",
  181. cl::desc("Path to the profile remapping file."),
  182. cl::Hidden);
  183. static cl::opt<bool> DebugInfoForProfiling(
  184. "debug-info-for-profiling", cl::init(false), cl::Hidden,
  185. cl::desc("Emit special debug info to enable PGO profile generation."));
  186. static cl::opt<bool> PseudoProbeForProfiling(
  187. "pseudo-probe-for-profiling", cl::init(false), cl::Hidden,
  188. cl::desc("Emit pseudo probes to enable PGO profile generation."));
  189. static cl::opt<bool> DisableLoopUnrolling(
  190. "disable-loop-unrolling",
  191. cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false));
  192. namespace llvm {
  193. extern cl::opt<bool> PrintPipelinePasses;
  194. } // namespace llvm
  195. template <typename PassManagerT>
  196. bool tryParsePipelineText(PassBuilder &PB,
  197. const cl::opt<std::string> &PipelineOpt) {
  198. if (PipelineOpt.empty())
  199. return false;
  200. // Verify the pipeline is parseable:
  201. PassManagerT PM;
  202. if (auto Err = PB.parsePassPipeline(PM, PipelineOpt)) {
  203. errs() << "Could not parse -" << PipelineOpt.ArgStr
  204. << " pipeline: " << toString(std::move(Err))
  205. << "... I'm going to ignore it.\n";
  206. return false;
  207. }
  208. return true;
  209. }
  210. /// If one of the EPPipeline command line options was given, register callbacks
  211. /// for parsing and inserting the given pipeline
  212. static void registerEPCallbacks(PassBuilder &PB) {
  213. if (tryParsePipelineText<FunctionPassManager>(PB, PeepholeEPPipeline))
  214. PB.registerPeepholeEPCallback(
  215. [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
  216. ExitOnError Err("Unable to parse PeepholeEP pipeline: ");
  217. Err(PB.parsePassPipeline(PM, PeepholeEPPipeline));
  218. });
  219. if (tryParsePipelineText<LoopPassManager>(PB,
  220. LateLoopOptimizationsEPPipeline))
  221. PB.registerLateLoopOptimizationsEPCallback(
  222. [&PB](LoopPassManager &PM, OptimizationLevel Level) {
  223. ExitOnError Err("Unable to parse LateLoopOptimizationsEP pipeline: ");
  224. Err(PB.parsePassPipeline(PM, LateLoopOptimizationsEPPipeline));
  225. });
  226. if (tryParsePipelineText<LoopPassManager>(PB, LoopOptimizerEndEPPipeline))
  227. PB.registerLoopOptimizerEndEPCallback(
  228. [&PB](LoopPassManager &PM, OptimizationLevel Level) {
  229. ExitOnError Err("Unable to parse LoopOptimizerEndEP pipeline: ");
  230. Err(PB.parsePassPipeline(PM, LoopOptimizerEndEPPipeline));
  231. });
  232. if (tryParsePipelineText<FunctionPassManager>(PB,
  233. ScalarOptimizerLateEPPipeline))
  234. PB.registerScalarOptimizerLateEPCallback(
  235. [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
  236. ExitOnError Err("Unable to parse ScalarOptimizerLateEP pipeline: ");
  237. Err(PB.parsePassPipeline(PM, ScalarOptimizerLateEPPipeline));
  238. });
  239. if (tryParsePipelineText<CGSCCPassManager>(PB, CGSCCOptimizerLateEPPipeline))
  240. PB.registerCGSCCOptimizerLateEPCallback(
  241. [&PB](CGSCCPassManager &PM, OptimizationLevel Level) {
  242. ExitOnError Err("Unable to parse CGSCCOptimizerLateEP pipeline: ");
  243. Err(PB.parsePassPipeline(PM, CGSCCOptimizerLateEPPipeline));
  244. });
  245. if (tryParsePipelineText<FunctionPassManager>(PB, VectorizerStartEPPipeline))
  246. PB.registerVectorizerStartEPCallback(
  247. [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
  248. ExitOnError Err("Unable to parse VectorizerStartEP pipeline: ");
  249. Err(PB.parsePassPipeline(PM, VectorizerStartEPPipeline));
  250. });
  251. if (tryParsePipelineText<ModulePassManager>(PB, PipelineStartEPPipeline))
  252. PB.registerPipelineStartEPCallback(
  253. [&PB](ModulePassManager &PM, OptimizationLevel) {
  254. ExitOnError Err("Unable to parse PipelineStartEP pipeline: ");
  255. Err(PB.parsePassPipeline(PM, PipelineStartEPPipeline));
  256. });
  257. if (tryParsePipelineText<ModulePassManager>(
  258. PB, PipelineEarlySimplificationEPPipeline))
  259. PB.registerPipelineEarlySimplificationEPCallback(
  260. [&PB](ModulePassManager &PM, OptimizationLevel) {
  261. ExitOnError Err("Unable to parse EarlySimplification pipeline: ");
  262. Err(PB.parsePassPipeline(PM, PipelineEarlySimplificationEPPipeline));
  263. });
  264. if (tryParsePipelineText<ModulePassManager>(PB, OptimizerEarlyEPPipeline))
  265. PB.registerOptimizerEarlyEPCallback(
  266. [&PB](ModulePassManager &PM, OptimizationLevel) {
  267. ExitOnError Err("Unable to parse OptimizerEarlyEP pipeline: ");
  268. Err(PB.parsePassPipeline(PM, OptimizerEarlyEPPipeline));
  269. });
  270. if (tryParsePipelineText<ModulePassManager>(PB, OptimizerLastEPPipeline))
  271. PB.registerOptimizerLastEPCallback(
  272. [&PB](ModulePassManager &PM, OptimizationLevel) {
  273. ExitOnError Err("Unable to parse OptimizerLastEP pipeline: ");
  274. Err(PB.parsePassPipeline(PM, OptimizerLastEPPipeline));
  275. });
  276. if (tryParsePipelineText<ModulePassManager>(
  277. PB, FullLinkTimeOptimizationEarlyEPPipeline))
  278. PB.registerFullLinkTimeOptimizationEarlyEPCallback(
  279. [&PB](ModulePassManager &PM, OptimizationLevel) {
  280. ExitOnError Err(
  281. "Unable to parse FullLinkTimeOptimizationEarlyEP pipeline: ");
  282. Err(PB.parsePassPipeline(PM,
  283. FullLinkTimeOptimizationEarlyEPPipeline));
  284. });
  285. if (tryParsePipelineText<ModulePassManager>(
  286. PB, FullLinkTimeOptimizationLastEPPipeline))
  287. PB.registerFullLinkTimeOptimizationLastEPCallback(
  288. [&PB](ModulePassManager &PM, OptimizationLevel) {
  289. ExitOnError Err(
  290. "Unable to parse FullLinkTimeOptimizationLastEP pipeline: ");
  291. Err(PB.parsePassPipeline(PM, FullLinkTimeOptimizationLastEPPipeline));
  292. });
  293. }
  294. #define HANDLE_EXTENSION(Ext) \
  295. llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
  296. #include "llvm/Support/Extension.def"
  297. bool llvm::runPassPipeline(StringRef Arg0, Module &M, TargetMachine *TM,
  298. TargetLibraryInfoImpl *TLII, ToolOutputFile *Out,
  299. ToolOutputFile *ThinLTOLinkOut,
  300. ToolOutputFile *OptRemarkFile,
  301. StringRef PassPipeline,
  302. ArrayRef<PassPlugin> PassPlugins,
  303. OutputKind OK, VerifierKind VK,
  304. bool ShouldPreserveAssemblyUseListOrder,
  305. bool ShouldPreserveBitcodeUseListOrder,
  306. bool EmitSummaryIndex, bool EmitModuleHash,
  307. bool EnableDebugify, bool VerifyDIPreserve) {
  308. bool VerifyEachPass = VK == VK_VerifyEachPass;
  309. std::optional<PGOOptions> P;
  310. switch (PGOKindFlag) {
  311. case InstrGen:
  312. P = PGOOptions(ProfileFile, "", "", PGOOptions::IRInstr);
  313. break;
  314. case InstrUse:
  315. P = PGOOptions(ProfileFile, "", ProfileRemappingFile, PGOOptions::IRUse);
  316. break;
  317. case SampleUse:
  318. P = PGOOptions(ProfileFile, "", ProfileRemappingFile,
  319. PGOOptions::SampleUse);
  320. break;
  321. case NoPGO:
  322. if (DebugInfoForProfiling || PseudoProbeForProfiling)
  323. P = PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
  324. DebugInfoForProfiling, PseudoProbeForProfiling);
  325. else
  326. P = std::nullopt;
  327. }
  328. if (CSPGOKindFlag != NoCSPGO) {
  329. if (P && (P->Action == PGOOptions::IRInstr ||
  330. P->Action == PGOOptions::SampleUse)) {
  331. errs() << "CSPGOKind cannot be used with IRInstr or SampleUse";
  332. return false;
  333. }
  334. if (CSPGOKindFlag == CSInstrGen) {
  335. if (CSProfileGenFile.empty()) {
  336. errs() << "CSInstrGen needs to specify CSProfileGenFile";
  337. return false;
  338. }
  339. if (P) {
  340. P->CSAction = PGOOptions::CSIRInstr;
  341. P->CSProfileGenFile = CSProfileGenFile;
  342. } else
  343. P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile,
  344. PGOOptions::NoAction, PGOOptions::CSIRInstr);
  345. } else /* CSPGOKindFlag == CSInstrUse */ {
  346. if (!P) {
  347. errs() << "CSInstrUse needs to be together with InstrUse";
  348. return false;
  349. }
  350. P->CSAction = PGOOptions::CSIRUse;
  351. }
  352. }
  353. if (TM)
  354. TM->setPGOOption(P);
  355. LoopAnalysisManager LAM;
  356. FunctionAnalysisManager FAM;
  357. CGSCCAnalysisManager CGAM;
  358. ModuleAnalysisManager MAM;
  359. PassInstrumentationCallbacks PIC;
  360. PrintPassOptions PrintPassOpts;
  361. PrintPassOpts.Verbose = DebugPM == DebugLogging::Verbose;
  362. PrintPassOpts.SkipAnalyses = DebugPM == DebugLogging::Quiet;
  363. StandardInstrumentations SI(M.getContext(), DebugPM != DebugLogging::None,
  364. VerifyEachPass, PrintPassOpts);
  365. SI.registerCallbacks(PIC, &FAM);
  366. DebugifyEachInstrumentation Debugify;
  367. DebugifyStatsMap DIStatsMap;
  368. DebugInfoPerPass DebugInfoBeforePass;
  369. if (DebugifyEach) {
  370. Debugify.setDIStatsMap(DIStatsMap);
  371. Debugify.setDebugifyMode(DebugifyMode::SyntheticDebugInfo);
  372. Debugify.registerCallbacks(PIC);
  373. } else if (VerifyEachDebugInfoPreserve) {
  374. Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
  375. Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
  376. Debugify.setOrigDIVerifyBugsReportFilePath(
  377. VerifyDIPreserveExport);
  378. Debugify.registerCallbacks(PIC);
  379. }
  380. PipelineTuningOptions PTO;
  381. // LoopUnrolling defaults on to true and DisableLoopUnrolling is initialized
  382. // to false above so we shouldn't necessarily need to check whether or not the
  383. // option has been enabled.
  384. PTO.LoopUnrolling = !DisableLoopUnrolling;
  385. PassBuilder PB(TM, PTO, P, &PIC);
  386. registerEPCallbacks(PB);
  387. // For any loaded plugins, let them register pass builder callbacks.
  388. for (auto &PassPlugin : PassPlugins)
  389. PassPlugin.registerPassBuilderCallbacks(PB);
  390. #define HANDLE_EXTENSION(Ext) \
  391. get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
  392. #include "llvm/Support/Extension.def"
  393. // Specially handle the alias analysis manager so that we can register
  394. // a custom pipeline of AA passes with it.
  395. AAManager AA;
  396. if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) {
  397. errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
  398. return false;
  399. }
  400. // Register the AA manager first so that our version is the one used.
  401. FAM.registerPass([&] { return std::move(AA); });
  402. // Register our TargetLibraryInfoImpl.
  403. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  404. // Register all the basic analyses with the managers.
  405. PB.registerModuleAnalyses(MAM);
  406. PB.registerCGSCCAnalyses(CGAM);
  407. PB.registerFunctionAnalyses(FAM);
  408. PB.registerLoopAnalyses(LAM);
  409. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  410. ModulePassManager MPM;
  411. if (EnableDebugify)
  412. MPM.addPass(NewPMDebugifyPass());
  413. if (VerifyDIPreserve)
  414. MPM.addPass(NewPMDebugifyPass(DebugifyMode::OriginalDebugInfo, "",
  415. &DebugInfoBeforePass));
  416. // Add passes according to the -passes options.
  417. if (!PassPipeline.empty()) {
  418. if (auto Err = PB.parsePassPipeline(MPM, PassPipeline)) {
  419. errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
  420. return false;
  421. }
  422. }
  423. if (VK > VK_NoVerifier)
  424. MPM.addPass(VerifierPass());
  425. if (EnableDebugify)
  426. MPM.addPass(NewPMCheckDebugifyPass(false, "", &DIStatsMap));
  427. if (VerifyDIPreserve)
  428. MPM.addPass(NewPMCheckDebugifyPass(
  429. false, "", nullptr, DebugifyMode::OriginalDebugInfo,
  430. &DebugInfoBeforePass, VerifyDIPreserveExport));
  431. // Add any relevant output pass at the end of the pipeline.
  432. switch (OK) {
  433. case OK_NoOutput:
  434. break; // No output pass needed.
  435. case OK_OutputAssembly:
  436. MPM.addPass(PrintModulePass(
  437. Out->os(), "", ShouldPreserveAssemblyUseListOrder, EmitSummaryIndex));
  438. break;
  439. case OK_OutputBitcode:
  440. MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder,
  441. EmitSummaryIndex, EmitModuleHash));
  442. break;
  443. case OK_OutputThinLTOBitcode:
  444. MPM.addPass(ThinLTOBitcodeWriterPass(
  445. Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr));
  446. break;
  447. }
  448. // Before executing passes, print the final values of the LLVM options.
  449. cl::PrintOptionValues();
  450. // Print a textual, '-passes=' compatible, representation of pipeline if
  451. // requested.
  452. if (PrintPipelinePasses) {
  453. std::string Pipeline;
  454. raw_string_ostream SOS(Pipeline);
  455. MPM.printPipeline(SOS, [&PIC](StringRef ClassName) {
  456. auto PassName = PIC.getPassNameForClassName(ClassName);
  457. return PassName.empty() ? ClassName : PassName;
  458. });
  459. outs() << Pipeline;
  460. outs() << "\n";
  461. if (!DisablePipelineVerification) {
  462. // Check that we can parse the returned pipeline string as an actual
  463. // pipeline.
  464. ModulePassManager TempPM;
  465. if (auto Err = PB.parsePassPipeline(TempPM, Pipeline)) {
  466. errs() << "Could not parse dumped pass pipeline: "
  467. << toString(std::move(Err)) << "\n";
  468. return false;
  469. }
  470. }
  471. return true;
  472. }
  473. // Now that we have all of the passes ready, run them.
  474. MPM.run(M, MAM);
  475. // Declare success.
  476. if (OK != OK_NoOutput) {
  477. Out->keep();
  478. if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut)
  479. ThinLTOLinkOut->keep();
  480. }
  481. if (OptRemarkFile)
  482. OptRemarkFile->keep();
  483. if (DebugifyEach && !DebugifyExport.empty())
  484. exportDebugifyStats(DebugifyExport, Debugify.getDebugifyStatsMap());
  485. return true;
  486. }
  487. void llvm::printPasses(raw_ostream &OS) {
  488. PassBuilder PB;
  489. PB.printPassNames(OS);
  490. }