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