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/AsmParser/Parser.h" 25 #include "llvm/Bitcode/BitcodeWriterPass.h" 26 #include "llvm/CodeGen/CommandFlags.h" 27 #include "llvm/CodeGen/TargetPassConfig.h" 28 #include "llvm/Config/llvm-config.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/DebugInfo.h" 31 #include "llvm/IR/IRPrintingPasses.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/LLVMRemarkStreamer.h" 34 #include "llvm/IR/LegacyPassManager.h" 35 #include "llvm/IR/LegacyPassNameParser.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/Verifier.h" 38 #include "llvm/IRReader/IRReader.h" 39 #include "llvm/InitializePasses.h" 40 #include "llvm/LinkAllIR.h" 41 #include "llvm/LinkAllPasses.h" 42 #include "llvm/MC/SubtargetFeature.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/FileSystem.h" 45 #include "llvm/Support/Host.h" 46 #include "llvm/Support/InitLLVM.h" 47 #include "llvm/Support/PluginLoader.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/IPO/WholeProgramDevirt.h" 59 #include "llvm/Transforms/Utils/Cloning.h" 60 #include "llvm/Transforms/Utils/Debugify.h" 61 #include <algorithm> 62 #include <memory> 63 using namespace llvm; 64 using namespace opt_tool; 65 66 static codegen::RegisterCodeGenFlags CFG; 67 68 // The OptimizationList is automatically populated with registered Passes by the 69 // PassNameParser. 70 // 71 static cl::list<const PassInfo*, bool, PassNameParser> 72 PassList(cl::desc("Optimizations available:")); 73 74 // This flag specifies a textual description of the optimization pass pipeline 75 // to run over the module. This flag switches opt to use the new pass manager 76 // infrastructure, completely disabling all of the flags specific to the old 77 // pass management. 78 static cl::opt<std::string> PassPipeline( 79 "passes", 80 cl::desc("A textual description of the pass pipeline for optimizing"), 81 cl::Hidden); 82 83 // Other command line options... 84 // 85 static cl::opt<std::string> 86 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 87 cl::init("-"), cl::value_desc("filename")); 88 89 static cl::opt<std::string> 90 OutputFilename("o", cl::desc("Override output filename"), 91 cl::value_desc("filename")); 92 93 static cl::opt<bool> 94 Force("f", cl::desc("Enable binary output on terminals")); 95 96 static cl::opt<bool> 97 PrintEachXForm("p", cl::desc("Print module after each transformation")); 98 99 static cl::opt<bool> 100 NoOutput("disable-output", 101 cl::desc("Do not write result bitcode file"), cl::Hidden); 102 103 static cl::opt<bool> 104 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 105 106 static cl::opt<bool> 107 OutputThinLTOBC("thinlto-bc", 108 cl::desc("Write output as ThinLTO-ready bitcode")); 109 110 static cl::opt<bool> 111 SplitLTOUnit("thinlto-split-lto-unit", 112 cl::desc("Enable splitting of a ThinLTO LTOUnit")); 113 114 static cl::opt<std::string> ThinLinkBitcodeFile( 115 "thin-link-bitcode-file", cl::value_desc("filename"), 116 cl::desc( 117 "A file in which to write minimized bitcode for the thin link only")); 118 119 static cl::opt<bool> 120 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden); 121 122 static cl::opt<bool> NoUpgradeDebugInfo("disable-upgrade-debug-info", 123 cl::desc("Generate invalid output"), 124 cl::ReallyHidden); 125 126 static cl::opt<bool> VerifyEach("verify-each", 127 cl::desc("Verify after each transform")); 128 129 static cl::opt<bool> 130 DisableDITypeMap("disable-debug-info-type-map", 131 cl::desc("Don't use a uniquing type map for debug info")); 132 133 static cl::opt<bool> 134 StripDebug("strip-debug", 135 cl::desc("Strip debugger symbol info from translation unit")); 136 137 static cl::opt<bool> 138 StripNamedMetadata("strip-named-metadata", 139 cl::desc("Strip module-level named metadata")); 140 141 static cl::opt<bool> DisableInline("disable-inlining", 142 cl::desc("Do not run the inliner pass")); 143 144 static cl::opt<bool> 145 DisableOptimizations("disable-opt", 146 cl::desc("Do not run any optimization passes")); 147 148 static cl::opt<bool> 149 StandardLinkOpts("std-link-opts", 150 cl::desc("Include the standard link time optimizations")); 151 152 static cl::opt<bool> 153 OptLevelO0("O0", 154 cl::desc("Optimization level 0. Similar to clang -O0")); 155 156 static cl::opt<bool> 157 OptLevelO1("O1", 158 cl::desc("Optimization level 1. Similar to clang -O1")); 159 160 static cl::opt<bool> 161 OptLevelO2("O2", 162 cl::desc("Optimization level 2. Similar to clang -O2")); 163 164 static cl::opt<bool> 165 OptLevelOs("Os", 166 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); 167 168 static cl::opt<bool> 169 OptLevelOz("Oz", 170 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); 171 172 static cl::opt<bool> 173 OptLevelO3("O3", 174 cl::desc("Optimization level 3. Similar to clang -O3")); 175 176 static cl::opt<unsigned> 177 CodeGenOptLevel("codegen-opt-level", 178 cl::desc("Override optimization level for codegen hooks")); 179 180 static cl::opt<std::string> 181 TargetTriple("mtriple", cl::desc("Override target triple for module")); 182 183 static cl::opt<bool> 184 DisableLoopUnrolling("disable-loop-unrolling", 185 cl::desc("Disable loop unrolling in all relevant passes"), 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 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; 410 411 Builder.SLPVectorize = OptLevel > 1 && SizeLevel < 2; 412 413 if (TM) 414 TM->adjustPassManager(Builder); 415 416 if (Coroutines) 417 addCoroutinePassesToExtensionPoints(Builder); 418 419 switch (PGOKindFlag) { 420 case InstrGen: 421 Builder.EnablePGOInstrGen = true; 422 Builder.PGOInstrGen = ProfileFile; 423 break; 424 case InstrUse: 425 Builder.PGOInstrUse = ProfileFile; 426 break; 427 case SampleUse: 428 Builder.PGOSampleUse = ProfileFile; 429 break; 430 default: 431 break; 432 } 433 434 switch (CSPGOKindFlag) { 435 case CSInstrGen: 436 Builder.EnablePGOCSInstrGen = true; 437 break; 438 case CSInstrUse: 439 Builder.EnablePGOCSInstrUse = true; 440 break; 441 default: 442 break; 443 } 444 445 Builder.populateFunctionPassManager(FPM); 446 Builder.populateModulePassManager(MPM); 447 } 448 449 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) { 450 PassManagerBuilder Builder; 451 Builder.VerifyInput = true; 452 if (DisableOptimizations) 453 Builder.OptLevel = 0; 454 455 if (!DisableInline) 456 Builder.Inliner = createFunctionInliningPass(); 457 Builder.populateLTOPassManager(PM); 458 } 459 460 //===----------------------------------------------------------------------===// 461 // CodeGen-related helper functions. 462 // 463 464 static CodeGenOpt::Level GetCodeGenOptLevel() { 465 if (CodeGenOptLevel.getNumOccurrences()) 466 return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel)); 467 if (OptLevelO1) 468 return CodeGenOpt::Less; 469 if (OptLevelO2) 470 return CodeGenOpt::Default; 471 if (OptLevelO3) 472 return CodeGenOpt::Aggressive; 473 return CodeGenOpt::None; 474 } 475 476 // Returns the TargetMachine instance or zero if no triple is provided. 477 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr, 478 StringRef FeaturesStr, 479 const TargetOptions &Options) { 480 std::string Error; 481 const Target *TheTarget = 482 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 483 // Some modules don't specify a triple, and this is okay. 484 if (!TheTarget) { 485 return nullptr; 486 } 487 488 return TheTarget->createTargetMachine( 489 TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(), 490 Options, codegen::getExplicitRelocModel(), 491 codegen::getExplicitCodeModel(), GetCodeGenOptLevel()); 492 } 493 494 #ifdef BUILD_EXAMPLES 495 void initializeExampleIRTransforms(llvm::PassRegistry &Registry); 496 #endif 497 498 499 void exportDebugifyStats(llvm::StringRef Path, const DebugifyStatsMap &Map) { 500 std::error_code EC; 501 raw_fd_ostream OS{Path, EC}; 502 if (EC) { 503 errs() << "Could not open file: " << EC.message() << ", " << Path << '\n'; 504 return; 505 } 506 507 OS << "Pass Name" << ',' << "# of missing debug values" << ',' 508 << "# of missing locations" << ',' << "Missing/Expected value ratio" << ',' 509 << "Missing/Expected location ratio" << '\n'; 510 for (const auto &Entry : Map) { 511 StringRef Pass = Entry.first; 512 DebugifyStatistics Stats = Entry.second; 513 514 OS << Pass << ',' << Stats.NumDbgValuesMissing << ',' 515 << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ',' 516 << Stats.getEmptyLocationRatio() << '\n'; 517 } 518 } 519 520 struct TimeTracerRAII { 521 TimeTracerRAII(StringRef ProgramName) { 522 if (TimeTrace) 523 timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName); 524 } 525 ~TimeTracerRAII() { 526 if (TimeTrace) { 527 if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) { 528 handleAllErrors(std::move(E), [&](const StringError &SE) { 529 errs() << SE.getMessage() << "\n"; 530 }); 531 return; 532 } 533 timeTraceProfilerCleanup(); 534 } 535 } 536 }; 537 538 //===----------------------------------------------------------------------===// 539 // main for opt 540 // 541 int main(int argc, char **argv) { 542 InitLLVM X(argc, argv); 543 544 // Enable debug stream buffering. 545 EnableDebugBuffering = true; 546 547 LLVMContext Context; 548 549 InitializeAllTargets(); 550 InitializeAllTargetMCs(); 551 InitializeAllAsmPrinters(); 552 InitializeAllAsmParsers(); 553 554 // Initialize passes 555 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 556 initializeCore(Registry); 557 initializeCoroutines(Registry); 558 initializeScalarOpts(Registry); 559 initializeObjCARCOpts(Registry); 560 initializeVectorization(Registry); 561 initializeIPO(Registry); 562 initializeAnalysis(Registry); 563 initializeTransformUtils(Registry); 564 initializeInstCombine(Registry); 565 initializeAggressiveInstCombine(Registry); 566 initializeInstrumentation(Registry); 567 initializeTarget(Registry); 568 // For codegen passes, only passes that do IR to IR transformation are 569 // supported. 570 initializeExpandMemCmpPassPass(Registry); 571 initializeScalarizeMaskedMemIntrinPass(Registry); 572 initializeCodeGenPreparePass(Registry); 573 initializeAtomicExpandPass(Registry); 574 initializeRewriteSymbolsLegacyPassPass(Registry); 575 initializeWinEHPreparePass(Registry); 576 initializeDwarfEHPreparePass(Registry); 577 initializeSafeStackLegacyPassPass(Registry); 578 initializeSjLjEHPreparePass(Registry); 579 initializePreISelIntrinsicLoweringLegacyPassPass(Registry); 580 initializeGlobalMergePass(Registry); 581 initializeIndirectBrExpandPassPass(Registry); 582 initializeInterleavedLoadCombinePass(Registry); 583 initializeInterleavedAccessPass(Registry); 584 initializeEntryExitInstrumenterPass(Registry); 585 initializePostInlineEntryExitInstrumenterPass(Registry); 586 initializeUnreachableBlockElimLegacyPassPass(Registry); 587 initializeExpandReductionsPass(Registry); 588 initializeWasmEHPreparePass(Registry); 589 initializeWriteBitcodePassPass(Registry); 590 initializeHardwareLoopsPass(Registry); 591 initializeTypePromotionPass(Registry); 592 593 #ifdef BUILD_EXAMPLES 594 initializeExampleIRTransforms(Registry); 595 #endif 596 597 cl::ParseCommandLineOptions(argc, argv, 598 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 599 600 if (AnalyzeOnly && NoOutput) { 601 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 602 return 1; 603 } 604 605 TimeTracerRAII TimeTracer(argv[0]); 606 607 SMDiagnostic Err; 608 609 Context.setDiscardValueNames(DiscardValueNames); 610 if (!DisableDITypeMap) 611 Context.enableDebugTypeODRUniquing(); 612 613 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 614 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 615 RemarksFormat, RemarksWithHotness, 616 RemarksHotnessThreshold); 617 if (Error E = RemarksFileOrErr.takeError()) { 618 errs() << toString(std::move(E)) << '\n'; 619 return 1; 620 } 621 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 622 623 // Load the input module... 624 auto SetDataLayout = [](StringRef) -> Optional<std::string> { 625 if (ClDataLayout.empty()) 626 return None; 627 return ClDataLayout; 628 }; 629 std::unique_ptr<Module> M; 630 if (NoUpgradeDebugInfo) 631 M = parseAssemblyFileWithIndexNoUpgradeDebugInfo( 632 InputFilename, Err, Context, nullptr, SetDataLayout) 633 .Mod; 634 else 635 M = parseIRFile(InputFilename, Err, Context, SetDataLayout); 636 637 if (!M) { 638 Err.print(argv[0], errs()); 639 return 1; 640 } 641 642 // Strip debug info before running the verifier. 643 if (StripDebug) 644 StripDebugInfo(*M); 645 646 // Erase module-level named metadata, if requested. 647 if (StripNamedMetadata) { 648 while (!M->named_metadata_empty()) { 649 NamedMDNode *NMD = &*M->named_metadata_begin(); 650 M->eraseNamedMetadata(NMD); 651 } 652 } 653 654 // If we are supposed to override the target triple or data layout, do so now. 655 if (!TargetTriple.empty()) 656 M->setTargetTriple(Triple::normalize(TargetTriple)); 657 658 // Immediately run the verifier to catch any problems before starting up the 659 // pass pipelines. Otherwise we can crash on broken code during 660 // doInitialization(). 661 if (!NoVerify && verifyModule(*M, &errs())) { 662 errs() << argv[0] << ": " << InputFilename 663 << ": error: input module is broken!\n"; 664 return 1; 665 } 666 667 // Enable testing of whole program devirtualization on this module by invoking 668 // the facility for updating public visibility to linkage unit visibility when 669 // specified by an internal option. This is normally done during LTO which is 670 // not performed via opt. 671 updateVCallVisibilityInModule(*M, 672 /* WholeProgramVisibilityEnabledInLTO */ false); 673 674 // Figure out what stream we are supposed to write to... 675 std::unique_ptr<ToolOutputFile> Out; 676 std::unique_ptr<ToolOutputFile> ThinLinkOut; 677 if (NoOutput) { 678 if (!OutputFilename.empty()) 679 errs() << "WARNING: The -o (output filename) option is ignored when\n" 680 "the --disable-output option is used.\n"; 681 } else { 682 // Default to standard output. 683 if (OutputFilename.empty()) 684 OutputFilename = "-"; 685 686 std::error_code EC; 687 sys::fs::OpenFlags Flags = OutputAssembly ? sys::fs::OF_Text 688 : sys::fs::OF_None; 689 Out.reset(new ToolOutputFile(OutputFilename, EC, Flags)); 690 if (EC) { 691 errs() << EC.message() << '\n'; 692 return 1; 693 } 694 695 if (!ThinLinkBitcodeFile.empty()) { 696 ThinLinkOut.reset( 697 new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None)); 698 if (EC) { 699 errs() << EC.message() << '\n'; 700 return 1; 701 } 702 } 703 } 704 705 Triple ModuleTriple(M->getTargetTriple()); 706 std::string CPUStr, FeaturesStr; 707 TargetMachine *Machine = nullptr; 708 const TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(); 709 710 if (ModuleTriple.getArch()) { 711 CPUStr = codegen::getCPUStr(); 712 FeaturesStr = codegen::getFeaturesStr(); 713 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options); 714 } else if (ModuleTriple.getArchName() != "unknown" && 715 ModuleTriple.getArchName() != "") { 716 errs() << argv[0] << ": unrecognized architecture '" 717 << ModuleTriple.getArchName() << "' provided.\n"; 718 return 1; 719 } 720 721 std::unique_ptr<TargetMachine> TM(Machine); 722 723 // Override function attributes based on CPUStr, FeaturesStr, and command line 724 // flags. 725 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M); 726 727 // If the output is set to be emitted to standard out, and standard out is a 728 // console, print out a warning message and refuse to do it. We don't 729 // impress anyone by spewing tons of binary goo to a terminal. 730 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 731 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) 732 NoOutput = true; 733 734 if (OutputThinLTOBC) 735 M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit); 736 737 if (PassPipeline.getNumOccurrences() > 0) { 738 OutputKind OK = OK_NoOutput; 739 if (!NoOutput) 740 OK = OutputAssembly 741 ? OK_OutputAssembly 742 : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode); 743 744 VerifierKind VK = VK_VerifyInAndOut; 745 if (NoVerify) 746 VK = VK_NoVerifier; 747 else if (VerifyEach) 748 VK = VK_VerifyEachPass; 749 750 // The user has asked to use the new pass manager and provided a pipeline 751 // string. Hand off the rest of the functionality to the new code for that 752 // layer. 753 return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(), 754 RemarksFile.get(), PassPipeline, OK, VK, 755 PreserveAssemblyUseListOrder, 756 PreserveBitcodeUseListOrder, EmitSummaryIndex, 757 EmitModuleHash, EnableDebugify, Coroutines) 758 ? 0 759 : 1; 760 } 761 762 // Create a PassManager to hold and optimize the collection of passes we are 763 // about to build. 764 OptCustomPassManager Passes; 765 bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach; 766 767 // Add an appropriate TargetLibraryInfo pass for the module's triple. 768 TargetLibraryInfoImpl TLII(ModuleTriple); 769 770 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 771 if (DisableSimplifyLibCalls) 772 TLII.disableAllFunctions(); 773 else { 774 // Disable individual builtin functions in TargetLibraryInfo. 775 LibFunc F; 776 for (auto &FuncName : DisableBuiltins) 777 if (TLII.getLibFunc(FuncName, F)) 778 TLII.setUnavailable(F); 779 else { 780 errs() << argv[0] << ": cannot disable nonexistent builtin function " 781 << FuncName << '\n'; 782 return 1; 783 } 784 } 785 786 Passes.add(new TargetLibraryInfoWrapperPass(TLII)); 787 788 // Add internal analysis passes from the target machine. 789 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis() 790 : TargetIRAnalysis())); 791 792 if (AddOneTimeDebugifyPasses) 793 Passes.add(createDebugifyModulePass()); 794 795 std::unique_ptr<legacy::FunctionPassManager> FPasses; 796 if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || 797 OptLevelO3) { 798 FPasses.reset(new legacy::FunctionPassManager(M.get())); 799 FPasses->add(createTargetTransformInfoWrapperPass( 800 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); 801 } 802 803 if (PrintBreakpoints) { 804 // Default to standard output. 805 if (!Out) { 806 if (OutputFilename.empty()) 807 OutputFilename = "-"; 808 809 std::error_code EC; 810 Out = std::make_unique<ToolOutputFile>(OutputFilename, EC, 811 sys::fs::OF_None); 812 if (EC) { 813 errs() << EC.message() << '\n'; 814 return 1; 815 } 816 } 817 Passes.add(createBreakpointPrinter(Out->os())); 818 NoOutput = true; 819 } 820 821 if (TM) { 822 // FIXME: We should dyn_cast this when supported. 823 auto <M = static_cast<LLVMTargetMachine &>(*TM); 824 Pass *TPC = LTM.createPassConfig(Passes); 825 Passes.add(TPC); 826 } 827 828 // Create a new optimization pass for each one specified on the command line 829 for (unsigned i = 0; i < PassList.size(); ++i) { 830 if (StandardLinkOpts && 831 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 832 AddStandardLinkPasses(Passes); 833 StandardLinkOpts = false; 834 } 835 836 if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) { 837 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 838 OptLevelO0 = false; 839 } 840 841 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 842 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 843 OptLevelO1 = false; 844 } 845 846 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 847 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 848 OptLevelO2 = false; 849 } 850 851 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 852 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 853 OptLevelOs = false; 854 } 855 856 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 857 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 858 OptLevelOz = false; 859 } 860 861 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 862 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 863 OptLevelO3 = false; 864 } 865 866 const PassInfo *PassInf = PassList[i]; 867 Pass *P = nullptr; 868 if (PassInf->getNormalCtor()) 869 P = PassInf->getNormalCtor()(); 870 else 871 errs() << argv[0] << ": cannot create pass: " 872 << PassInf->getPassName() << "\n"; 873 if (P) { 874 PassKind Kind = P->getPassKind(); 875 addPass(Passes, P); 876 877 if (AnalyzeOnly) { 878 switch (Kind) { 879 case PT_Region: 880 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet)); 881 break; 882 case PT_Loop: 883 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet)); 884 break; 885 case PT_Function: 886 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet)); 887 break; 888 case PT_CallGraphSCC: 889 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet)); 890 break; 891 default: 892 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet)); 893 break; 894 } 895 } 896 } 897 898 if (PrintEachXForm) 899 Passes.add( 900 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder)); 901 } 902 903 if (StandardLinkOpts) { 904 AddStandardLinkPasses(Passes); 905 StandardLinkOpts = false; 906 } 907 908 if (OptLevelO0) 909 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 910 911 if (OptLevelO1) 912 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 913 914 if (OptLevelO2) 915 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 916 917 if (OptLevelOs) 918 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 919 920 if (OptLevelOz) 921 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 922 923 if (OptLevelO3) 924 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 925 926 if (FPasses) { 927 FPasses->doInitialization(); 928 for (Function &F : *M) 929 FPasses->run(F); 930 FPasses->doFinalization(); 931 } 932 933 // Check that the module is well formed on completion of optimization 934 if (!NoVerify && !VerifyEach) 935 Passes.add(createVerifierPass()); 936 937 if (AddOneTimeDebugifyPasses) 938 Passes.add(createCheckDebugifyModulePass(false)); 939 940 // In run twice mode, we want to make sure the output is bit-by-bit 941 // equivalent if we run the pass manager again, so setup two buffers and 942 // a stream to write to them. Note that llc does something similar and it 943 // may be worth to abstract this out in the future. 944 SmallVector<char, 0> Buffer; 945 SmallVector<char, 0> FirstRunBuffer; 946 std::unique_ptr<raw_svector_ostream> BOS; 947 raw_ostream *OS = nullptr; 948 949 const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly; 950 951 // Write bitcode or assembly to the output as the last step... 952 if (ShouldEmitOutput || RunTwice) { 953 assert(Out); 954 OS = &Out->os(); 955 if (RunTwice) { 956 BOS = std::make_unique<raw_svector_ostream>(Buffer); 957 OS = BOS.get(); 958 } 959 if (OutputAssembly) { 960 if (EmitSummaryIndex) 961 report_fatal_error("Text output is incompatible with -module-summary"); 962 if (EmitModuleHash) 963 report_fatal_error("Text output is incompatible with -module-hash"); 964 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder)); 965 } else if (OutputThinLTOBC) 966 Passes.add(createWriteThinLTOBitcodePass( 967 *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr)); 968 else 969 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder, 970 EmitSummaryIndex, EmitModuleHash)); 971 } 972 973 // Before executing passes, print the final values of the LLVM options. 974 cl::PrintOptionValues(); 975 976 if (!RunTwice) { 977 // Now that we have all of the passes ready, run them. 978 Passes.run(*M); 979 } else { 980 // If requested, run all passes twice with the same pass manager to catch 981 // bugs caused by persistent state in the passes. 982 std::unique_ptr<Module> M2(CloneModule(*M)); 983 // Run all passes on the original module first, so the second run processes 984 // the clone to catch CloneModule bugs. 985 Passes.run(*M); 986 FirstRunBuffer = Buffer; 987 Buffer.clear(); 988 989 Passes.run(*M2); 990 991 // Compare the two outputs and make sure they're the same 992 assert(Out); 993 if (Buffer.size() != FirstRunBuffer.size() || 994 (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) { 995 errs() 996 << "Running the pass manager twice changed the output.\n" 997 "Writing the result of the second run to the specified output.\n" 998 "To generate the one-run comparison binary, just run without\n" 999 "the compile-twice option\n"; 1000 if (ShouldEmitOutput) { 1001 Out->os() << BOS->str(); 1002 Out->keep(); 1003 } 1004 if (RemarksFile) 1005 RemarksFile->keep(); 1006 return 1; 1007 } 1008 if (ShouldEmitOutput) 1009 Out->os() << BOS->str(); 1010 } 1011 1012 if (DebugifyEach && !DebugifyExport.empty()) 1013 exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap()); 1014 1015 // Declare success. 1016 if (!NoOutput || PrintBreakpoints) 1017 Out->keep(); 1018 1019 if (RemarksFile) 1020 RemarksFile->keep(); 1021 1022 if (ThinLinkOut) 1023 ThinLinkOut->keep(); 1024 1025 return 0; 1026 } 1027