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