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