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