1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Optimizations may be specified an arbitrary number of times on the command 10 // line, They are run in the order specified. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "BreakpointPrinter.h" 15 #include "NewPMDriver.h" 16 #include "PassPrinters.h" 17 #include "llvm/ADT/Triple.h" 18 #include "llvm/Analysis/CallGraph.h" 19 #include "llvm/Analysis/CallGraphSCCPass.h" 20 #include "llvm/Analysis/LoopPass.h" 21 #include "llvm/Analysis/RegionPass.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Bitcode/BitcodeWriterPass.h" 25 #include "llvm/CodeGen/CommandFlags.h" 26 #include "llvm/CodeGen/TargetPassConfig.h" 27 #include "llvm/Config/llvm-config.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/LLVMRemarkStreamer.h" 33 #include "llvm/IR/LegacyPassManager.h" 34 #include "llvm/IR/LegacyPassNameParser.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/Verifier.h" 37 #include "llvm/IRReader/IRReader.h" 38 #include "llvm/InitializePasses.h" 39 #include "llvm/LinkAllIR.h" 40 #include "llvm/LinkAllPasses.h" 41 #include "llvm/MC/SubtargetFeature.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/Host.h" 45 #include "llvm/Support/InitLLVM.h" 46 #include "llvm/Support/PluginLoader.h" 47 #include "llvm/Support/SourceMgr.h" 48 #include "llvm/Support/SystemUtils.h" 49 #include "llvm/Support/TargetRegistry.h" 50 #include "llvm/Support/TargetSelect.h" 51 #include "llvm/Support/ToolOutputFile.h" 52 #include "llvm/Support/YAMLTraits.h" 53 #include "llvm/Target/TargetMachine.h" 54 #include "llvm/Transforms/Coroutines.h" 55 #include "llvm/Transforms/IPO/AlwaysInliner.h" 56 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 57 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 58 #include "llvm/Transforms/Utils/Cloning.h" 59 #include "llvm/Transforms/Utils/Debugify.h" 60 #include <algorithm> 61 #include <memory> 62 using namespace llvm; 63 using namespace opt_tool; 64 65 static codegen::RegisterCodeGenFlags CFG; 66 67 // The OptimizationList is automatically populated with registered Passes by the 68 // PassNameParser. 69 // 70 static cl::list<const PassInfo*, bool, PassNameParser> 71 PassList(cl::desc("Optimizations available:")); 72 73 // This flag specifies a textual description of the optimization pass pipeline 74 // to run over the module. This flag switches opt to use the new pass manager 75 // infrastructure, completely disabling all of the flags specific to the old 76 // pass management. 77 static cl::opt<std::string> PassPipeline( 78 "passes", 79 cl::desc("A textual description of the pass pipeline for optimizing"), 80 cl::Hidden); 81 82 // Other command line options... 83 // 84 static cl::opt<std::string> 85 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 86 cl::init("-"), cl::value_desc("filename")); 87 88 static cl::opt<std::string> 89 OutputFilename("o", cl::desc("Override output filename"), 90 cl::value_desc("filename")); 91 92 static cl::opt<bool> 93 Force("f", cl::desc("Enable binary output on terminals")); 94 95 static cl::opt<bool> 96 PrintEachXForm("p", cl::desc("Print module after each transformation")); 97 98 static cl::opt<bool> 99 NoOutput("disable-output", 100 cl::desc("Do not write result bitcode file"), cl::Hidden); 101 102 static cl::opt<bool> 103 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 104 105 static cl::opt<bool> 106 OutputThinLTOBC("thinlto-bc", 107 cl::desc("Write output as ThinLTO-ready bitcode")); 108 109 static cl::opt<bool> 110 SplitLTOUnit("thinlto-split-lto-unit", 111 cl::desc("Enable splitting of a ThinLTO LTOUnit")); 112 113 static cl::opt<std::string> ThinLinkBitcodeFile( 114 "thin-link-bitcode-file", cl::value_desc("filename"), 115 cl::desc( 116 "A file in which to write minimized bitcode for the thin link only")); 117 118 static cl::opt<bool> 119 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden); 120 121 static cl::opt<bool> 122 VerifyEach("verify-each", cl::desc("Verify after each transform")); 123 124 static cl::opt<bool> 125 DisableDITypeMap("disable-debug-info-type-map", 126 cl::desc("Don't use a uniquing type map for debug info")); 127 128 static cl::opt<bool> 129 StripDebug("strip-debug", 130 cl::desc("Strip debugger symbol info from translation unit")); 131 132 static cl::opt<bool> 133 StripNamedMetadata("strip-named-metadata", 134 cl::desc("Strip module-level named metadata")); 135 136 static cl::opt<bool> DisableInline("disable-inlining", 137 cl::desc("Do not run the inliner pass")); 138 139 static cl::opt<bool> 140 DisableOptimizations("disable-opt", 141 cl::desc("Do not run any optimization passes")); 142 143 static cl::opt<bool> 144 StandardLinkOpts("std-link-opts", 145 cl::desc("Include the standard link time optimizations")); 146 147 static cl::opt<bool> 148 OptLevelO0("O0", 149 cl::desc("Optimization level 0. Similar to clang -O0")); 150 151 static cl::opt<bool> 152 OptLevelO1("O1", 153 cl::desc("Optimization level 1. Similar to clang -O1")); 154 155 static cl::opt<bool> 156 OptLevelO2("O2", 157 cl::desc("Optimization level 2. Similar to clang -O2")); 158 159 static cl::opt<bool> 160 OptLevelOs("Os", 161 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); 162 163 static cl::opt<bool> 164 OptLevelOz("Oz", 165 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); 166 167 static cl::opt<bool> 168 OptLevelO3("O3", 169 cl::desc("Optimization level 3. Similar to clang -O3")); 170 171 static cl::opt<unsigned> 172 CodeGenOptLevel("codegen-opt-level", 173 cl::desc("Override optimization level for codegen hooks")); 174 175 static cl::opt<std::string> 176 TargetTriple("mtriple", cl::desc("Override target triple for module")); 177 178 static cl::opt<bool> 179 DisableLoopUnrolling("disable-loop-unrolling", 180 cl::desc("Disable loop unrolling in all relevant passes"), 181 cl::init(false)); 182 183 static cl::opt<bool> 184 DisableSLPVectorization("disable-slp-vectorization", 185 cl::desc("Disable the slp vectorization pass"), 186 cl::init(false)); 187 188 static cl::opt<bool> EmitSummaryIndex("module-summary", 189 cl::desc("Emit module summary index"), 190 cl::init(false)); 191 192 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"), 193 cl::init(false)); 194 195 static cl::opt<bool> 196 DisableSimplifyLibCalls("disable-simplify-libcalls", 197 cl::desc("Disable simplify-libcalls")); 198 199 static cl::list<std::string> 200 DisableBuiltins("disable-builtin", 201 cl::desc("Disable specific target library builtin function"), 202 cl::ZeroOrMore); 203 204 205 static cl::opt<bool> 206 Quiet("q", cl::desc("Obsolete option"), cl::Hidden); 207 208 static cl::alias 209 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet)); 210 211 static cl::opt<bool> 212 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization")); 213 214 static cl::opt<bool> EnableDebugify( 215 "enable-debugify", 216 cl::desc( 217 "Start the pipeline with debugify and end it with check-debugify")); 218 219 static cl::opt<bool> DebugifyEach( 220 "debugify-each", 221 cl::desc( 222 "Start each pass with debugify and end it with check-debugify")); 223 224 static cl::opt<std::string> 225 DebugifyExport("debugify-export", 226 cl::desc("Export per-pass debugify statistics to this file"), 227 cl::value_desc("filename"), cl::init("")); 228 229 static cl::opt<bool> 230 PrintBreakpoints("print-breakpoints-for-testing", 231 cl::desc("Print select breakpoints location for testing")); 232 233 static cl::opt<std::string> ClDataLayout("data-layout", 234 cl::desc("data layout string to use"), 235 cl::value_desc("layout-string"), 236 cl::init("")); 237 238 static cl::opt<bool> PreserveBitcodeUseListOrder( 239 "preserve-bc-uselistorder", 240 cl::desc("Preserve use-list order when writing LLVM bitcode."), 241 cl::init(true), cl::Hidden); 242 243 static cl::opt<bool> PreserveAssemblyUseListOrder( 244 "preserve-ll-uselistorder", 245 cl::desc("Preserve use-list order when writing LLVM assembly."), 246 cl::init(false), cl::Hidden); 247 248 static cl::opt<bool> 249 RunTwice("run-twice", 250 cl::desc("Run all passes twice, re-using the same pass manager."), 251 cl::init(false), cl::Hidden); 252 253 static cl::opt<bool> DiscardValueNames( 254 "discard-value-names", 255 cl::desc("Discard names from Value (other than GlobalValue)."), 256 cl::init(false), cl::Hidden); 257 258 static cl::opt<bool> Coroutines( 259 "enable-coroutines", 260 cl::desc("Enable coroutine passes."), 261 cl::init(false), cl::Hidden); 262 263 static cl::opt<bool> TimeTrace( 264 "time-trace", 265 cl::desc("Record time trace")); 266 267 static cl::opt<unsigned> TimeTraceGranularity( 268 "time-trace-granularity", 269 cl::desc("Minimum time granularity (in microseconds) traced by time profiler"), 270 cl::init(500), cl::Hidden); 271 272 static cl::opt<std::string> 273 TimeTraceFile("time-trace-file", 274 cl::desc("Specify time trace file destination"), 275 cl::value_desc("filename")); 276 277 static cl::opt<bool> RemarksWithHotness( 278 "pass-remarks-with-hotness", 279 cl::desc("With PGO, include profile count in optimization remarks"), 280 cl::Hidden); 281 282 static cl::opt<unsigned> 283 RemarksHotnessThreshold("pass-remarks-hotness-threshold", 284 cl::desc("Minimum profile count required for " 285 "an optimization remark to be output"), 286 cl::Hidden); 287 288 static cl::opt<std::string> 289 RemarksFilename("pass-remarks-output", 290 cl::desc("Output filename for pass remarks"), 291 cl::value_desc("filename")); 292 293 static cl::opt<std::string> 294 RemarksPasses("pass-remarks-filter", 295 cl::desc("Only record optimization remarks from passes whose " 296 "names match the given regular expression"), 297 cl::value_desc("regex")); 298 299 static cl::opt<std::string> RemarksFormat( 300 "pass-remarks-format", 301 cl::desc("The format used for serializing remarks (default: YAML)"), 302 cl::value_desc("format"), cl::init("yaml")); 303 304 cl::opt<PGOKind> 305 PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden, 306 cl::desc("The kind of profile guided optimization"), 307 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."), 308 clEnumValN(InstrGen, "pgo-instr-gen-pipeline", 309 "Instrument the IR to generate profile."), 310 clEnumValN(InstrUse, "pgo-instr-use-pipeline", 311 "Use instrumented profile to guide PGO."), 312 clEnumValN(SampleUse, "pgo-sample-use-pipeline", 313 "Use sampled profile to guide PGO."))); 314 cl::opt<std::string> ProfileFile("profile-file", 315 cl::desc("Path to the profile."), cl::Hidden); 316 317 cl::opt<CSPGOKind> CSPGOKindFlag( 318 "cspgo-kind", cl::init(NoCSPGO), cl::Hidden, 319 cl::desc("The kind of context sensitive profile guided optimization"), 320 cl::values( 321 clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."), 322 clEnumValN( 323 CSInstrGen, "cspgo-instr-gen-pipeline", 324 "Instrument (context sensitive) the IR to generate profile."), 325 clEnumValN( 326 CSInstrUse, "cspgo-instr-use-pipeline", 327 "Use instrumented (context sensitive) profile to guide PGO."))); 328 cl::opt<std::string> CSProfileGenFile( 329 "cs-profilegen-file", 330 cl::desc("Path to the instrumented context sensitive profile."), 331 cl::Hidden); 332 333 class OptCustomPassManager : public legacy::PassManager { 334 DebugifyStatsMap DIStatsMap; 335 336 public: 337 using super = legacy::PassManager; 338 339 void add(Pass *P) override { 340 // Wrap each pass with (-check)-debugify passes if requested, making 341 // exceptions for passes which shouldn't see -debugify instrumentation. 342 bool WrapWithDebugify = DebugifyEach && !P->getAsImmutablePass() && 343 !isIRPrintingPass(P) && !isBitcodeWriterPass(P); 344 if (!WrapWithDebugify) { 345 super::add(P); 346 return; 347 } 348 349 // Apply -debugify/-check-debugify before/after each pass and collect 350 // debug info loss statistics. 351 PassKind Kind = P->getPassKind(); 352 StringRef Name = P->getPassName(); 353 354 // TODO: Implement Debugify for LoopPass. 355 switch (Kind) { 356 case PT_Function: 357 super::add(createDebugifyFunctionPass()); 358 super::add(P); 359 super::add(createCheckDebugifyFunctionPass(true, Name, &DIStatsMap)); 360 break; 361 case PT_Module: 362 super::add(createDebugifyModulePass()); 363 super::add(P); 364 super::add(createCheckDebugifyModulePass(true, Name, &DIStatsMap)); 365 break; 366 default: 367 super::add(P); 368 break; 369 } 370 } 371 372 const DebugifyStatsMap &getDebugifyStatsMap() const { return DIStatsMap; } 373 }; 374 375 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) { 376 // Add the pass to the pass manager... 377 PM.add(P); 378 379 // If we are verifying all of the intermediate steps, add the verifier... 380 if (VerifyEach) 381 PM.add(createVerifierPass()); 382 } 383 384 /// This routine adds optimization passes based on selected optimization level, 385 /// OptLevel. 386 /// 387 /// OptLevel - Optimization Level 388 static void AddOptimizationPasses(legacy::PassManagerBase &MPM, 389 legacy::FunctionPassManager &FPM, 390 TargetMachine *TM, unsigned OptLevel, 391 unsigned SizeLevel) { 392 if (!NoVerify || VerifyEach) 393 FPM.add(createVerifierPass()); // Verify that input is correct 394 395 PassManagerBuilder Builder; 396 Builder.OptLevel = OptLevel; 397 Builder.SizeLevel = SizeLevel; 398 399 if (DisableInline) { 400 // No inlining pass 401 } else if (OptLevel > 1) { 402 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false); 403 } else { 404 Builder.Inliner = createAlwaysInlinerLegacyPass(); 405 } 406 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ? 407 DisableLoopUnrolling : OptLevel == 0; 408 409 // Check if vectorization is explicitly disabled via -vectorize-loops=false. 410 // The flag enables vectorization in the LoopVectorize pass, it is on by 411 // default, and if it was disabled, leave it disabled here. 412 // Another flag that exists: -loop-vectorize, controls adding the pass to the 413 // pass manager. If set, the pass is added, and there is no additional check 414 // here for it. 415 if (Builder.LoopVectorize) 416 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; 417 418 // When #pragma vectorize is on for SLP, do the same as above 419 Builder.SLPVectorize = 420 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2; 421 422 if (TM) 423 TM->adjustPassManager(Builder); 424 425 if (Coroutines) 426 addCoroutinePassesToExtensionPoints(Builder); 427 428 switch (PGOKindFlag) { 429 case InstrGen: 430 Builder.EnablePGOInstrGen = true; 431 Builder.PGOInstrGen = ProfileFile; 432 break; 433 case InstrUse: 434 Builder.PGOInstrUse = ProfileFile; 435 break; 436 case SampleUse: 437 Builder.PGOSampleUse = ProfileFile; 438 break; 439 default: 440 break; 441 } 442 443 switch (CSPGOKindFlag) { 444 case CSInstrGen: 445 Builder.EnablePGOCSInstrGen = true; 446 break; 447 case CSInstrUse: 448 Builder.EnablePGOCSInstrUse = true; 449 break; 450 default: 451 break; 452 } 453 454 Builder.populateFunctionPassManager(FPM); 455 Builder.populateModulePassManager(MPM); 456 } 457 458 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) { 459 PassManagerBuilder Builder; 460 Builder.VerifyInput = true; 461 if (DisableOptimizations) 462 Builder.OptLevel = 0; 463 464 if (!DisableInline) 465 Builder.Inliner = createFunctionInliningPass(); 466 Builder.populateLTOPassManager(PM); 467 } 468 469 //===----------------------------------------------------------------------===// 470 // CodeGen-related helper functions. 471 // 472 473 static CodeGenOpt::Level GetCodeGenOptLevel() { 474 if (CodeGenOptLevel.getNumOccurrences()) 475 return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel)); 476 if (OptLevelO1) 477 return CodeGenOpt::Less; 478 if (OptLevelO2) 479 return CodeGenOpt::Default; 480 if (OptLevelO3) 481 return CodeGenOpt::Aggressive; 482 return CodeGenOpt::None; 483 } 484 485 // Returns the TargetMachine instance or zero if no triple is provided. 486 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr, 487 StringRef FeaturesStr, 488 const TargetOptions &Options) { 489 std::string Error; 490 const Target *TheTarget = 491 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 492 // Some modules don't specify a triple, and this is okay. 493 if (!TheTarget) { 494 return nullptr; 495 } 496 497 return TheTarget->createTargetMachine( 498 TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(), 499 Options, codegen::getExplicitRelocModel(), 500 codegen::getExplicitCodeModel(), GetCodeGenOptLevel()); 501 } 502 503 #ifdef BUILD_EXAMPLES 504 void initializeExampleIRTransforms(llvm::PassRegistry &Registry); 505 #endif 506 507 508 void exportDebugifyStats(llvm::StringRef Path, const DebugifyStatsMap &Map) { 509 std::error_code EC; 510 raw_fd_ostream OS{Path, EC}; 511 if (EC) { 512 errs() << "Could not open file: " << EC.message() << ", " << Path << '\n'; 513 return; 514 } 515 516 OS << "Pass Name" << ',' << "# of missing debug values" << ',' 517 << "# of missing locations" << ',' << "Missing/Expected value ratio" << ',' 518 << "Missing/Expected location ratio" << '\n'; 519 for (const auto &Entry : Map) { 520 StringRef Pass = Entry.first; 521 DebugifyStatistics Stats = Entry.second; 522 523 OS << Pass << ',' << Stats.NumDbgValuesMissing << ',' 524 << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ',' 525 << Stats.getEmptyLocationRatio() << '\n'; 526 } 527 } 528 529 struct TimeTracerRAII { 530 TimeTracerRAII(StringRef ProgramName) { 531 if (TimeTrace) 532 timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName); 533 } 534 ~TimeTracerRAII() { 535 if (TimeTrace) { 536 if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) { 537 handleAllErrors(std::move(E), [&](const StringError &SE) { 538 errs() << SE.getMessage() << "\n"; 539 }); 540 return; 541 } 542 timeTraceProfilerCleanup(); 543 } 544 } 545 }; 546 547 //===----------------------------------------------------------------------===// 548 // main for opt 549 // 550 int main(int argc, char **argv) { 551 InitLLVM X(argc, argv); 552 553 // Enable debug stream buffering. 554 EnableDebugBuffering = true; 555 556 LLVMContext Context; 557 558 InitializeAllTargets(); 559 InitializeAllTargetMCs(); 560 InitializeAllAsmPrinters(); 561 InitializeAllAsmParsers(); 562 563 // Initialize passes 564 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 565 initializeCore(Registry); 566 initializeCoroutines(Registry); 567 initializeScalarOpts(Registry); 568 initializeObjCARCOpts(Registry); 569 initializeVectorization(Registry); 570 initializeIPO(Registry); 571 initializeAnalysis(Registry); 572 initializeTransformUtils(Registry); 573 initializeInstCombine(Registry); 574 initializeAggressiveInstCombine(Registry); 575 initializeInstrumentation(Registry); 576 initializeTarget(Registry); 577 // For codegen passes, only passes that do IR to IR transformation are 578 // supported. 579 initializeExpandMemCmpPassPass(Registry); 580 initializeScalarizeMaskedMemIntrinPass(Registry); 581 initializeCodeGenPreparePass(Registry); 582 initializeAtomicExpandPass(Registry); 583 initializeRewriteSymbolsLegacyPassPass(Registry); 584 initializeWinEHPreparePass(Registry); 585 initializeDwarfEHPreparePass(Registry); 586 initializeSafeStackLegacyPassPass(Registry); 587 initializeSjLjEHPreparePass(Registry); 588 initializePreISelIntrinsicLoweringLegacyPassPass(Registry); 589 initializeGlobalMergePass(Registry); 590 initializeIndirectBrExpandPassPass(Registry); 591 initializeInterleavedLoadCombinePass(Registry); 592 initializeInterleavedAccessPass(Registry); 593 initializeEntryExitInstrumenterPass(Registry); 594 initializePostInlineEntryExitInstrumenterPass(Registry); 595 initializeUnreachableBlockElimLegacyPassPass(Registry); 596 initializeExpandReductionsPass(Registry); 597 initializeWasmEHPreparePass(Registry); 598 initializeWriteBitcodePassPass(Registry); 599 initializeHardwareLoopsPass(Registry); 600 initializeTypePromotionPass(Registry); 601 602 #ifdef BUILD_EXAMPLES 603 initializeExampleIRTransforms(Registry); 604 #endif 605 606 cl::ParseCommandLineOptions(argc, argv, 607 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 608 609 if (AnalyzeOnly && NoOutput) { 610 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 611 return 1; 612 } 613 614 TimeTracerRAII TimeTracer(argv[0]); 615 616 SMDiagnostic Err; 617 618 Context.setDiscardValueNames(DiscardValueNames); 619 if (!DisableDITypeMap) 620 Context.enableDebugTypeODRUniquing(); 621 622 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 623 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 624 RemarksFormat, RemarksWithHotness, 625 RemarksHotnessThreshold); 626 if (Error E = RemarksFileOrErr.takeError()) { 627 errs() << toString(std::move(E)) << '\n'; 628 return 1; 629 } 630 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 631 632 // Load the input module... 633 std::unique_ptr<Module> M = 634 parseIRFile(InputFilename, Err, Context, !NoVerify, ClDataLayout); 635 636 if (!M) { 637 Err.print(argv[0], errs()); 638 return 1; 639 } 640 641 // Strip debug info before running the verifier. 642 if (StripDebug) 643 StripDebugInfo(*M); 644 645 // Erase module-level named metadata, if requested. 646 if (StripNamedMetadata) { 647 while (!M->named_metadata_empty()) { 648 NamedMDNode *NMD = &*M->named_metadata_begin(); 649 M->eraseNamedMetadata(NMD); 650 } 651 } 652 653 // If we are supposed to override the target triple or data layout, do so now. 654 if (!TargetTriple.empty()) 655 M->setTargetTriple(Triple::normalize(TargetTriple)); 656 657 // Immediately run the verifier to catch any problems before starting up the 658 // pass pipelines. Otherwise we can crash on broken code during 659 // doInitialization(). 660 if (!NoVerify && verifyModule(*M, &errs())) { 661 errs() << argv[0] << ": " << InputFilename 662 << ": error: input module is broken!\n"; 663 return 1; 664 } 665 666 // Enable testing of whole program devirtualization on this module by invoking 667 // the facility for updating public visibility to linkage unit visibility when 668 // specified by an internal option. This is normally done during LTO which is 669 // not performed via opt. 670 updateVCallVisibilityInModule(*M, 671 /* WholeProgramVisibilityEnabledInLTO */ false); 672 673 // Figure out what stream we are supposed to write to... 674 std::unique_ptr<ToolOutputFile> Out; 675 std::unique_ptr<ToolOutputFile> ThinLinkOut; 676 if (NoOutput) { 677 if (!OutputFilename.empty()) 678 errs() << "WARNING: The -o (output filename) option is ignored when\n" 679 "the --disable-output option is used.\n"; 680 } else { 681 // Default to standard output. 682 if (OutputFilename.empty()) 683 OutputFilename = "-"; 684 685 std::error_code EC; 686 sys::fs::OpenFlags Flags = OutputAssembly ? sys::fs::OF_Text 687 : sys::fs::OF_None; 688 Out.reset(new ToolOutputFile(OutputFilename, EC, Flags)); 689 if (EC) { 690 errs() << EC.message() << '\n'; 691 return 1; 692 } 693 694 if (!ThinLinkBitcodeFile.empty()) { 695 ThinLinkOut.reset( 696 new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None)); 697 if (EC) { 698 errs() << EC.message() << '\n'; 699 return 1; 700 } 701 } 702 } 703 704 Triple ModuleTriple(M->getTargetTriple()); 705 std::string CPUStr, FeaturesStr; 706 TargetMachine *Machine = nullptr; 707 const TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(); 708 709 if (ModuleTriple.getArch()) { 710 CPUStr = codegen::getCPUStr(); 711 FeaturesStr = codegen::getFeaturesStr(); 712 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options); 713 } else if (ModuleTriple.getArchName() != "unknown" && 714 ModuleTriple.getArchName() != "") { 715 errs() << argv[0] << ": unrecognized architecture '" 716 << ModuleTriple.getArchName() << "' provided.\n"; 717 return 1; 718 } 719 720 std::unique_ptr<TargetMachine> TM(Machine); 721 722 // Override function attributes based on CPUStr, FeaturesStr, and command line 723 // flags. 724 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M); 725 726 // If the output is set to be emitted to standard out, and standard out is a 727 // console, print out a warning message and refuse to do it. We don't 728 // impress anyone by spewing tons of binary goo to a terminal. 729 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 730 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) 731 NoOutput = true; 732 733 if (OutputThinLTOBC) 734 M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit); 735 736 if (PassPipeline.getNumOccurrences() > 0) { 737 OutputKind OK = OK_NoOutput; 738 if (!NoOutput) 739 OK = OutputAssembly 740 ? OK_OutputAssembly 741 : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode); 742 743 VerifierKind VK = VK_VerifyInAndOut; 744 if (NoVerify) 745 VK = VK_NoVerifier; 746 else if (VerifyEach) 747 VK = VK_VerifyEachPass; 748 749 // The user has asked to use the new pass manager and provided a pipeline 750 // string. Hand off the rest of the functionality to the new code for that 751 // layer. 752 return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(), 753 RemarksFile.get(), PassPipeline, OK, VK, 754 PreserveAssemblyUseListOrder, 755 PreserveBitcodeUseListOrder, EmitSummaryIndex, 756 EmitModuleHash, EnableDebugify, Coroutines) 757 ? 0 758 : 1; 759 } 760 761 // Create a PassManager to hold and optimize the collection of passes we are 762 // about to build. 763 OptCustomPassManager Passes; 764 bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach; 765 766 // Add an appropriate TargetLibraryInfo pass for the module's triple. 767 TargetLibraryInfoImpl TLII(ModuleTriple); 768 769 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 770 if (DisableSimplifyLibCalls) 771 TLII.disableAllFunctions(); 772 else { 773 // Disable individual builtin functions in TargetLibraryInfo. 774 LibFunc F; 775 for (auto &FuncName : DisableBuiltins) 776 if (TLII.getLibFunc(FuncName, F)) 777 TLII.setUnavailable(F); 778 else { 779 errs() << argv[0] << ": cannot disable nonexistent builtin function " 780 << FuncName << '\n'; 781 return 1; 782 } 783 } 784 785 Passes.add(new TargetLibraryInfoWrapperPass(TLII)); 786 787 // Add internal analysis passes from the target machine. 788 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis() 789 : TargetIRAnalysis())); 790 791 if (AddOneTimeDebugifyPasses) 792 Passes.add(createDebugifyModulePass()); 793 794 std::unique_ptr<legacy::FunctionPassManager> FPasses; 795 if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || 796 OptLevelO3) { 797 FPasses.reset(new legacy::FunctionPassManager(M.get())); 798 FPasses->add(createTargetTransformInfoWrapperPass( 799 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); 800 } 801 802 if (PrintBreakpoints) { 803 // Default to standard output. 804 if (!Out) { 805 if (OutputFilename.empty()) 806 OutputFilename = "-"; 807 808 std::error_code EC; 809 Out = std::make_unique<ToolOutputFile>(OutputFilename, EC, 810 sys::fs::OF_None); 811 if (EC) { 812 errs() << EC.message() << '\n'; 813 return 1; 814 } 815 } 816 Passes.add(createBreakpointPrinter(Out->os())); 817 NoOutput = true; 818 } 819 820 if (TM) { 821 // FIXME: We should dyn_cast this when supported. 822 auto <M = static_cast<LLVMTargetMachine &>(*TM); 823 Pass *TPC = LTM.createPassConfig(Passes); 824 Passes.add(TPC); 825 } 826 827 // Create a new optimization pass for each one specified on the command line 828 for (unsigned i = 0; i < PassList.size(); ++i) { 829 if (StandardLinkOpts && 830 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 831 AddStandardLinkPasses(Passes); 832 StandardLinkOpts = false; 833 } 834 835 if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) { 836 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 837 OptLevelO0 = false; 838 } 839 840 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 841 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 842 OptLevelO1 = false; 843 } 844 845 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 846 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 847 OptLevelO2 = false; 848 } 849 850 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 851 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 852 OptLevelOs = false; 853 } 854 855 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 856 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 857 OptLevelOz = false; 858 } 859 860 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 861 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 862 OptLevelO3 = false; 863 } 864 865 const PassInfo *PassInf = PassList[i]; 866 Pass *P = nullptr; 867 if (PassInf->getNormalCtor()) 868 P = PassInf->getNormalCtor()(); 869 else 870 errs() << argv[0] << ": cannot create pass: " 871 << PassInf->getPassName() << "\n"; 872 if (P) { 873 PassKind Kind = P->getPassKind(); 874 addPass(Passes, P); 875 876 if (AnalyzeOnly) { 877 switch (Kind) { 878 case PT_Region: 879 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet)); 880 break; 881 case PT_Loop: 882 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet)); 883 break; 884 case PT_Function: 885 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet)); 886 break; 887 case PT_CallGraphSCC: 888 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet)); 889 break; 890 default: 891 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet)); 892 break; 893 } 894 } 895 } 896 897 if (PrintEachXForm) 898 Passes.add( 899 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder)); 900 } 901 902 if (StandardLinkOpts) { 903 AddStandardLinkPasses(Passes); 904 StandardLinkOpts = false; 905 } 906 907 if (OptLevelO0) 908 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 909 910 if (OptLevelO1) 911 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 912 913 if (OptLevelO2) 914 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 915 916 if (OptLevelOs) 917 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 918 919 if (OptLevelOz) 920 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 921 922 if (OptLevelO3) 923 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 924 925 if (FPasses) { 926 FPasses->doInitialization(); 927 for (Function &F : *M) 928 FPasses->run(F); 929 FPasses->doFinalization(); 930 } 931 932 // Check that the module is well formed on completion of optimization 933 if (!NoVerify && !VerifyEach) 934 Passes.add(createVerifierPass()); 935 936 if (AddOneTimeDebugifyPasses) 937 Passes.add(createCheckDebugifyModulePass(false)); 938 939 // In run twice mode, we want to make sure the output is bit-by-bit 940 // equivalent if we run the pass manager again, so setup two buffers and 941 // a stream to write to them. Note that llc does something similar and it 942 // may be worth to abstract this out in the future. 943 SmallVector<char, 0> Buffer; 944 SmallVector<char, 0> FirstRunBuffer; 945 std::unique_ptr<raw_svector_ostream> BOS; 946 raw_ostream *OS = nullptr; 947 948 const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly; 949 950 // Write bitcode or assembly to the output as the last step... 951 if (ShouldEmitOutput || RunTwice) { 952 assert(Out); 953 OS = &Out->os(); 954 if (RunTwice) { 955 BOS = std::make_unique<raw_svector_ostream>(Buffer); 956 OS = BOS.get(); 957 } 958 if (OutputAssembly) { 959 if (EmitSummaryIndex) 960 report_fatal_error("Text output is incompatible with -module-summary"); 961 if (EmitModuleHash) 962 report_fatal_error("Text output is incompatible with -module-hash"); 963 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder)); 964 } else if (OutputThinLTOBC) 965 Passes.add(createWriteThinLTOBitcodePass( 966 *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr)); 967 else 968 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder, 969 EmitSummaryIndex, EmitModuleHash)); 970 } 971 972 // Before executing passes, print the final values of the LLVM options. 973 cl::PrintOptionValues(); 974 975 if (!RunTwice) { 976 // Now that we have all of the passes ready, run them. 977 Passes.run(*M); 978 } else { 979 // If requested, run all passes twice with the same pass manager to catch 980 // bugs caused by persistent state in the passes. 981 std::unique_ptr<Module> M2(CloneModule(*M)); 982 // Run all passes on the original module first, so the second run processes 983 // the clone to catch CloneModule bugs. 984 Passes.run(*M); 985 FirstRunBuffer = Buffer; 986 Buffer.clear(); 987 988 Passes.run(*M2); 989 990 // Compare the two outputs and make sure they're the same 991 assert(Out); 992 if (Buffer.size() != FirstRunBuffer.size() || 993 (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) { 994 errs() 995 << "Running the pass manager twice changed the output.\n" 996 "Writing the result of the second run to the specified output.\n" 997 "To generate the one-run comparison binary, just run without\n" 998 "the compile-twice option\n"; 999 if (ShouldEmitOutput) { 1000 Out->os() << BOS->str(); 1001 Out->keep(); 1002 } 1003 if (RemarksFile) 1004 RemarksFile->keep(); 1005 return 1; 1006 } 1007 if (ShouldEmitOutput) 1008 Out->os() << BOS->str(); 1009 } 1010 1011 if (DebugifyEach && !DebugifyExport.empty()) 1012 exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap()); 1013 1014 // Declare success. 1015 if (!NoOutput || PrintBreakpoints) 1016 Out->keep(); 1017 1018 if (RemarksFile) 1019 RemarksFile->keep(); 1020 1021 if (ThinLinkOut) 1022 ThinLinkOut->keep(); 1023 1024 return 0; 1025 } 1026