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