[PM] Wire the analysis passes (such as they are) into the registry, and
[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) {
195     PM.add(createVerifierPass());
196     PM.add(createDebugInfoVerifierPass());
197   }
198 }
199
200 /// AddOptimizationPasses - This routine adds optimization passes
201 /// based on selected optimization level, OptLevel. This routine
202 /// duplicates llvm-gcc behaviour.
203 ///
204 /// OptLevel - Optimization Level
205 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
206                                   unsigned OptLevel, unsigned SizeLevel) {
207   FPM.add(createVerifierPass());          // Verify that input is correct
208   MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
209
210   PassManagerBuilder Builder;
211   Builder.OptLevel = OptLevel;
212   Builder.SizeLevel = SizeLevel;
213
214   if (DisableInline) {
215     // No inlining pass
216   } else if (OptLevel > 1) {
217     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
218   } else {
219     Builder.Inliner = createAlwaysInlinerPass();
220   }
221   Builder.DisableUnitAtATime = !UnitAtATime;
222   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
223                                DisableLoopUnrolling : OptLevel == 0;
224
225   // This is final, unless there is a #pragma vectorize enable
226   if (DisableLoopVectorization)
227     Builder.LoopVectorize = false;
228   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
229   else if (!Builder.LoopVectorize)
230     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
231
232   // When #pragma vectorize is on for SLP, do the same as above
233   Builder.SLPVectorize =
234       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
235
236   Builder.populateFunctionPassManager(FPM);
237   Builder.populateModulePassManager(MPM);
238 }
239
240 static void AddStandardCompilePasses(PassManagerBase &PM) {
241   PM.add(createVerifierPass());                  // Verify that input is correct
242
243   // If the -strip-debug command line option was specified, do it.
244   if (StripDebug)
245     addPass(PM, createStripSymbolsPass(true));
246
247   // Verify debug info only after it's (possibly) stripped.
248   PM.add(createDebugInfoVerifierPass());
249
250   if (DisableOptimizations) return;
251
252   // -std-compile-opts adds the same module passes as -O3.
253   PassManagerBuilder Builder;
254   if (!DisableInline)
255     Builder.Inliner = createFunctionInliningPass();
256   Builder.OptLevel = 3;
257   Builder.populateModulePassManager(PM);
258 }
259
260 static void AddStandardLinkPasses(PassManagerBase &PM) {
261   PM.add(createVerifierPass());                  // Verify that input is correct
262
263   // If the -strip-debug command line option was specified, do it.
264   if (StripDebug)
265     addPass(PM, createStripSymbolsPass(true));
266
267   // Verify debug info only after it's (possibly) stripped.
268   PM.add(createDebugInfoVerifierPass());
269
270   if (DisableOptimizations) return;
271
272   PassManagerBuilder Builder;
273   Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
274                                  /*RunInliner=*/ !DisableInline);
275 }
276
277 //===----------------------------------------------------------------------===//
278 // CodeGen-related helper functions.
279 //
280
281 CodeGenOpt::Level GetCodeGenOptLevel() {
282   if (OptLevelO1)
283     return CodeGenOpt::Less;
284   if (OptLevelO2)
285     return CodeGenOpt::Default;
286   if (OptLevelO3)
287     return CodeGenOpt::Aggressive;
288   return CodeGenOpt::None;
289 }
290
291 // Returns the TargetMachine instance or zero if no triple is provided.
292 static TargetMachine* GetTargetMachine(Triple TheTriple) {
293   std::string Error;
294   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
295                                                          Error);
296   // Some modules don't specify a triple, and this is okay.
297   if (!TheTarget) {
298     return 0;
299   }
300
301   // Package up features to be passed to target/subtarget
302   std::string FeaturesStr;
303   if (MAttrs.size()) {
304     SubtargetFeatures Features;
305     for (unsigned i = 0; i != MAttrs.size(); ++i)
306       Features.AddFeature(MAttrs[i]);
307     FeaturesStr = Features.getString();
308   }
309
310   return TheTarget->createTargetMachine(TheTriple.getTriple(),
311                                         MCPU, FeaturesStr,
312                                         InitTargetOptionsFromCodeGenFlags(),
313                                         RelocModel, CMModel,
314                                         GetCodeGenOptLevel());
315 }
316
317 #ifdef LINK_POLLY_INTO_TOOLS
318 namespace polly {
319 void initializePollyPasses(llvm::PassRegistry &Registry);
320 }
321 #endif
322
323 //===----------------------------------------------------------------------===//
324 // main for opt
325 //
326 int main(int argc, char **argv) {
327   sys::PrintStackTraceOnErrorSignal();
328   llvm::PrettyStackTraceProgram X(argc, argv);
329
330   // Enable debug stream buffering.
331   EnableDebugBuffering = true;
332
333   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
334   LLVMContext &Context = getGlobalContext();
335
336   InitializeAllTargets();
337   InitializeAllTargetMCs();
338
339   // Initialize passes
340   PassRegistry &Registry = *PassRegistry::getPassRegistry();
341   initializeCore(Registry);
342   initializeDebugIRPass(Registry);
343   initializeScalarOpts(Registry);
344   initializeObjCARCOpts(Registry);
345   initializeVectorization(Registry);
346   initializeIPO(Registry);
347   initializeAnalysis(Registry);
348   initializeIPA(Registry);
349   initializeTransformUtils(Registry);
350   initializeInstCombine(Registry);
351   initializeInstrumentation(Registry);
352   initializeTarget(Registry);
353   // For codegen passes, only passes that do IR to IR transformation are
354   // supported.
355   initializeCodeGenPreparePass(Registry);
356   initializeAtomicExpandLoadLinkedPass(Registry);
357
358 #ifdef LINK_POLLY_INTO_TOOLS
359   polly::initializePollyPasses(Registry);
360 #endif
361
362   cl::ParseCommandLineOptions(argc, argv,
363     "llvm .bc -> .bc modular optimizer and analysis printer\n");
364
365   if (AnalyzeOnly && NoOutput) {
366     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
367     return 1;
368   }
369
370   SMDiagnostic Err;
371
372   // Load the input module...
373   std::unique_ptr<Module> M;
374   M.reset(ParseIRFile(InputFilename, Err, Context));
375
376   if (M.get() == 0) {
377     Err.print(argv[0], errs());
378     return 1;
379   }
380
381   // If we are supposed to override the target triple, do so now.
382   if (!TargetTriple.empty())
383     M->setTargetTriple(Triple::normalize(TargetTriple));
384
385   // Figure out what stream we are supposed to write to...
386   std::unique_ptr<tool_output_file> Out;
387   if (NoOutput) {
388     if (!OutputFilename.empty())
389       errs() << "WARNING: The -o (output filename) option is ignored when\n"
390                 "the --disable-output option is used.\n";
391   } else {
392     // Default to standard output.
393     if (OutputFilename.empty())
394       OutputFilename = "-";
395
396     std::string ErrorInfo;
397     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
398                                    sys::fs::F_None));
399     if (!ErrorInfo.empty()) {
400       errs() << ErrorInfo << '\n';
401       return 1;
402     }
403   }
404
405   // If the output is set to be emitted to standard out, and standard out is a
406   // console, print out a warning message and refuse to do it.  We don't
407   // impress anyone by spewing tons of binary goo to a terminal.
408   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
409     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
410       NoOutput = true;
411
412   if (PassPipeline.getNumOccurrences() > 0) {
413     OutputKind OK = OK_NoOutput;
414     if (!NoOutput)
415       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
416
417     VerifierKind VK = VK_VerifyInAndOut;
418     if (NoVerify)
419       VK = VK_NoVerifier;
420     else if (VerifyEach)
421       VK = VK_VerifyEachPass;
422
423     // The user has asked to use the new pass manager and provided a pipeline
424     // string. Hand off the rest of the functionality to the new code for that
425     // layer.
426     return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
427                            OK, VK)
428                ? 0
429                : 1;
430   }
431
432   // Create a PassManager to hold and optimize the collection of passes we are
433   // about to build.
434   //
435   PassManager Passes;
436
437   // Add an appropriate TargetLibraryInfo pass for the module's triple.
438   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
439
440   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
441   if (DisableSimplifyLibCalls)
442     TLI->disableAllFunctions();
443   Passes.add(TLI);
444
445   // Add an appropriate DataLayout instance for this module.
446   const DataLayout *DL = M.get()->getDataLayout();
447   if (!DL && !DefaultDataLayout.empty()) {
448     M->setDataLayout(DefaultDataLayout);
449     DL = M.get()->getDataLayout();
450   }
451
452   if (DL)
453     Passes.add(new DataLayoutPass(M.get()));
454
455   Triple ModuleTriple(M->getTargetTriple());
456   TargetMachine *Machine = 0;
457   if (ModuleTriple.getArch())
458     Machine = GetTargetMachine(Triple(ModuleTriple));
459   std::unique_ptr<TargetMachine> TM(Machine);
460
461   // Add internal analysis passes from the target machine.
462   if (TM.get())
463     TM->addAnalysisPasses(Passes);
464
465   std::unique_ptr<FunctionPassManager> FPasses;
466   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
467     FPasses.reset(new FunctionPassManager(M.get()));
468     if (DL)
469       FPasses->add(new DataLayoutPass(M.get()));
470     if (TM.get())
471       TM->addAnalysisPasses(*FPasses);
472
473   }
474
475   if (PrintBreakpoints) {
476     // Default to standard output.
477     if (!Out) {
478       if (OutputFilename.empty())
479         OutputFilename = "-";
480
481       std::string ErrorInfo;
482       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
483                                      sys::fs::F_None));
484       if (!ErrorInfo.empty()) {
485         errs() << ErrorInfo << '\n';
486         return 1;
487       }
488     }
489     Passes.add(createBreakpointPrinter(Out->os()));
490     NoOutput = true;
491   }
492
493   // If the -strip-debug command line option was specified, add it.  If
494   // -std-compile-opts was also specified, it will handle StripDebug.
495   if (StripDebug && !StandardCompileOpts)
496     addPass(Passes, createStripSymbolsPass(true));
497
498   // Create a new optimization pass for each one specified on the command line
499   for (unsigned i = 0; i < PassList.size(); ++i) {
500     // Check to see if -std-compile-opts was specified before this option.  If
501     // so, handle it.
502     if (StandardCompileOpts &&
503         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
504       AddStandardCompilePasses(Passes);
505       StandardCompileOpts = false;
506     }
507
508     if (StandardLinkOpts &&
509         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
510       AddStandardLinkPasses(Passes);
511       StandardLinkOpts = false;
512     }
513
514     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
515       AddOptimizationPasses(Passes, *FPasses, 1, 0);
516       OptLevelO1 = false;
517     }
518
519     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
520       AddOptimizationPasses(Passes, *FPasses, 2, 0);
521       OptLevelO2 = false;
522     }
523
524     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
525       AddOptimizationPasses(Passes, *FPasses, 2, 1);
526       OptLevelOs = false;
527     }
528
529     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
530       AddOptimizationPasses(Passes, *FPasses, 2, 2);
531       OptLevelOz = false;
532     }
533
534     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
535       AddOptimizationPasses(Passes, *FPasses, 3, 0);
536       OptLevelO3 = false;
537     }
538
539     const PassInfo *PassInf = PassList[i];
540     Pass *P = 0;
541     if (PassInf->getTargetMachineCtor())
542       P = PassInf->getTargetMachineCtor()(TM.get());
543     else if (PassInf->getNormalCtor())
544       P = PassInf->getNormalCtor()();
545     else
546       errs() << argv[0] << ": cannot create pass: "
547              << PassInf->getPassName() << "\n";
548     if (P) {
549       PassKind Kind = P->getPassKind();
550       addPass(Passes, P);
551
552       if (AnalyzeOnly) {
553         switch (Kind) {
554         case PT_BasicBlock:
555           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
556           break;
557         case PT_Region:
558           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
559           break;
560         case PT_Loop:
561           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
562           break;
563         case PT_Function:
564           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
565           break;
566         case PT_CallGraphSCC:
567           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
568           break;
569         default:
570           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
571           break;
572         }
573       }
574     }
575
576     if (PrintEachXForm)
577       Passes.add(createPrintModulePass(errs()));
578   }
579
580   // If -std-compile-opts was specified at the end of the pass list, add them.
581   if (StandardCompileOpts) {
582     AddStandardCompilePasses(Passes);
583     StandardCompileOpts = false;
584   }
585
586   if (StandardLinkOpts) {
587     AddStandardLinkPasses(Passes);
588     StandardLinkOpts = false;
589   }
590
591   if (OptLevelO1)
592     AddOptimizationPasses(Passes, *FPasses, 1, 0);
593
594   if (OptLevelO2)
595     AddOptimizationPasses(Passes, *FPasses, 2, 0);
596
597   if (OptLevelOs)
598     AddOptimizationPasses(Passes, *FPasses, 2, 1);
599
600   if (OptLevelOz)
601     AddOptimizationPasses(Passes, *FPasses, 2, 2);
602
603   if (OptLevelO3)
604     AddOptimizationPasses(Passes, *FPasses, 3, 0);
605
606   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
607     FPasses->doInitialization();
608     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
609       FPasses->run(*F);
610     FPasses->doFinalization();
611   }
612
613   // Check that the module is well formed on completion of optimization
614   if (!NoVerify && !VerifyEach) {
615     Passes.add(createVerifierPass());
616     Passes.add(createDebugInfoVerifierPass());
617   }
618
619   // Write bitcode or assembly to the output as the last step...
620   if (!NoOutput && !AnalyzeOnly) {
621     if (OutputAssembly)
622       Passes.add(createPrintModulePass(Out->os()));
623     else
624       Passes.add(createBitcodeWriterPass(Out->os()));
625   }
626
627   // Before executing passes, print the final values of the LLVM options.
628   cl::PrintOptionValues();
629
630   // Now that we have all of the passes ready, run them.
631   Passes.run(*M.get());
632
633   // Declare success.
634   if (!NoOutput || PrintBreakpoints)
635     Out->keep();
636
637   return 0;
638 }