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