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/IRPrintingPasses.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassNameParser.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LinkAllIR.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/IR/LegacyPassManager.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/PluginLoader.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/SystemUtils.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 using namespace opt_tool;
57 // The OptimizationList is automatically populated with registered Passes by the
60 static cl::list<const PassInfo*, bool, PassNameParser>
61 PassList(cl::desc("Optimizations available:"));
63 // This flag specifies a textual description of the optimization pass pipeline
64 // to run over the module. This flag switches opt to use the new pass manager
65 // infrastructure, completely disabling all of the flags specific to the old
67 static cl::opt<std::string> PassPipeline(
69 cl::desc("A textual description of the pass pipeline for optimizing"),
72 // Other command line options...
74 static cl::opt<std::string>
75 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
76 cl::init("-"), cl::value_desc("filename"));
78 static cl::opt<std::string>
79 OutputFilename("o", cl::desc("Override output filename"),
80 cl::value_desc("filename"));
83 Force("f", cl::desc("Enable binary output on terminals"));
86 PrintEachXForm("p", cl::desc("Print module after each transformation"));
89 NoOutput("disable-output",
90 cl::desc("Do not write result bitcode file"), cl::Hidden);
93 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
96 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
99 VerifyEach("verify-each", cl::desc("Verify after each transform"));
102 StripDebug("strip-debug",
103 cl::desc("Strip debugger symbol info from translation unit"));
106 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
109 DisableOptimizations("disable-opt",
110 cl::desc("Do not run any optimization passes"));
113 StandardLinkOpts("std-link-opts",
114 cl::desc("Include the standard link time optimizations"));
118 cl::desc("Optimization level 1. Similar to clang -O1"));
122 cl::desc("Optimization level 2. Similar to clang -O2"));
126 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
130 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
134 cl::desc("Optimization level 3. Similar to clang -O3"));
136 static cl::opt<std::string>
137 TargetTriple("mtriple", cl::desc("Override target triple for module"));
140 UnitAtATime("funit-at-a-time",
141 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
145 DisableLoopUnrolling("disable-loop-unrolling",
146 cl::desc("Disable loop unrolling in all relevant passes"),
149 DisableLoopVectorization("disable-loop-vectorization",
150 cl::desc("Disable the loop vectorization pass"),
154 DisableSLPVectorization("disable-slp-vectorization",
155 cl::desc("Disable the slp vectorization pass"),
160 DisableSimplifyLibCalls("disable-simplify-libcalls",
161 cl::desc("Disable simplify-libcalls"));
164 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
167 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
170 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
173 PrintBreakpoints("print-breakpoints-for-testing",
174 cl::desc("Print select breakpoints location for testing"));
176 static cl::opt<std::string>
177 DefaultDataLayout("default-data-layout",
178 cl::desc("data layout string to use if not specified by module"),
179 cl::value_desc("layout-string"), cl::init(""));
183 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
184 // Add the pass to the pass manager...
187 // If we are verifying all of the intermediate steps, add the verifier...
189 PM.add(createVerifierPass());
190 PM.add(createDebugInfoVerifierPass());
194 /// This routine adds optimization passes based on selected optimization level,
197 /// OptLevel - Optimization Level
198 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
199 legacy::FunctionPassManager &FPM,
200 unsigned OptLevel, unsigned SizeLevel) {
201 FPM.add(createVerifierPass()); // Verify that input is correct
202 MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
204 PassManagerBuilder Builder;
205 Builder.OptLevel = OptLevel;
206 Builder.SizeLevel = SizeLevel;
210 } else if (OptLevel > 1) {
211 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
213 Builder.Inliner = createAlwaysInlinerPass();
215 Builder.DisableUnitAtATime = !UnitAtATime;
216 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
217 DisableLoopUnrolling : OptLevel == 0;
219 // This is final, unless there is a #pragma vectorize enable
220 if (DisableLoopVectorization)
221 Builder.LoopVectorize = false;
222 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
223 else if (!Builder.LoopVectorize)
224 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
226 // When #pragma vectorize is on for SLP, do the same as above
227 Builder.SLPVectorize =
228 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
230 Builder.populateFunctionPassManager(FPM);
231 Builder.populateModulePassManager(MPM);
234 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
235 PassManagerBuilder Builder;
236 Builder.VerifyInput = true;
237 Builder.StripDebug = StripDebug;
238 if (DisableOptimizations)
239 Builder.OptLevel = 0;
242 Builder.Inliner = createFunctionInliningPass();
243 Builder.populateLTOPassManager(PM);
246 //===----------------------------------------------------------------------===//
247 // CodeGen-related helper functions.
250 CodeGenOpt::Level GetCodeGenOptLevel() {
252 return CodeGenOpt::Less;
254 return CodeGenOpt::Default;
256 return CodeGenOpt::Aggressive;
257 return CodeGenOpt::None;
260 // Returns the TargetMachine instance or zero if no triple is provided.
261 static TargetMachine* GetTargetMachine(Triple TheTriple) {
263 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
265 // Some modules don't specify a triple, and this is okay.
270 // Package up features to be passed to target/subtarget
271 std::string FeaturesStr;
273 SubtargetFeatures Features;
274 for (unsigned i = 0; i != MAttrs.size(); ++i)
275 Features.AddFeature(MAttrs[i]);
276 FeaturesStr = Features.getString();
279 return TheTarget->createTargetMachine(TheTriple.getTriple(),
281 InitTargetOptionsFromCodeGenFlags(),
283 GetCodeGenOptLevel());
286 #ifdef LINK_POLLY_INTO_TOOLS
288 void initializePollyPasses(llvm::PassRegistry &Registry);
292 //===----------------------------------------------------------------------===//
295 int main(int argc, char **argv) {
296 sys::PrintStackTraceOnErrorSignal();
297 llvm::PrettyStackTraceProgram X(argc, argv);
299 // Enable debug stream buffering.
300 EnableDebugBuffering = true;
302 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
303 LLVMContext &Context = getGlobalContext();
305 InitializeAllTargets();
306 InitializeAllTargetMCs();
307 InitializeAllAsmPrinters();
310 PassRegistry &Registry = *PassRegistry::getPassRegistry();
311 initializeCore(Registry);
312 initializeScalarOpts(Registry);
313 initializeObjCARCOpts(Registry);
314 initializeVectorization(Registry);
315 initializeIPO(Registry);
316 initializeAnalysis(Registry);
317 initializeIPA(Registry);
318 initializeTransformUtils(Registry);
319 initializeInstCombine(Registry);
320 initializeInstrumentation(Registry);
321 initializeTarget(Registry);
322 // For codegen passes, only passes that do IR to IR transformation are
324 initializeCodeGenPreparePass(Registry);
325 initializeAtomicExpandPass(Registry);
326 initializeRewriteSymbolsPass(Registry);
327 initializeWinEHPreparePass(Registry);
328 initializeDwarfEHPreparePass(Registry);
330 #ifdef LINK_POLLY_INTO_TOOLS
331 polly::initializePollyPasses(Registry);
334 cl::ParseCommandLineOptions(argc, argv,
335 "llvm .bc -> .bc modular optimizer and analysis printer\n");
337 if (AnalyzeOnly && NoOutput) {
338 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
344 // Load the input module...
345 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
348 Err.print(argv[0], errs());
352 // If we are supposed to override the target triple, do so now.
353 if (!TargetTriple.empty())
354 M->setTargetTriple(Triple::normalize(TargetTriple));
356 // Figure out what stream we are supposed to write to...
357 std::unique_ptr<tool_output_file> Out;
359 if (!OutputFilename.empty())
360 errs() << "WARNING: The -o (output filename) option is ignored when\n"
361 "the --disable-output option is used.\n";
363 // Default to standard output.
364 if (OutputFilename.empty())
365 OutputFilename = "-";
368 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
370 errs() << EC.message() << '\n';
375 Triple ModuleTriple(M->getTargetTriple());
376 TargetMachine *Machine = nullptr;
377 if (ModuleTriple.getArch())
378 Machine = GetTargetMachine(ModuleTriple);
379 std::unique_ptr<TargetMachine> TM(Machine);
381 // If the output is set to be emitted to standard out, and standard out is a
382 // console, print out a warning message and refuse to do it. We don't
383 // impress anyone by spewing tons of binary goo to a terminal.
384 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
385 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
388 if (PassPipeline.getNumOccurrences() > 0) {
389 OutputKind OK = OK_NoOutput;
391 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
393 VerifierKind VK = VK_VerifyInAndOut;
397 VK = VK_VerifyEachPass;
399 // The user has asked to use the new pass manager and provided a pipeline
400 // string. Hand off the rest of the functionality to the new code for that
402 return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
403 PassPipeline, OK, VK)
408 // Create a PassManager to hold and optimize the collection of passes we are
411 legacy::PassManager Passes;
413 // Add an appropriate TargetLibraryInfo pass for the module's triple.
414 TargetLibraryInfoImpl TLII(ModuleTriple);
416 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
417 if (DisableSimplifyLibCalls)
418 TLII.disableAllFunctions();
419 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
421 // Add an appropriate DataLayout instance for this module.
422 const DataLayout *DL = M->getDataLayout();
423 if (!DL && !DefaultDataLayout.empty()) {
424 M->setDataLayout(DefaultDataLayout);
425 DL = M->getDataLayout();
429 Passes.add(new DataLayoutPass());
431 // Add internal analysis passes from the target machine.
432 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
433 : TargetIRAnalysis()));
435 std::unique_ptr<legacy::FunctionPassManager> FPasses;
436 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
437 FPasses.reset(new legacy::FunctionPassManager(M.get()));
439 FPasses->add(new DataLayoutPass());
440 FPasses->add(createTargetTransformInfoWrapperPass(
441 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
444 if (PrintBreakpoints) {
445 // Default to standard output.
447 if (OutputFilename.empty())
448 OutputFilename = "-";
451 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
454 errs() << EC.message() << '\n';
458 Passes.add(createBreakpointPrinter(Out->os()));
462 // If the -strip-debug command line option was specified, add it.
464 addPass(Passes, createStripSymbolsPass(true));
466 // Create a new optimization pass for each one specified on the command line
467 for (unsigned i = 0; i < PassList.size(); ++i) {
468 if (StandardLinkOpts &&
469 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
470 AddStandardLinkPasses(Passes);
471 StandardLinkOpts = false;
474 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
475 AddOptimizationPasses(Passes, *FPasses, 1, 0);
479 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
480 AddOptimizationPasses(Passes, *FPasses, 2, 0);
484 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
485 AddOptimizationPasses(Passes, *FPasses, 2, 1);
489 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
490 AddOptimizationPasses(Passes, *FPasses, 2, 2);
494 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
495 AddOptimizationPasses(Passes, *FPasses, 3, 0);
499 const PassInfo *PassInf = PassList[i];
501 if (PassInf->getTargetMachineCtor())
502 P = PassInf->getTargetMachineCtor()(TM.get());
503 else if (PassInf->getNormalCtor())
504 P = PassInf->getNormalCtor()();
506 errs() << argv[0] << ": cannot create pass: "
507 << PassInf->getPassName() << "\n";
509 PassKind Kind = P->getPassKind();
515 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
518 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
521 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
524 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
526 case PT_CallGraphSCC:
527 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
530 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
537 Passes.add(createPrintModulePass(errs()));
540 if (StandardLinkOpts) {
541 AddStandardLinkPasses(Passes);
542 StandardLinkOpts = false;
546 AddOptimizationPasses(Passes, *FPasses, 1, 0);
549 AddOptimizationPasses(Passes, *FPasses, 2, 0);
552 AddOptimizationPasses(Passes, *FPasses, 2, 1);
555 AddOptimizationPasses(Passes, *FPasses, 2, 2);
558 AddOptimizationPasses(Passes, *FPasses, 3, 0);
560 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
561 FPasses->doInitialization();
562 for (Function &F : *M)
564 FPasses->doFinalization();
567 // Check that the module is well formed on completion of optimization
568 if (!NoVerify && !VerifyEach) {
569 Passes.add(createVerifierPass());
570 Passes.add(createDebugInfoVerifierPass());
573 // Write bitcode or assembly to the output as the last step...
574 if (!NoOutput && !AnalyzeOnly) {
576 Passes.add(createPrintModulePass(Out->os()));
578 Passes.add(createBitcodeWriterPass(Out->os()));
581 // Before executing passes, print the final values of the LLVM options.
582 cl::PrintOptionValues();
584 // Now that we have all of the passes ready, run them.
588 if (!NoOutput || PrintBreakpoints)