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