1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
15 #include "BreakpointPrinter.h"
16 #include "NewPMDriver.h"
17 #include "PassPrinters.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/CodeGen/CommandFlags.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/IRPrintingPasses.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/LegacyPassNameParser.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/LinkAllIR.h"
38 #include "llvm/LinkAllPasses.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/Utils/Cloning.h"
58 using namespace opt_tool;
60 // The OptimizationList is automatically populated with registered Passes by the
63 static cl::list<const PassInfo*, bool, PassNameParser>
64 PassList(cl::desc("Optimizations available:"));
66 // This flag specifies a textual description of the optimization pass pipeline
67 // to run over the module. This flag switches opt to use the new pass manager
68 // infrastructure, completely disabling all of the flags specific to the old
70 static cl::opt<std::string> PassPipeline(
72 cl::desc("A textual description of the pass pipeline for optimizing"),
75 // Other command line options...
77 static cl::opt<std::string>
78 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
79 cl::init("-"), cl::value_desc("filename"));
81 static cl::opt<std::string>
82 OutputFilename("o", cl::desc("Override output filename"),
83 cl::value_desc("filename"));
86 Force("f", cl::desc("Enable binary output on terminals"));
89 PrintEachXForm("p", cl::desc("Print module after each transformation"));
92 NoOutput("disable-output",
93 cl::desc("Do not write result bitcode file"), cl::Hidden);
96 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
99 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
102 VerifyEach("verify-each", cl::desc("Verify after each transform"));
105 DisableDITypeMap("disable-debug-info-type-map",
106 cl::desc("Don't use a uniquing type map for debug info"));
109 StripDebug("strip-debug",
110 cl::desc("Strip debugger symbol info from translation unit"));
113 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
116 DisableOptimizations("disable-opt",
117 cl::desc("Do not run any optimization passes"));
120 StandardLinkOpts("std-link-opts",
121 cl::desc("Include the standard link time optimizations"));
125 cl::desc("Optimization level 1. Similar to clang -O1"));
129 cl::desc("Optimization level 2. Similar to clang -O2"));
133 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
137 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
141 cl::desc("Optimization level 3. Similar to clang -O3"));
143 static cl::opt<unsigned>
144 CodeGenOptLevel("codegen-opt-level",
145 cl::desc("Override optimization level for codegen hooks"));
147 static cl::opt<std::string>
148 TargetTriple("mtriple", cl::desc("Override target triple for module"));
151 UnitAtATime("funit-at-a-time",
152 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
156 DisableLoopUnrolling("disable-loop-unrolling",
157 cl::desc("Disable loop unrolling in all relevant passes"),
160 DisableLoopVectorization("disable-loop-vectorization",
161 cl::desc("Disable the loop vectorization pass"),
165 DisableSLPVectorization("disable-slp-vectorization",
166 cl::desc("Disable the slp vectorization pass"),
169 static cl::opt<bool> EmitSummaryIndex("module-summary",
170 cl::desc("Emit module summary index"),
173 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
177 DisableSimplifyLibCalls("disable-simplify-libcalls",
178 cl::desc("Disable simplify-libcalls"));
181 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
184 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
187 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
190 PrintBreakpoints("print-breakpoints-for-testing",
191 cl::desc("Print select breakpoints location for testing"));
193 static cl::opt<std::string>
194 DefaultDataLayout("default-data-layout",
195 cl::desc("data layout string to use if not specified by module"),
196 cl::value_desc("layout-string"), cl::init(""));
198 static cl::opt<bool> PreserveBitcodeUseListOrder(
199 "preserve-bc-uselistorder",
200 cl::desc("Preserve use-list order when writing LLVM bitcode."),
201 cl::init(true), cl::Hidden);
203 static cl::opt<bool> PreserveAssemblyUseListOrder(
204 "preserve-ll-uselistorder",
205 cl::desc("Preserve use-list order when writing LLVM assembly."),
206 cl::init(false), cl::Hidden);
209 RunTwice("run-twice",
210 cl::desc("Run all passes twice, re-using the same pass manager."),
211 cl::init(false), cl::Hidden);
213 static cl::opt<bool> DiscardValueNames(
214 "discard-value-names",
215 cl::desc("Discard names from Value (other than GlobalValue)."),
216 cl::init(false), cl::Hidden);
218 static cl::opt<bool> PassRemarksWithHotness(
219 "pass-remarks-with-hotness",
220 cl::desc("With PGO, include profile count in optimization remarks"),
223 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
224 // Add the pass to the pass manager...
227 // If we are verifying all of the intermediate steps, add the verifier...
229 PM.add(createVerifierPass());
232 /// This routine adds optimization passes based on selected optimization level,
235 /// OptLevel - Optimization Level
236 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
237 legacy::FunctionPassManager &FPM,
238 TargetMachine *TM, unsigned OptLevel,
239 unsigned SizeLevel) {
240 if (!NoVerify || VerifyEach)
241 FPM.add(createVerifierPass()); // Verify that input is correct
243 PassManagerBuilder Builder;
244 Builder.OptLevel = OptLevel;
245 Builder.SizeLevel = SizeLevel;
249 } else if (OptLevel > 1) {
250 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
252 Builder.Inliner = createAlwaysInlinerPass();
254 Builder.DisableUnitAtATime = !UnitAtATime;
255 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
256 DisableLoopUnrolling : OptLevel == 0;
258 // This is final, unless there is a #pragma vectorize enable
259 if (DisableLoopVectorization)
260 Builder.LoopVectorize = false;
261 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
262 else if (!Builder.LoopVectorize)
263 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
265 // When #pragma vectorize is on for SLP, do the same as above
266 Builder.SLPVectorize =
267 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
269 // Add target-specific passes that need to run as early as possible.
271 Builder.addExtension(
272 PassManagerBuilder::EP_EarlyAsPossible,
273 [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
274 TM->addEarlyAsPossiblePasses(PM);
277 Builder.populateFunctionPassManager(FPM);
278 Builder.populateModulePassManager(MPM);
281 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
282 PassManagerBuilder Builder;
283 Builder.VerifyInput = true;
284 if (DisableOptimizations)
285 Builder.OptLevel = 0;
288 Builder.Inliner = createFunctionInliningPass();
289 Builder.populateLTOPassManager(PM);
292 //===----------------------------------------------------------------------===//
293 // CodeGen-related helper functions.
296 static CodeGenOpt::Level GetCodeGenOptLevel() {
297 if (CodeGenOptLevel.getNumOccurrences())
298 return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
300 return CodeGenOpt::Less;
302 return CodeGenOpt::Default;
304 return CodeGenOpt::Aggressive;
305 return CodeGenOpt::None;
308 // Returns the TargetMachine instance or zero if no triple is provided.
309 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
310 StringRef FeaturesStr,
311 const TargetOptions &Options) {
313 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
315 // Some modules don't specify a triple, and this is okay.
320 return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
321 FeaturesStr, Options, getRelocModel(),
322 CMModel, GetCodeGenOptLevel());
325 #ifdef LINK_POLLY_INTO_TOOLS
327 void initializePollyPasses(llvm::PassRegistry &Registry);
331 //===----------------------------------------------------------------------===//
334 int main(int argc, char **argv) {
335 sys::PrintStackTraceOnErrorSignal(argv[0]);
336 llvm::PrettyStackTraceProgram X(argc, argv);
338 // Enable debug stream buffering.
339 EnableDebugBuffering = true;
341 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
344 InitializeAllTargets();
345 InitializeAllTargetMCs();
346 InitializeAllAsmPrinters();
349 PassRegistry &Registry = *PassRegistry::getPassRegistry();
350 initializeCore(Registry);
351 initializeScalarOpts(Registry);
352 initializeObjCARCOpts(Registry);
353 initializeVectorization(Registry);
354 initializeIPO(Registry);
355 initializeAnalysis(Registry);
356 initializeTransformUtils(Registry);
357 initializeInstCombine(Registry);
358 initializeInstrumentation(Registry);
359 initializeTarget(Registry);
360 // For codegen passes, only passes that do IR to IR transformation are
362 initializeCodeGenPreparePass(Registry);
363 initializeAtomicExpandPass(Registry);
364 initializeRewriteSymbolsPass(Registry);
365 initializeWinEHPreparePass(Registry);
366 initializeDwarfEHPreparePass(Registry);
367 initializeSafeStackPass(Registry);
368 initializeSjLjEHPreparePass(Registry);
369 initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
370 initializeGlobalMergePass(Registry);
371 initializeInterleavedAccessPass(Registry);
372 initializeUnreachableBlockElimLegacyPassPass(Registry);
374 #ifdef LINK_POLLY_INTO_TOOLS
375 polly::initializePollyPasses(Registry);
378 cl::ParseCommandLineOptions(argc, argv,
379 "llvm .bc -> .bc modular optimizer and analysis printer\n");
381 if (AnalyzeOnly && NoOutput) {
382 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
388 Context.setDiscardValueNames(DiscardValueNames);
389 if (!DisableDITypeMap)
390 Context.enableDebugTypeODRUniquing();
392 if (PassRemarksWithHotness)
393 Context.setDiagnosticHotnessRequested(true);
395 // Load the input module...
396 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
399 Err.print(argv[0], errs());
403 // Strip debug info before running the verifier.
407 // Immediately run the verifier to catch any problems before starting up the
408 // pass pipelines. Otherwise we can crash on broken code during
409 // doInitialization().
410 if (!NoVerify && verifyModule(*M, &errs())) {
411 errs() << argv[0] << ": " << InputFilename
412 << ": error: input module is broken!\n";
416 // If we are supposed to override the target triple, do so now.
417 if (!TargetTriple.empty())
418 M->setTargetTriple(Triple::normalize(TargetTriple));
420 // Figure out what stream we are supposed to write to...
421 std::unique_ptr<tool_output_file> Out;
423 if (!OutputFilename.empty())
424 errs() << "WARNING: The -o (output filename) option is ignored when\n"
425 "the --disable-output option is used.\n";
427 // Default to standard output.
428 if (OutputFilename.empty())
429 OutputFilename = "-";
432 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
434 errs() << EC.message() << '\n';
439 Triple ModuleTriple(M->getTargetTriple());
440 std::string CPUStr, FeaturesStr;
441 TargetMachine *Machine = nullptr;
442 const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
444 if (ModuleTriple.getArch()) {
445 CPUStr = getCPUStr();
446 FeaturesStr = getFeaturesStr();
447 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
450 std::unique_ptr<TargetMachine> TM(Machine);
452 // Override function attributes based on CPUStr, FeaturesStr, and command line
454 setFunctionAttributes(CPUStr, FeaturesStr, *M);
456 // If the output is set to be emitted to standard out, and standard out is a
457 // console, print out a warning message and refuse to do it. We don't
458 // impress anyone by spewing tons of binary goo to a terminal.
459 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
460 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
463 if (PassPipeline.getNumOccurrences() > 0) {
464 OutputKind OK = OK_NoOutput;
466 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
468 VerifierKind VK = VK_VerifyInAndOut;
472 VK = VK_VerifyEachPass;
474 // The user has asked to use the new pass manager and provided a pipeline
475 // string. Hand off the rest of the functionality to the new code for that
477 return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
478 PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
479 PreserveBitcodeUseListOrder)
484 // Create a PassManager to hold and optimize the collection of passes we are
487 legacy::PassManager Passes;
489 // Add an appropriate TargetLibraryInfo pass for the module's triple.
490 TargetLibraryInfoImpl TLII(ModuleTriple);
492 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
493 if (DisableSimplifyLibCalls)
494 TLII.disableAllFunctions();
495 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
497 // Add an appropriate DataLayout instance for this module.
498 const DataLayout &DL = M->getDataLayout();
499 if (DL.isDefault() && !DefaultDataLayout.empty()) {
500 M->setDataLayout(DefaultDataLayout);
503 // Add internal analysis passes from the target machine.
504 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
505 : TargetIRAnalysis()));
507 std::unique_ptr<legacy::FunctionPassManager> FPasses;
508 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
509 FPasses.reset(new legacy::FunctionPassManager(M.get()));
510 FPasses->add(createTargetTransformInfoWrapperPass(
511 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
514 if (PrintBreakpoints) {
515 // Default to standard output.
517 if (OutputFilename.empty())
518 OutputFilename = "-";
521 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
524 errs() << EC.message() << '\n';
528 Passes.add(createBreakpointPrinter(Out->os()));
532 // Create a new optimization pass for each one specified on the command line
533 for (unsigned i = 0; i < PassList.size(); ++i) {
534 if (StandardLinkOpts &&
535 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
536 AddStandardLinkPasses(Passes);
537 StandardLinkOpts = false;
540 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
541 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
545 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
546 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
550 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
551 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
555 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
556 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
560 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
561 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
565 const PassInfo *PassInf = PassList[i];
567 if (PassInf->getTargetMachineCtor())
568 P = PassInf->getTargetMachineCtor()(TM.get());
569 else if (PassInf->getNormalCtor())
570 P = PassInf->getNormalCtor()();
572 errs() << argv[0] << ": cannot create pass: "
573 << PassInf->getPassName() << "\n";
575 PassKind Kind = P->getPassKind();
581 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
584 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
587 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
590 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
592 case PT_CallGraphSCC:
593 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
596 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
604 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
607 if (StandardLinkOpts) {
608 AddStandardLinkPasses(Passes);
609 StandardLinkOpts = false;
613 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
616 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
619 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
622 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
625 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
628 FPasses->doInitialization();
629 for (Function &F : *M)
631 FPasses->doFinalization();
634 // Check that the module is well formed on completion of optimization
635 if (!NoVerify && !VerifyEach)
636 Passes.add(createVerifierPass());
638 // In run twice mode, we want to make sure the output is bit-by-bit
639 // equivalent if we run the pass manager again, so setup two buffers and
640 // a stream to write to them. Note that llc does something similar and it
641 // may be worth to abstract this out in the future.
642 SmallVector<char, 0> Buffer;
643 SmallVector<char, 0> CompileTwiceBuffer;
644 std::unique_ptr<raw_svector_ostream> BOS;
645 raw_ostream *OS = nullptr;
647 // Write bitcode or assembly to the output as the last step...
648 if (!NoOutput && !AnalyzeOnly) {
652 BOS = make_unique<raw_svector_ostream>(Buffer);
655 if (OutputAssembly) {
656 if (EmitSummaryIndex)
657 report_fatal_error("Text output is incompatible with -module-summary");
659 report_fatal_error("Text output is incompatible with -module-hash");
660 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
662 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
663 EmitSummaryIndex, EmitModuleHash));
666 // Before executing passes, print the final values of the LLVM options.
667 cl::PrintOptionValues();
669 // If requested, run all passes again with the same pass manager to catch
670 // bugs caused by persistent state in the passes
672 std::unique_ptr<Module> M2(CloneModule(M.get()));
674 CompileTwiceBuffer = Buffer;
678 // Now that we have all of the passes ready, run them.
681 // Compare the two outputs and make sure they're the same
684 if (Buffer.size() != CompileTwiceBuffer.size() ||
685 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
687 errs() << "Running the pass manager twice changed the output.\n"
688 "Writing the result of the second run to the specified output.\n"
689 "To generate the one-run comparison binary, just run without\n"
690 "the compile-twice option\n";
691 Out->os() << BOS->str();
695 Out->os() << BOS->str();
699 if (!NoOutput || PrintBreakpoints)