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