1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===// 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 // Optimizations may be specified an arbitrary number of times on the command 10 // line, They are run in the order specified. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "BreakpointPrinter.h" 15 #include "NewPMDriver.h" 16 #include "PassPrinters.h" 17 #include "llvm/ADT/Triple.h" 18 #include "llvm/Analysis/CallGraph.h" 19 #include "llvm/Analysis/CallGraphSCCPass.h" 20 #include "llvm/Analysis/LoopPass.h" 21 #include "llvm/Analysis/RegionPass.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/AsmParser/Parser.h" 25 #include "llvm/CodeGen/CommandFlags.h" 26 #include "llvm/CodeGen/TargetPassConfig.h" 27 #include "llvm/Config/llvm-config.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DebugInfo.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/LLVMRemarkStreamer.h" 32 #include "llvm/IR/LegacyPassManager.h" 33 #include "llvm/IR/LegacyPassNameParser.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/IR/Verifier.h" 36 #include "llvm/IRReader/IRReader.h" 37 #include "llvm/InitializePasses.h" 38 #include "llvm/LinkAllIR.h" 39 #include "llvm/LinkAllPasses.h" 40 #include "llvm/MC/SubtargetFeature.h" 41 #include "llvm/Remarks/HotnessThresholdParser.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/Host.h" 45 #include "llvm/Support/InitLLVM.h" 46 #include "llvm/Support/PluginLoader.h" 47 #include "llvm/Support/SourceMgr.h" 48 #include "llvm/Support/SystemUtils.h" 49 #include "llvm/Support/TargetRegistry.h" 50 #include "llvm/Support/TargetSelect.h" 51 #include "llvm/Support/ToolOutputFile.h" 52 #include "llvm/Support/YAMLTraits.h" 53 #include "llvm/Target/TargetMachine.h" 54 #include "llvm/Transforms/Coroutines.h" 55 #include "llvm/Transforms/IPO/AlwaysInliner.h" 56 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 57 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 58 #include "llvm/Transforms/Utils/Cloning.h" 59 #include "llvm/Transforms/Utils/Debugify.h" 60 #include <algorithm> 61 #include <memory> 62 using namespace llvm; 63 using namespace opt_tool; 64 65 static codegen::RegisterCodeGenFlags CFG; 66 67 // The OptimizationList is automatically populated with registered Passes by the 68 // PassNameParser. 69 static cl::list<const PassInfo *, bool, PassNameParser> PassList(cl::desc( 70 "Optimizations available (use '-passes=' for the new pass manager)")); 71 72 static cl::opt<bool> EnableNewPassManager( 73 "enable-new-pm", 74 cl::desc("Enable the new pass manager, translating " 75 "'opt -foo' to 'opt -passes=foo'. This is strictly for the new PM " 76 "migration, use '-passes=' when possible."), 77 cl::init(LLVM_ENABLE_NEW_PASS_MANAGER)); 78 79 // This flag specifies a textual description of the optimization pass pipeline 80 // to run over the module. This flag switches opt to use the new pass manager 81 // infrastructure, completely disabling all of the flags specific to the old 82 // pass management. 83 static cl::opt<std::string> PassPipeline( 84 "passes", 85 cl::desc( 86 "A textual description of the pass pipeline. To have analysis passes " 87 "available before a certain pass, add 'require<foo-analysis>'.")); 88 89 static cl::opt<bool> PrintPasses("print-passes", 90 cl::desc("Print available passes that can be " 91 "specified in -passes=foo and exit")); 92 93 static cl::opt<std::string> 94 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 95 cl::init("-"), cl::value_desc("filename")); 96 97 static cl::opt<std::string> 98 OutputFilename("o", cl::desc("Override output filename"), 99 cl::value_desc("filename")); 100 101 static cl::opt<bool> 102 Force("f", cl::desc("Enable binary output on terminals")); 103 104 static cl::opt<bool> 105 PrintEachXForm("p", cl::desc("Print module after each transformation")); 106 107 static cl::opt<bool> 108 NoOutput("disable-output", 109 cl::desc("Do not write result bitcode file"), cl::Hidden); 110 111 static cl::opt<bool> 112 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 113 114 static cl::opt<bool> 115 OutputThinLTOBC("thinlto-bc", 116 cl::desc("Write output as ThinLTO-ready bitcode")); 117 118 static cl::opt<bool> 119 SplitLTOUnit("thinlto-split-lto-unit", 120 cl::desc("Enable splitting of a ThinLTO LTOUnit")); 121 122 static cl::opt<std::string> ThinLinkBitcodeFile( 123 "thin-link-bitcode-file", cl::value_desc("filename"), 124 cl::desc( 125 "A file in which to write minimized bitcode for the thin link only")); 126 127 static cl::opt<bool> 128 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden); 129 130 static cl::opt<bool> NoUpgradeDebugInfo("disable-upgrade-debug-info", 131 cl::desc("Generate invalid output"), 132 cl::ReallyHidden); 133 134 static cl::opt<bool> VerifyEach("verify-each", 135 cl::desc("Verify after each transform")); 136 137 static cl::opt<bool> 138 DisableDITypeMap("disable-debug-info-type-map", 139 cl::desc("Don't use a uniquing type map for debug info")); 140 141 static cl::opt<bool> 142 StripDebug("strip-debug", 143 cl::desc("Strip debugger symbol info from translation unit")); 144 145 static cl::opt<bool> 146 StripNamedMetadata("strip-named-metadata", 147 cl::desc("Strip module-level named metadata")); 148 149 static cl::opt<bool> 150 DisableInline("disable-inlining", 151 cl::desc("Do not run the inliner pass (legacy PM only)")); 152 153 static cl::opt<bool> 154 DisableOptimizations("disable-opt", 155 cl::desc("Do not run any optimization passes")); 156 157 static cl::opt<bool> StandardLinkOpts( 158 "std-link-opts", 159 cl::desc("Include the standard link time optimizations (legacy PM only)")); 160 161 static cl::opt<bool> 162 OptLevelO0("O0", cl::desc("Optimization level 0. Similar to clang -O0. " 163 "Use -passes='default<O0>' for the new PM")); 164 165 static cl::opt<bool> 166 OptLevelO1("O1", cl::desc("Optimization level 1. Similar to clang -O1. " 167 "Use -passes='default<O1>' for the new PM")); 168 169 static cl::opt<bool> 170 OptLevelO2("O2", cl::desc("Optimization level 2. Similar to clang -O2. " 171 "Use -passes='default<O2>' for the new PM")); 172 173 static cl::opt<bool> 174 OptLevelOs("Os", cl::desc("Like -O2 but size-conscious. Similar to clang " 175 "-Os. Use -passes='default<Os>' for the new PM")); 176 177 static cl::opt<bool> OptLevelOz( 178 "Oz", 179 cl::desc("Like -O2 but optimize for code size above all else. Similar to " 180 "clang -Oz. Use -passes='default<Oz>' for the new PM")); 181 182 static cl::opt<bool> 183 OptLevelO3("O3", cl::desc("Optimization level 3. Similar to clang -O3. " 184 "Use -passes='default<O3>' for the new PM")); 185 186 static cl::opt<unsigned> CodeGenOptLevel( 187 "codegen-opt-level", 188 cl::desc("Override optimization level for codegen hooks, legacy PM only")); 189 190 static cl::opt<std::string> 191 TargetTriple("mtriple", cl::desc("Override target triple for module")); 192 193 cl::opt<bool> DisableLoopUnrolling( 194 "disable-loop-unrolling", 195 cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false)); 196 197 static cl::opt<bool> EmitSummaryIndex("module-summary", 198 cl::desc("Emit module summary index"), 199 cl::init(false)); 200 201 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"), 202 cl::init(false)); 203 204 static cl::opt<bool> 205 DisableSimplifyLibCalls("disable-simplify-libcalls", 206 cl::desc("Disable simplify-libcalls")); 207 208 static cl::list<std::string> 209 DisableBuiltins("disable-builtin", 210 cl::desc("Disable specific target library builtin function"), 211 cl::ZeroOrMore); 212 213 static cl::opt<bool> 214 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization. " 215 "Legacy pass manager only.")); 216 217 static cl::opt<bool> EnableDebugify( 218 "enable-debugify", 219 cl::desc( 220 "Start the pipeline with debugify and end it with check-debugify")); 221 222 static cl::opt<bool> VerifyDebugInfoPreserve( 223 "verify-debuginfo-preserve", 224 cl::desc("Start the pipeline with collecting and end it with checking of " 225 "debug info preservation.")); 226 227 static cl::opt<bool> VerifyEachDebugInfoPreserve( 228 "verify-each-debuginfo-preserve", 229 cl::desc("Start each pass with collecting and end it with checking of " 230 "debug info preservation.")); 231 232 static cl::opt<std::string> 233 VerifyDIPreserveExport("verify-di-preserve-export", 234 cl::desc("Export debug info preservation failures into " 235 "specified (JSON) file (should be abs path as we use" 236 " append mode to insert new JSON objects)"), 237 cl::value_desc("filename"), cl::init("")); 238 239 static cl::opt<bool> 240 PrintBreakpoints("print-breakpoints-for-testing", 241 cl::desc("Print select breakpoints location for testing")); 242 243 static cl::opt<std::string> ClDataLayout("data-layout", 244 cl::desc("data layout string to use"), 245 cl::value_desc("layout-string"), 246 cl::init("")); 247 248 static cl::opt<bool> PreserveBitcodeUseListOrder( 249 "preserve-bc-uselistorder", 250 cl::desc("Preserve use-list order when writing LLVM bitcode."), 251 cl::init(true), cl::Hidden); 252 253 static cl::opt<bool> PreserveAssemblyUseListOrder( 254 "preserve-ll-uselistorder", 255 cl::desc("Preserve use-list order when writing LLVM assembly."), 256 cl::init(false), cl::Hidden); 257 258 static cl::opt<bool> RunTwice("run-twice", 259 cl::desc("Run all passes twice, re-using the " 260 "same pass manager (legacy PM only)."), 261 cl::init(false), cl::Hidden); 262 263 static cl::opt<bool> DiscardValueNames( 264 "discard-value-names", 265 cl::desc("Discard names from Value (other than GlobalValue)."), 266 cl::init(false), cl::Hidden); 267 268 static cl::opt<bool> Coroutines( 269 "enable-coroutines", 270 cl::desc("Enable coroutine passes."), 271 cl::init(false), cl::Hidden); 272 273 static cl::opt<bool> TimeTrace( 274 "time-trace", 275 cl::desc("Record time trace")); 276 277 static cl::opt<unsigned> TimeTraceGranularity( 278 "time-trace-granularity", 279 cl::desc("Minimum time granularity (in microseconds) traced by time profiler"), 280 cl::init(500), cl::Hidden); 281 282 static cl::opt<std::string> 283 TimeTraceFile("time-trace-file", 284 cl::desc("Specify time trace file destination"), 285 cl::value_desc("filename")); 286 287 static cl::opt<bool> RemarksWithHotness( 288 "pass-remarks-with-hotness", 289 cl::desc("With PGO, include profile count in optimization remarks"), 290 cl::Hidden); 291 292 static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser> 293 RemarksHotnessThreshold( 294 "pass-remarks-hotness-threshold", 295 cl::desc("Minimum profile count required for " 296 "an optimization remark to be output. " 297 "Use 'auto' to apply the threshold from profile summary."), 298 cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden); 299 300 static cl::opt<std::string> 301 RemarksFilename("pass-remarks-output", 302 cl::desc("Output filename for pass remarks"), 303 cl::value_desc("filename")); 304 305 static cl::opt<std::string> 306 RemarksPasses("pass-remarks-filter", 307 cl::desc("Only record optimization remarks from passes whose " 308 "names match the given regular expression"), 309 cl::value_desc("regex")); 310 311 static cl::opt<std::string> RemarksFormat( 312 "pass-remarks-format", 313 cl::desc("The format used for serializing remarks (default: YAML)"), 314 cl::value_desc("format"), cl::init("yaml")); 315 316 cl::opt<PGOKind> 317 PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden, 318 cl::desc("The kind of profile guided optimization"), 319 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."), 320 clEnumValN(InstrGen, "pgo-instr-gen-pipeline", 321 "Instrument the IR to generate profile."), 322 clEnumValN(InstrUse, "pgo-instr-use-pipeline", 323 "Use instrumented profile to guide PGO."), 324 clEnumValN(SampleUse, "pgo-sample-use-pipeline", 325 "Use sampled profile to guide PGO."))); 326 cl::opt<std::string> ProfileFile("profile-file", 327 cl::desc("Path to the profile."), cl::Hidden); 328 329 cl::opt<CSPGOKind> CSPGOKindFlag( 330 "cspgo-kind", cl::init(NoCSPGO), cl::Hidden, 331 cl::desc("The kind of context sensitive profile guided optimization"), 332 cl::values( 333 clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."), 334 clEnumValN( 335 CSInstrGen, "cspgo-instr-gen-pipeline", 336 "Instrument (context sensitive) the IR to generate profile."), 337 clEnumValN( 338 CSInstrUse, "cspgo-instr-use-pipeline", 339 "Use instrumented (context sensitive) profile to guide PGO."))); 340 cl::opt<std::string> CSProfileGenFile( 341 "cs-profilegen-file", 342 cl::desc("Path to the instrumented context sensitive profile."), 343 cl::Hidden); 344 345 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) { 346 // Add the pass to the pass manager... 347 PM.add(P); 348 349 // If we are verifying all of the intermediate steps, add the verifier... 350 if (VerifyEach) 351 PM.add(createVerifierPass()); 352 } 353 354 /// This routine adds optimization passes based on selected optimization level, 355 /// OptLevel. 356 /// 357 /// OptLevel - Optimization Level 358 static void AddOptimizationPasses(legacy::PassManagerBase &MPM, 359 legacy::FunctionPassManager &FPM, 360 TargetMachine *TM, unsigned OptLevel, 361 unsigned SizeLevel) { 362 if (!NoVerify || VerifyEach) 363 FPM.add(createVerifierPass()); // Verify that input is correct 364 365 PassManagerBuilder Builder; 366 Builder.OptLevel = OptLevel; 367 Builder.SizeLevel = SizeLevel; 368 369 if (DisableInline) { 370 // No inlining pass 371 } else if (OptLevel > 1) { 372 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false); 373 } else { 374 Builder.Inliner = createAlwaysInlinerLegacyPass(); 375 } 376 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ? 377 DisableLoopUnrolling : OptLevel == 0; 378 379 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; 380 381 Builder.SLPVectorize = OptLevel > 1 && SizeLevel < 2; 382 383 if (TM) 384 TM->adjustPassManager(Builder); 385 386 if (Coroutines) 387 addCoroutinePassesToExtensionPoints(Builder); 388 389 switch (PGOKindFlag) { 390 case InstrGen: 391 Builder.EnablePGOInstrGen = true; 392 Builder.PGOInstrGen = ProfileFile; 393 break; 394 case InstrUse: 395 Builder.PGOInstrUse = ProfileFile; 396 break; 397 case SampleUse: 398 Builder.PGOSampleUse = ProfileFile; 399 break; 400 default: 401 break; 402 } 403 404 switch (CSPGOKindFlag) { 405 case CSInstrGen: 406 Builder.EnablePGOCSInstrGen = true; 407 break; 408 case CSInstrUse: 409 Builder.EnablePGOCSInstrUse = true; 410 break; 411 default: 412 break; 413 } 414 415 Builder.populateFunctionPassManager(FPM); 416 Builder.populateModulePassManager(MPM); 417 } 418 419 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) { 420 PassManagerBuilder Builder; 421 Builder.VerifyInput = true; 422 if (DisableOptimizations) 423 Builder.OptLevel = 0; 424 425 if (!DisableInline) 426 Builder.Inliner = createFunctionInliningPass(); 427 Builder.populateLTOPassManager(PM); 428 } 429 430 //===----------------------------------------------------------------------===// 431 // CodeGen-related helper functions. 432 // 433 434 static CodeGenOpt::Level GetCodeGenOptLevel() { 435 if (CodeGenOptLevel.getNumOccurrences()) 436 return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel)); 437 if (OptLevelO1) 438 return CodeGenOpt::Less; 439 if (OptLevelO2) 440 return CodeGenOpt::Default; 441 if (OptLevelO3) 442 return CodeGenOpt::Aggressive; 443 return CodeGenOpt::None; 444 } 445 446 // Returns the TargetMachine instance or zero if no triple is provided. 447 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr, 448 StringRef FeaturesStr, 449 const TargetOptions &Options) { 450 std::string Error; 451 const Target *TheTarget = 452 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 453 // Some modules don't specify a triple, and this is okay. 454 if (!TheTarget) { 455 return nullptr; 456 } 457 458 return TheTarget->createTargetMachine( 459 TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(), 460 Options, codegen::getExplicitRelocModel(), 461 codegen::getExplicitCodeModel(), GetCodeGenOptLevel()); 462 } 463 464 #ifdef BUILD_EXAMPLES 465 void initializeExampleIRTransforms(llvm::PassRegistry &Registry); 466 #endif 467 468 struct TimeTracerRAII { 469 TimeTracerRAII(StringRef ProgramName) { 470 if (TimeTrace) 471 timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName); 472 } 473 ~TimeTracerRAII() { 474 if (TimeTrace) { 475 if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) { 476 handleAllErrors(std::move(E), [&](const StringError &SE) { 477 errs() << SE.getMessage() << "\n"; 478 }); 479 return; 480 } 481 timeTraceProfilerCleanup(); 482 } 483 } 484 }; 485 486 // For use in NPM transition. Currently this contains most codegen-specific 487 // passes. Remove passes from here when porting to the NPM. 488 // TODO: use a codegen version of PassRegistry.def/PassBuilder::is*Pass() once 489 // it exists. 490 static bool shouldPinPassToLegacyPM(StringRef Pass) { 491 std::vector<StringRef> PassNameExactToIgnore = { 492 "nvvm-reflect", 493 "nvvm-intr-range", 494 "amdgpu-simplifylib", 495 "amdgpu-usenative", 496 "amdgpu-promote-alloca", 497 "amdgpu-promote-alloca-to-vector", 498 "amdgpu-lower-kernel-attributes", 499 "amdgpu-propagate-attributes-early", 500 "amdgpu-propagate-attributes-late", 501 "amdgpu-unify-metadata", 502 "amdgpu-printf-runtime-binding", 503 "amdgpu-always-inline"}; 504 if (llvm::is_contained(PassNameExactToIgnore, Pass)) 505 return false; 506 507 std::vector<StringRef> PassNamePrefix = { 508 "x86-", "xcore-", "wasm-", "systemz-", "ppc-", "nvvm-", "nvptx-", 509 "mips-", "lanai-", "hexagon-", "bpf-", "avr-", "thumb2-", "arm-", 510 "si-", "gcn-", "amdgpu-", "aarch64-", "amdgcn-", "polly-"}; 511 std::vector<StringRef> PassNameContain = {"ehprepare"}; 512 std::vector<StringRef> PassNameExact = { 513 "safe-stack", "cost-model", 514 "codegenprepare", "interleaved-load-combine", 515 "unreachableblockelim", "verify-safepoint-ir", 516 "atomic-expand", 517 "hardware-loops", "type-promotion", 518 "mve-tail-predication", "interleaved-access", 519 "global-merge", "pre-isel-intrinsic-lowering", 520 "expand-reductions", "indirectbr-expand", 521 "generic-to-nvvm", "expandmemcmp", 522 "loop-reduce", "lower-amx-type", 523 "lower-amx-intrinsics", "polyhedral-info", 524 "replace-with-veclib"}; 525 for (const auto &P : PassNamePrefix) 526 if (Pass.startswith(P)) 527 return true; 528 for (const auto &P : PassNameContain) 529 if (Pass.contains(P)) 530 return true; 531 return llvm::is_contained(PassNameExact, Pass); 532 } 533 534 // For use in NPM transition. 535 static bool shouldForceLegacyPM() { 536 for (const auto &P : PassList) { 537 StringRef Arg = P->getPassArgument(); 538 if (shouldPinPassToLegacyPM(Arg)) 539 return true; 540 } 541 return false; 542 } 543 544 //===----------------------------------------------------------------------===// 545 // main for opt 546 // 547 int main(int argc, char **argv) { 548 InitLLVM X(argc, argv); 549 550 // Enable debug stream buffering. 551 EnableDebugBuffering = true; 552 553 LLVMContext Context; 554 555 InitializeAllTargets(); 556 InitializeAllTargetMCs(); 557 InitializeAllAsmPrinters(); 558 InitializeAllAsmParsers(); 559 560 // Initialize passes 561 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 562 initializeCore(Registry); 563 initializeCoroutines(Registry); 564 initializeScalarOpts(Registry); 565 initializeObjCARCOpts(Registry); 566 initializeVectorization(Registry); 567 initializeIPO(Registry); 568 initializeAnalysis(Registry); 569 initializeTransformUtils(Registry); 570 initializeInstCombine(Registry); 571 initializeAggressiveInstCombine(Registry); 572 initializeInstrumentation(Registry); 573 initializeTarget(Registry); 574 // For codegen passes, only passes that do IR to IR transformation are 575 // supported. 576 initializeExpandMemCmpPassPass(Registry); 577 initializeScalarizeMaskedMemIntrinLegacyPassPass(Registry); 578 initializeCodeGenPreparePass(Registry); 579 initializeAtomicExpandPass(Registry); 580 initializeRewriteSymbolsLegacyPassPass(Registry); 581 initializeWinEHPreparePass(Registry); 582 initializeDwarfEHPrepareLegacyPassPass(Registry); 583 initializeSafeStackLegacyPassPass(Registry); 584 initializeSjLjEHPreparePass(Registry); 585 initializePreISelIntrinsicLoweringLegacyPassPass(Registry); 586 initializeGlobalMergePass(Registry); 587 initializeIndirectBrExpandPassPass(Registry); 588 initializeInterleavedLoadCombinePass(Registry); 589 initializeInterleavedAccessPass(Registry); 590 initializeEntryExitInstrumenterPass(Registry); 591 initializePostInlineEntryExitInstrumenterPass(Registry); 592 initializeUnreachableBlockElimLegacyPassPass(Registry); 593 initializeExpandReductionsPass(Registry); 594 initializeWasmEHPreparePass(Registry); 595 initializeWriteBitcodePassPass(Registry); 596 initializeHardwareLoopsPass(Registry); 597 initializeTypePromotionPass(Registry); 598 initializeReplaceWithVeclibLegacyPass(Registry); 599 600 #ifdef BUILD_EXAMPLES 601 initializeExampleIRTransforms(Registry); 602 #endif 603 604 cl::ParseCommandLineOptions(argc, argv, 605 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 606 607 if (AnalyzeOnly && NoOutput) { 608 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 609 return 1; 610 } 611 612 // FIXME: once the legacy PM code is deleted, move runPassPipeline() here and 613 // construct the PassBuilder before parsing IR so we can reuse the same 614 // PassBuilder for print passes. 615 if (PrintPasses) { 616 printPasses(outs()); 617 return 0; 618 } 619 620 TimeTracerRAII TimeTracer(argv[0]); 621 622 SMDiagnostic Err; 623 624 Context.setDiscardValueNames(DiscardValueNames); 625 if (!DisableDITypeMap) 626 Context.enableDebugTypeODRUniquing(); 627 628 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 629 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 630 RemarksFormat, RemarksWithHotness, 631 RemarksHotnessThreshold); 632 if (Error E = RemarksFileOrErr.takeError()) { 633 errs() << toString(std::move(E)) << '\n'; 634 return 1; 635 } 636 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 637 638 // Load the input module... 639 auto SetDataLayout = [](StringRef) -> Optional<std::string> { 640 if (ClDataLayout.empty()) 641 return None; 642 return ClDataLayout; 643 }; 644 std::unique_ptr<Module> M; 645 if (NoUpgradeDebugInfo) 646 M = parseAssemblyFileWithIndexNoUpgradeDebugInfo( 647 InputFilename, Err, Context, nullptr, SetDataLayout) 648 .Mod; 649 else 650 M = parseIRFile(InputFilename, Err, Context, SetDataLayout); 651 652 if (!M) { 653 Err.print(argv[0], errs()); 654 return 1; 655 } 656 657 // Strip debug info before running the verifier. 658 if (StripDebug) 659 StripDebugInfo(*M); 660 661 // Erase module-level named metadata, if requested. 662 if (StripNamedMetadata) { 663 while (!M->named_metadata_empty()) { 664 NamedMDNode *NMD = &*M->named_metadata_begin(); 665 M->eraseNamedMetadata(NMD); 666 } 667 } 668 669 // If we are supposed to override the target triple or data layout, do so now. 670 if (!TargetTriple.empty()) 671 M->setTargetTriple(Triple::normalize(TargetTriple)); 672 673 // Immediately run the verifier to catch any problems before starting up the 674 // pass pipelines. Otherwise we can crash on broken code during 675 // doInitialization(). 676 if (!NoVerify && verifyModule(*M, &errs())) { 677 errs() << argv[0] << ": " << InputFilename 678 << ": error: input module is broken!\n"; 679 return 1; 680 } 681 682 // Enable testing of whole program devirtualization on this module by invoking 683 // the facility for updating public visibility to linkage unit visibility when 684 // specified by an internal option. This is normally done during LTO which is 685 // not performed via opt. 686 updateVCallVisibilityInModule(*M, 687 /* WholeProgramVisibilityEnabledInLTO */ false, 688 /* DynamicExportSymbols */ {}); 689 690 // Figure out what stream we are supposed to write to... 691 std::unique_ptr<ToolOutputFile> Out; 692 std::unique_ptr<ToolOutputFile> ThinLinkOut; 693 if (NoOutput) { 694 if (!OutputFilename.empty()) 695 errs() << "WARNING: The -o (output filename) option is ignored when\n" 696 "the --disable-output option is used.\n"; 697 } else { 698 // Default to standard output. 699 if (OutputFilename.empty()) 700 OutputFilename = "-"; 701 702 std::error_code EC; 703 sys::fs::OpenFlags Flags = 704 OutputAssembly ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None; 705 Out.reset(new ToolOutputFile(OutputFilename, EC, Flags)); 706 if (EC) { 707 errs() << EC.message() << '\n'; 708 return 1; 709 } 710 711 if (!ThinLinkBitcodeFile.empty()) { 712 ThinLinkOut.reset( 713 new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None)); 714 if (EC) { 715 errs() << EC.message() << '\n'; 716 return 1; 717 } 718 } 719 } 720 721 Triple ModuleTriple(M->getTargetTriple()); 722 std::string CPUStr, FeaturesStr; 723 TargetMachine *Machine = nullptr; 724 const TargetOptions Options = 725 codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple); 726 727 if (ModuleTriple.getArch()) { 728 CPUStr = codegen::getCPUStr(); 729 FeaturesStr = codegen::getFeaturesStr(); 730 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options); 731 } else if (ModuleTriple.getArchName() != "unknown" && 732 ModuleTriple.getArchName() != "") { 733 errs() << argv[0] << ": unrecognized architecture '" 734 << ModuleTriple.getArchName() << "' provided.\n"; 735 return 1; 736 } 737 738 std::unique_ptr<TargetMachine> TM(Machine); 739 740 // Override function attributes based on CPUStr, FeaturesStr, and command line 741 // flags. 742 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M); 743 744 // If the output is set to be emitted to standard out, and standard out is a 745 // console, print out a warning message and refuse to do it. We don't 746 // impress anyone by spewing tons of binary goo to a terminal. 747 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 748 if (CheckBitcodeOutputToConsole(Out->os())) 749 NoOutput = true; 750 751 if (OutputThinLTOBC) 752 M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit); 753 754 // Add an appropriate TargetLibraryInfo pass for the module's triple. 755 TargetLibraryInfoImpl TLII(ModuleTriple); 756 757 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 758 if (DisableSimplifyLibCalls) 759 TLII.disableAllFunctions(); 760 else { 761 // Disable individual builtin functions in TargetLibraryInfo. 762 LibFunc F; 763 for (auto &FuncName : DisableBuiltins) 764 if (TLII.getLibFunc(FuncName, F)) 765 TLII.setUnavailable(F); 766 else { 767 errs() << argv[0] << ": cannot disable nonexistent builtin function " 768 << FuncName << '\n'; 769 return 1; 770 } 771 } 772 773 // If `-passes=` is specified, use NPM. 774 // If `-enable-new-pm` is specified and there are no codegen passes, use NPM. 775 // e.g. `-enable-new-pm -sroa` will use NPM. 776 // but `-enable-new-pm -codegenprepare` will still revert to legacy PM. 777 if ((EnableNewPassManager && !shouldForceLegacyPM()) || 778 PassPipeline.getNumOccurrences() > 0) { 779 if (AnalyzeOnly) { 780 errs() << "Cannot specify -analyze under new pass manager, either " 781 "specify '-enable-new-pm=0', or use the corresponding new pass " 782 "manager pass, e.g. '-passes=print<scalar-evolution>'. For a " 783 "full list of passes, see the '--print-passes' flag.\n"; 784 return 1; 785 } 786 if (legacy::debugPassSpecified()) { 787 errs() 788 << "-debug-pass does not work with the new PM, either use " 789 "-debug-pass-manager, or use the legacy PM (-enable-new-pm=0)\n"; 790 return 1; 791 } 792 if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) { 793 errs() 794 << "Cannot specify passes via both -foo-pass and --passes=foo-pass\n"; 795 return 1; 796 } 797 SmallVector<StringRef, 4> Passes; 798 if (OptLevelO0) 799 Passes.push_back("default<O0>"); 800 if (OptLevelO1) 801 Passes.push_back("default<O1>"); 802 if (OptLevelO2) 803 Passes.push_back("default<O2>"); 804 if (OptLevelO3) 805 Passes.push_back("default<O3>"); 806 if (OptLevelOs) 807 Passes.push_back("default<Os>"); 808 if (OptLevelOz) 809 Passes.push_back("default<Oz>"); 810 for (const auto &P : PassList) 811 Passes.push_back(P->getPassArgument()); 812 OutputKind OK = OK_NoOutput; 813 if (!NoOutput) 814 OK = OutputAssembly 815 ? OK_OutputAssembly 816 : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode); 817 818 VerifierKind VK = VK_VerifyInAndOut; 819 if (NoVerify) 820 VK = VK_NoVerifier; 821 else if (VerifyEach) 822 VK = VK_VerifyEachPass; 823 824 // The user has asked to use the new pass manager and provided a pipeline 825 // string. Hand off the rest of the functionality to the new code for that 826 // layer. 827 return runPassPipeline(argv[0], *M, TM.get(), &TLII, Out.get(), 828 ThinLinkOut.get(), RemarksFile.get(), PassPipeline, 829 Passes, OK, VK, PreserveAssemblyUseListOrder, 830 PreserveBitcodeUseListOrder, EmitSummaryIndex, 831 EmitModuleHash, EnableDebugify, Coroutines) 832 ? 0 833 : 1; 834 } 835 836 // Create a PassManager to hold and optimize the collection of passes we are 837 // about to build. If the -debugify-each option is set, wrap each pass with 838 // the (-check)-debugify passes. 839 DebugifyCustomPassManager Passes; 840 DebugifyStatsMap DIStatsMap; 841 DebugInfoPerPassMap DIPreservationMap; 842 if (DebugifyEach) { 843 Passes.setDebugifyMode(DebugifyMode::SyntheticDebugInfo); 844 Passes.setDIStatsMap(DIStatsMap); 845 } else if (VerifyEachDebugInfoPreserve) { 846 Passes.setDebugifyMode(DebugifyMode::OriginalDebugInfo); 847 Passes.setDIPreservationMap(DIPreservationMap); 848 if (!VerifyDIPreserveExport.empty()) 849 Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport); 850 } 851 852 bool AddOneTimeDebugifyPasses = 853 (EnableDebugify && !DebugifyEach) || 854 (VerifyDebugInfoPreserve && !VerifyEachDebugInfoPreserve); 855 856 Passes.add(new TargetLibraryInfoWrapperPass(TLII)); 857 858 // Add internal analysis passes from the target machine. 859 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis() 860 : TargetIRAnalysis())); 861 862 if (AddOneTimeDebugifyPasses) { 863 if (EnableDebugify) { 864 Passes.setDIStatsMap(DIStatsMap); 865 Passes.add(createDebugifyModulePass()); 866 } else if (VerifyDebugInfoPreserve) { 867 Passes.setDIPreservationMap(DIPreservationMap); 868 Passes.add(createDebugifyModulePass( 869 DebugifyMode::OriginalDebugInfo, "", 870 &(Passes.getDebugInfoPerPassMap()))); 871 } 872 } 873 874 std::unique_ptr<legacy::FunctionPassManager> FPasses; 875 if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || 876 OptLevelO3) { 877 FPasses.reset(new legacy::FunctionPassManager(M.get())); 878 FPasses->add(createTargetTransformInfoWrapperPass( 879 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); 880 } 881 882 if (PrintBreakpoints) { 883 // Default to standard output. 884 if (!Out) { 885 if (OutputFilename.empty()) 886 OutputFilename = "-"; 887 888 std::error_code EC; 889 Out = std::make_unique<ToolOutputFile>(OutputFilename, EC, 890 sys::fs::OF_None); 891 if (EC) { 892 errs() << EC.message() << '\n'; 893 return 1; 894 } 895 } 896 Passes.add(createBreakpointPrinter(Out->os())); 897 NoOutput = true; 898 } 899 900 if (TM) { 901 // FIXME: We should dyn_cast this when supported. 902 auto <M = static_cast<LLVMTargetMachine &>(*TM); 903 Pass *TPC = LTM.createPassConfig(Passes); 904 Passes.add(TPC); 905 } 906 907 // Create a new optimization pass for each one specified on the command line 908 for (unsigned i = 0; i < PassList.size(); ++i) { 909 if (StandardLinkOpts && 910 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 911 AddStandardLinkPasses(Passes); 912 StandardLinkOpts = false; 913 } 914 915 if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) { 916 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 917 OptLevelO0 = false; 918 } 919 920 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 921 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 922 OptLevelO1 = false; 923 } 924 925 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 926 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 927 OptLevelO2 = false; 928 } 929 930 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 931 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 932 OptLevelOs = false; 933 } 934 935 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 936 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 937 OptLevelOz = false; 938 } 939 940 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 941 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 942 OptLevelO3 = false; 943 } 944 945 const PassInfo *PassInf = PassList[i]; 946 Pass *P = nullptr; 947 if (PassInf->getNormalCtor()) 948 P = PassInf->getNormalCtor()(); 949 else 950 errs() << argv[0] << ": cannot create pass: " 951 << PassInf->getPassName() << "\n"; 952 if (P) { 953 PassKind Kind = P->getPassKind(); 954 addPass(Passes, P); 955 956 if (AnalyzeOnly) { 957 switch (Kind) { 958 case PT_Region: 959 Passes.add(createRegionPassPrinter(PassInf, Out->os())); 960 break; 961 case PT_Loop: 962 Passes.add(createLoopPassPrinter(PassInf, Out->os())); 963 break; 964 case PT_Function: 965 Passes.add(createFunctionPassPrinter(PassInf, Out->os())); 966 break; 967 case PT_CallGraphSCC: 968 Passes.add(createCallGraphPassPrinter(PassInf, Out->os())); 969 break; 970 default: 971 Passes.add(createModulePassPrinter(PassInf, Out->os())); 972 break; 973 } 974 } 975 } 976 977 if (PrintEachXForm) 978 Passes.add( 979 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder)); 980 } 981 982 if (StandardLinkOpts) { 983 AddStandardLinkPasses(Passes); 984 StandardLinkOpts = false; 985 } 986 987 if (OptLevelO0) 988 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 989 990 if (OptLevelO1) 991 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 992 993 if (OptLevelO2) 994 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 995 996 if (OptLevelOs) 997 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 998 999 if (OptLevelOz) 1000 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 1001 1002 if (OptLevelO3) 1003 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 1004 1005 if (FPasses) { 1006 FPasses->doInitialization(); 1007 for (Function &F : *M) 1008 FPasses->run(F); 1009 FPasses->doFinalization(); 1010 } 1011 1012 // Check that the module is well formed on completion of optimization 1013 if (!NoVerify && !VerifyEach) 1014 Passes.add(createVerifierPass()); 1015 1016 if (AddOneTimeDebugifyPasses) { 1017 if (EnableDebugify) 1018 Passes.add(createCheckDebugifyModulePass(false)); 1019 else if (VerifyDebugInfoPreserve) { 1020 if (!VerifyDIPreserveExport.empty()) 1021 Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport); 1022 Passes.add(createCheckDebugifyModulePass( 1023 false, "", nullptr, DebugifyMode::OriginalDebugInfo, 1024 &(Passes.getDebugInfoPerPassMap()), VerifyDIPreserveExport)); 1025 } 1026 } 1027 1028 // In run twice mode, we want to make sure the output is bit-by-bit 1029 // equivalent if we run the pass manager again, so setup two buffers and 1030 // a stream to write to them. Note that llc does something similar and it 1031 // may be worth to abstract this out in the future. 1032 SmallVector<char, 0> Buffer; 1033 SmallVector<char, 0> FirstRunBuffer; 1034 std::unique_ptr<raw_svector_ostream> BOS; 1035 raw_ostream *OS = nullptr; 1036 1037 const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly; 1038 1039 // Write bitcode or assembly to the output as the last step... 1040 if (ShouldEmitOutput || RunTwice) { 1041 assert(Out); 1042 OS = &Out->os(); 1043 if (RunTwice) { 1044 BOS = std::make_unique<raw_svector_ostream>(Buffer); 1045 OS = BOS.get(); 1046 } 1047 if (OutputAssembly) { 1048 if (EmitSummaryIndex) 1049 report_fatal_error("Text output is incompatible with -module-summary"); 1050 if (EmitModuleHash) 1051 report_fatal_error("Text output is incompatible with -module-hash"); 1052 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder)); 1053 } else if (OutputThinLTOBC) 1054 Passes.add(createWriteThinLTOBitcodePass( 1055 *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr)); 1056 else 1057 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder, 1058 EmitSummaryIndex, EmitModuleHash)); 1059 } 1060 1061 // Before executing passes, print the final values of the LLVM options. 1062 cl::PrintOptionValues(); 1063 1064 if (!RunTwice) { 1065 // Now that we have all of the passes ready, run them. 1066 Passes.run(*M); 1067 } else { 1068 // If requested, run all passes twice with the same pass manager to catch 1069 // bugs caused by persistent state in the passes. 1070 std::unique_ptr<Module> M2(CloneModule(*M)); 1071 // Run all passes on the original module first, so the second run processes 1072 // the clone to catch CloneModule bugs. 1073 Passes.run(*M); 1074 FirstRunBuffer = Buffer; 1075 Buffer.clear(); 1076 1077 Passes.run(*M2); 1078 1079 // Compare the two outputs and make sure they're the same 1080 assert(Out); 1081 if (Buffer.size() != FirstRunBuffer.size() || 1082 (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) { 1083 errs() 1084 << "Running the pass manager twice changed the output.\n" 1085 "Writing the result of the second run to the specified output.\n" 1086 "To generate the one-run comparison binary, just run without\n" 1087 "the compile-twice option\n"; 1088 if (ShouldEmitOutput) { 1089 Out->os() << BOS->str(); 1090 Out->keep(); 1091 } 1092 if (RemarksFile) 1093 RemarksFile->keep(); 1094 return 1; 1095 } 1096 if (ShouldEmitOutput) 1097 Out->os() << BOS->str(); 1098 } 1099 1100 if (DebugifyEach && !DebugifyExport.empty()) 1101 exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap()); 1102 1103 // Declare success. 1104 if (!NoOutput || PrintBreakpoints) 1105 Out->keep(); 1106 1107 if (RemarksFile) 1108 RemarksFile->keep(); 1109 1110 if (ThinLinkOut) 1111 ThinLinkOut->keep(); 1112 1113 return 0; 1114 } 1115