Handle inlining in populateLTOPassManager like in populateModulePassManager.
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BreakpointPrinter.h"
16 #include "NewPMDriver.h"
17 #include "PassPrinters.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/Bitcode/BitcodeWriterPass.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/LegacyPassNameParser.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/LinkAllIR.h"
34 #include "llvm/LinkAllPasses.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/PassManager.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/PluginLoader.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/SystemUtils.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Target/TargetLibraryInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
51 #include <algorithm>
52 #include <memory>
53 using namespace llvm;
54 using namespace opt_tool;
55
56 // The OptimizationList is automatically populated with registered Passes by the
57 // PassNameParser.
58 //
59 static cl::list<const PassInfo*, bool, PassNameParser>
60 PassList(cl::desc("Optimizations available:"));
61
62 // This flag specifies a textual description of the optimization pass pipeline
63 // to run over the module. This flag switches opt to use the new pass manager
64 // infrastructure, completely disabling all of the flags specific to the old
65 // pass management.
66 static cl::opt<std::string> PassPipeline(
67     "passes",
68     cl::desc("A textual description of the pass pipeline for optimizing"),
69     cl::Hidden);
70
71 // Other command line options...
72 //
73 static cl::opt<std::string>
74 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
75     cl::init("-"), cl::value_desc("filename"));
76
77 static cl::opt<std::string>
78 OutputFilename("o", cl::desc("Override output filename"),
79                cl::value_desc("filename"));
80
81 static cl::opt<bool>
82 Force("f", cl::desc("Enable binary output on terminals"));
83
84 static cl::opt<bool>
85 PrintEachXForm("p", cl::desc("Print module after each transformation"));
86
87 static cl::opt<bool>
88 NoOutput("disable-output",
89          cl::desc("Do not write result bitcode file"), cl::Hidden);
90
91 static cl::opt<bool>
92 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
93
94 static cl::opt<bool>
95 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
96
97 static cl::opt<bool>
98 VerifyEach("verify-each", cl::desc("Verify after each transform"));
99
100 static cl::opt<bool>
101 StripDebug("strip-debug",
102            cl::desc("Strip debugger symbol info from translation unit"));
103
104 static cl::opt<bool>
105 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
106
107 static cl::opt<bool>
108 DisableOptimizations("disable-opt",
109                      cl::desc("Do not run any optimization passes"));
110
111 static cl::opt<bool>
112 StandardCompileOpts("std-compile-opts",
113                    cl::desc("Include the standard compile time optimizations"));
114
115 static cl::opt<bool>
116 StandardLinkOpts("std-link-opts",
117                  cl::desc("Include the standard link time optimizations"));
118
119 static cl::opt<bool>
120 OptLevelO1("O1",
121            cl::desc("Optimization level 1. Similar to clang -O1"));
122
123 static cl::opt<bool>
124 OptLevelO2("O2",
125            cl::desc("Optimization level 2. Similar to clang -O2"));
126
127 static cl::opt<bool>
128 OptLevelOs("Os",
129            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
130
131 static cl::opt<bool>
132 OptLevelOz("Oz",
133            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
134
135 static cl::opt<bool>
136 OptLevelO3("O3",
137            cl::desc("Optimization level 3. Similar to clang -O3"));
138
139 static cl::opt<std::string>
140 TargetTriple("mtriple", cl::desc("Override target triple for module"));
141
142 static cl::opt<bool>
143 UnitAtATime("funit-at-a-time",
144             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
145             cl::init(true));
146
147 static cl::opt<bool>
148 DisableLoopUnrolling("disable-loop-unrolling",
149                      cl::desc("Disable loop unrolling in all relevant passes"),
150                      cl::init(false));
151 static cl::opt<bool>
152 DisableLoopVectorization("disable-loop-vectorization",
153                      cl::desc("Disable the loop vectorization pass"),
154                      cl::init(false));
155
156 static cl::opt<bool>
157 DisableSLPVectorization("disable-slp-vectorization",
158                         cl::desc("Disable the slp vectorization pass"),
159                         cl::init(false));
160
161
162 static cl::opt<bool>
163 DisableSimplifyLibCalls("disable-simplify-libcalls",
164                         cl::desc("Disable simplify-libcalls"));
165
166 static cl::opt<bool>
167 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
168
169 static cl::alias
170 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
171
172 static cl::opt<bool>
173 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
174
175 static cl::opt<bool>
176 PrintBreakpoints("print-breakpoints-for-testing",
177                  cl::desc("Print select breakpoints location for testing"));
178
179 static cl::opt<std::string>
180 DefaultDataLayout("default-data-layout",
181           cl::desc("data layout string to use if not specified by module"),
182           cl::value_desc("layout-string"), cl::init(""));
183
184
185
186 static inline void addPass(PassManagerBase &PM, Pass *P) {
187   // Add the pass to the pass manager...
188   PM.add(P);
189
190   // If we are verifying all of the intermediate steps, add the verifier...
191   if (VerifyEach) {
192     PM.add(createVerifierPass());
193     PM.add(createDebugInfoVerifierPass());
194   }
195 }
196
197 /// AddOptimizationPasses - This routine adds optimization passes
198 /// based on selected optimization level, OptLevel. This routine
199 /// duplicates llvm-gcc behaviour.
200 ///
201 /// OptLevel - Optimization Level
202 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
203                                   unsigned OptLevel, unsigned SizeLevel) {
204   FPM.add(createVerifierPass());          // Verify that input is correct
205   MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
206
207   PassManagerBuilder Builder;
208   Builder.OptLevel = OptLevel;
209   Builder.SizeLevel = SizeLevel;
210
211   if (DisableInline) {
212     // No inlining pass
213   } else if (OptLevel > 1) {
214     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
215   } else {
216     Builder.Inliner = createAlwaysInlinerPass();
217   }
218   Builder.DisableUnitAtATime = !UnitAtATime;
219   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
220                                DisableLoopUnrolling : OptLevel == 0;
221
222   // This is final, unless there is a #pragma vectorize enable
223   if (DisableLoopVectorization)
224     Builder.LoopVectorize = false;
225   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
226   else if (!Builder.LoopVectorize)
227     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
228
229   // When #pragma vectorize is on for SLP, do the same as above
230   Builder.SLPVectorize =
231       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
232
233   Builder.populateFunctionPassManager(FPM);
234   Builder.populateModulePassManager(MPM);
235 }
236
237 static void AddStandardCompilePasses(PassManagerBase &PM) {
238   PM.add(createVerifierPass());                  // Verify that input is correct
239
240   // If the -strip-debug command line option was specified, do it.
241   if (StripDebug)
242     addPass(PM, createStripSymbolsPass(true));
243
244   // Verify debug info only after it's (possibly) stripped.
245   PM.add(createDebugInfoVerifierPass());
246
247   if (DisableOptimizations) return;
248
249   // -std-compile-opts adds the same module passes as -O3.
250   PassManagerBuilder Builder;
251   if (!DisableInline)
252     Builder.Inliner = createFunctionInliningPass();
253   Builder.OptLevel = 3;
254   Builder.populateModulePassManager(PM);
255 }
256
257 static void AddStandardLinkPasses(PassManagerBase &PM) {
258   PM.add(createVerifierPass());                  // Verify that input is correct
259
260   // If the -strip-debug command line option was specified, do it.
261   if (StripDebug)
262     addPass(PM, createStripSymbolsPass(true));
263
264   // Verify debug info only after it's (possibly) stripped.
265   PM.add(createDebugInfoVerifierPass());
266
267   if (DisableOptimizations) return;
268
269   PassManagerBuilder Builder;
270   if (!DisableInline)
271     Builder.Inliner = createFunctionInliningPass();
272   Builder.populateLTOPassManager(PM);
273 }
274
275 //===----------------------------------------------------------------------===//
276 // CodeGen-related helper functions.
277 //
278
279 CodeGenOpt::Level GetCodeGenOptLevel() {
280   if (OptLevelO1)
281     return CodeGenOpt::Less;
282   if (OptLevelO2)
283     return CodeGenOpt::Default;
284   if (OptLevelO3)
285     return CodeGenOpt::Aggressive;
286   return CodeGenOpt::None;
287 }
288
289 // Returns the TargetMachine instance or zero if no triple is provided.
290 static TargetMachine* GetTargetMachine(Triple TheTriple) {
291   std::string Error;
292   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
293                                                          Error);
294   // Some modules don't specify a triple, and this is okay.
295   if (!TheTarget) {
296     return nullptr;
297   }
298
299   // Package up features to be passed to target/subtarget
300   std::string FeaturesStr;
301   if (MAttrs.size()) {
302     SubtargetFeatures Features;
303     for (unsigned i = 0; i != MAttrs.size(); ++i)
304       Features.AddFeature(MAttrs[i]);
305     FeaturesStr = Features.getString();
306   }
307
308   return TheTarget->createTargetMachine(TheTriple.getTriple(),
309                                         MCPU, FeaturesStr,
310                                         InitTargetOptionsFromCodeGenFlags(),
311                                         RelocModel, CMModel,
312                                         GetCodeGenOptLevel());
313 }
314
315 #ifdef LINK_POLLY_INTO_TOOLS
316 namespace polly {
317 void initializePollyPasses(llvm::PassRegistry &Registry);
318 }
319 #endif
320
321 //===----------------------------------------------------------------------===//
322 // main for opt
323 //
324 int main(int argc, char **argv) {
325   sys::PrintStackTraceOnErrorSignal();
326   llvm::PrettyStackTraceProgram X(argc, argv);
327
328   // Enable debug stream buffering.
329   EnableDebugBuffering = true;
330
331   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
332   LLVMContext &Context = getGlobalContext();
333
334   InitializeAllTargets();
335   InitializeAllTargetMCs();
336   InitializeAllAsmPrinters();
337
338   // Initialize passes
339   PassRegistry &Registry = *PassRegistry::getPassRegistry();
340   initializeCore(Registry);
341   initializeDebugIRPass(Registry);
342   initializeScalarOpts(Registry);
343   initializeObjCARCOpts(Registry);
344   initializeVectorization(Registry);
345   initializeIPO(Registry);
346   initializeAnalysis(Registry);
347   initializeIPA(Registry);
348   initializeTransformUtils(Registry);
349   initializeInstCombine(Registry);
350   initializeInstrumentation(Registry);
351   initializeTarget(Registry);
352   // For codegen passes, only passes that do IR to IR transformation are
353   // supported.
354   initializeCodeGenPreparePass(Registry);
355   initializeAtomicExpandLoadLinkedPass(Registry);
356
357 #ifdef LINK_POLLY_INTO_TOOLS
358   polly::initializePollyPasses(Registry);
359 #endif
360
361   cl::ParseCommandLineOptions(argc, argv,
362     "llvm .bc -> .bc modular optimizer and analysis printer\n");
363
364   if (AnalyzeOnly && NoOutput) {
365     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
366     return 1;
367   }
368
369   SMDiagnostic Err;
370
371   // Load the input module...
372   std::unique_ptr<Module> M;
373   M.reset(ParseIRFile(InputFilename, Err, Context));
374
375   if (!M.get()) {
376     Err.print(argv[0], errs());
377     return 1;
378   }
379
380   // If we are supposed to override the target triple, do so now.
381   if (!TargetTriple.empty())
382     M->setTargetTriple(Triple::normalize(TargetTriple));
383
384   // Figure out what stream we are supposed to write to...
385   std::unique_ptr<tool_output_file> Out;
386   if (NoOutput) {
387     if (!OutputFilename.empty())
388       errs() << "WARNING: The -o (output filename) option is ignored when\n"
389                 "the --disable-output option is used.\n";
390   } else {
391     // Default to standard output.
392     if (OutputFilename.empty())
393       OutputFilename = "-";
394
395     std::string ErrorInfo;
396     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
397                                    sys::fs::F_None));
398     if (!ErrorInfo.empty()) {
399       errs() << ErrorInfo << '\n';
400       return 1;
401     }
402   }
403
404   // If the output is set to be emitted to standard out, and standard out is a
405   // console, print out a warning message and refuse to do it.  We don't
406   // impress anyone by spewing tons of binary goo to a terminal.
407   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
408     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
409       NoOutput = true;
410
411   if (PassPipeline.getNumOccurrences() > 0) {
412     OutputKind OK = OK_NoOutput;
413     if (!NoOutput)
414       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
415
416     VerifierKind VK = VK_VerifyInAndOut;
417     if (NoVerify)
418       VK = VK_NoVerifier;
419     else if (VerifyEach)
420       VK = VK_VerifyEachPass;
421
422     // The user has asked to use the new pass manager and provided a pipeline
423     // string. Hand off the rest of the functionality to the new code for that
424     // layer.
425     return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
426                            OK, VK)
427                ? 0
428                : 1;
429   }
430
431   // Create a PassManager to hold and optimize the collection of passes we are
432   // about to build.
433   //
434   PassManager Passes;
435
436   // Add an appropriate TargetLibraryInfo pass for the module's triple.
437   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
438
439   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
440   if (DisableSimplifyLibCalls)
441     TLI->disableAllFunctions();
442   Passes.add(TLI);
443
444   // Add an appropriate DataLayout instance for this module.
445   const DataLayout *DL = M.get()->getDataLayout();
446   if (!DL && !DefaultDataLayout.empty()) {
447     M->setDataLayout(DefaultDataLayout);
448     DL = M.get()->getDataLayout();
449   }
450
451   if (DL)
452     Passes.add(new DataLayoutPass(M.get()));
453
454   Triple ModuleTriple(M->getTargetTriple());
455   TargetMachine *Machine = nullptr;
456   if (ModuleTriple.getArch())
457     Machine = GetTargetMachine(Triple(ModuleTriple));
458   std::unique_ptr<TargetMachine> TM(Machine);
459
460   // Add internal analysis passes from the target machine.
461   if (TM.get())
462     TM->addAnalysisPasses(Passes);
463
464   std::unique_ptr<FunctionPassManager> FPasses;
465   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
466     FPasses.reset(new FunctionPassManager(M.get()));
467     if (DL)
468       FPasses->add(new DataLayoutPass(M.get()));
469     if (TM.get())
470       TM->addAnalysisPasses(*FPasses);
471
472   }
473
474   if (PrintBreakpoints) {
475     // Default to standard output.
476     if (!Out) {
477       if (OutputFilename.empty())
478         OutputFilename = "-";
479
480       std::string ErrorInfo;
481       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
482                                      sys::fs::F_None));
483       if (!ErrorInfo.empty()) {
484         errs() << ErrorInfo << '\n';
485         return 1;
486       }
487     }
488     Passes.add(createBreakpointPrinter(Out->os()));
489     NoOutput = true;
490   }
491
492   // If the -strip-debug command line option was specified, add it.  If
493   // -std-compile-opts was also specified, it will handle StripDebug.
494   if (StripDebug && !StandardCompileOpts)
495     addPass(Passes, createStripSymbolsPass(true));
496
497   // Create a new optimization pass for each one specified on the command line
498   for (unsigned i = 0; i < PassList.size(); ++i) {
499     // Check to see if -std-compile-opts was specified before this option.  If
500     // so, handle it.
501     if (StandardCompileOpts &&
502         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
503       AddStandardCompilePasses(Passes);
504       StandardCompileOpts = false;
505     }
506
507     if (StandardLinkOpts &&
508         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
509       AddStandardLinkPasses(Passes);
510       StandardLinkOpts = false;
511     }
512
513     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
514       AddOptimizationPasses(Passes, *FPasses, 1, 0);
515       OptLevelO1 = false;
516     }
517
518     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
519       AddOptimizationPasses(Passes, *FPasses, 2, 0);
520       OptLevelO2 = false;
521     }
522
523     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
524       AddOptimizationPasses(Passes, *FPasses, 2, 1);
525       OptLevelOs = false;
526     }
527
528     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
529       AddOptimizationPasses(Passes, *FPasses, 2, 2);
530       OptLevelOz = false;
531     }
532
533     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
534       AddOptimizationPasses(Passes, *FPasses, 3, 0);
535       OptLevelO3 = false;
536     }
537
538     const PassInfo *PassInf = PassList[i];
539     Pass *P = nullptr;
540     if (PassInf->getTargetMachineCtor())
541       P = PassInf->getTargetMachineCtor()(TM.get());
542     else if (PassInf->getNormalCtor())
543       P = PassInf->getNormalCtor()();
544     else
545       errs() << argv[0] << ": cannot create pass: "
546              << PassInf->getPassName() << "\n";
547     if (P) {
548       PassKind Kind = P->getPassKind();
549       addPass(Passes, P);
550
551       if (AnalyzeOnly) {
552         switch (Kind) {
553         case PT_BasicBlock:
554           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
555           break;
556         case PT_Region:
557           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
558           break;
559         case PT_Loop:
560           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
561           break;
562         case PT_Function:
563           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
564           break;
565         case PT_CallGraphSCC:
566           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
567           break;
568         default:
569           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
570           break;
571         }
572       }
573     }
574
575     if (PrintEachXForm)
576       Passes.add(createPrintModulePass(errs()));
577   }
578
579   // If -std-compile-opts was specified at the end of the pass list, add them.
580   if (StandardCompileOpts) {
581     AddStandardCompilePasses(Passes);
582     StandardCompileOpts = false;
583   }
584
585   if (StandardLinkOpts) {
586     AddStandardLinkPasses(Passes);
587     StandardLinkOpts = false;
588   }
589
590   if (OptLevelO1)
591     AddOptimizationPasses(Passes, *FPasses, 1, 0);
592
593   if (OptLevelO2)
594     AddOptimizationPasses(Passes, *FPasses, 2, 0);
595
596   if (OptLevelOs)
597     AddOptimizationPasses(Passes, *FPasses, 2, 1);
598
599   if (OptLevelOz)
600     AddOptimizationPasses(Passes, *FPasses, 2, 2);
601
602   if (OptLevelO3)
603     AddOptimizationPasses(Passes, *FPasses, 3, 0);
604
605   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
606     FPasses->doInitialization();
607     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
608       FPasses->run(*F);
609     FPasses->doFinalization();
610   }
611
612   // Check that the module is well formed on completion of optimization
613   if (!NoVerify && !VerifyEach) {
614     Passes.add(createVerifierPass());
615     Passes.add(createDebugInfoVerifierPass());
616   }
617
618   // Write bitcode or assembly to the output as the last step...
619   if (!NoOutput && !AnalyzeOnly) {
620     if (OutputAssembly)
621       Passes.add(createPrintModulePass(Out->os()));
622     else
623       Passes.add(createBitcodeWriterPass(Out->os()));
624   }
625
626   // Before executing passes, print the final values of the LLVM options.
627   cl::PrintOptionValues();
628
629   // Now that we have all of the passes ready, run them.
630   Passes.run(*M.get());
631
632   // Declare success.
633   if (!NoOutput || PrintBreakpoints)
634     Out->keep();
635
636   return 0;
637 }