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