static link polly into tools
[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 #ifdef LINK_POLLY_INTO_TOOLS
308 namespace polly {
309 void initializePollyPasses(llvm::PassRegistry &Registry);
310 }
311 #endif
312
313 //===----------------------------------------------------------------------===//
314 // main for opt
315 //
316 int main(int argc, char **argv) {
317   sys::PrintStackTraceOnErrorSignal();
318   llvm::PrettyStackTraceProgram X(argc, argv);
319
320   // Enable debug stream buffering.
321   EnableDebugBuffering = true;
322
323   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
324   LLVMContext &Context = getGlobalContext();
325
326   InitializeAllTargets();
327   InitializeAllTargetMCs();
328
329   // Initialize passes
330   PassRegistry &Registry = *PassRegistry::getPassRegistry();
331   initializeCore(Registry);
332   initializeDebugIRPass(Registry);
333   initializeScalarOpts(Registry);
334   initializeObjCARCOpts(Registry);
335   initializeVectorization(Registry);
336   initializeIPO(Registry);
337   initializeAnalysis(Registry);
338   initializeIPA(Registry);
339   initializeTransformUtils(Registry);
340   initializeInstCombine(Registry);
341   initializeInstrumentation(Registry);
342   initializeTarget(Registry);
343   // For codegen passes, only passes that do IR to IR transformation are
344   // supported. For now, just add CodeGenPrepare.
345   initializeCodeGenPreparePass(Registry);
346
347 #ifdef LINK_POLLY_INTO_TOOLS
348   polly::initializePollyPasses(Registry);
349 #endif
350
351   cl::ParseCommandLineOptions(argc, argv,
352     "llvm .bc -> .bc modular optimizer and analysis printer\n");
353
354   if (AnalyzeOnly && NoOutput) {
355     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
356     return 1;
357   }
358
359   SMDiagnostic Err;
360
361   // Load the input module...
362   std::unique_ptr<Module> M;
363   M.reset(ParseIRFile(InputFilename, Err, Context));
364
365   if (M.get() == 0) {
366     Err.print(argv[0], errs());
367     return 1;
368   }
369
370   // If we are supposed to override the target triple, do so now.
371   if (!TargetTriple.empty())
372     M->setTargetTriple(Triple::normalize(TargetTriple));
373
374   // Figure out what stream we are supposed to write to...
375   std::unique_ptr<tool_output_file> Out;
376   if (NoOutput) {
377     if (!OutputFilename.empty())
378       errs() << "WARNING: The -o (output filename) option is ignored when\n"
379                 "the --disable-output option is used.\n";
380   } else {
381     // Default to standard output.
382     if (OutputFilename.empty())
383       OutputFilename = "-";
384
385     std::string ErrorInfo;
386     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
387                                    sys::fs::F_None));
388     if (!ErrorInfo.empty()) {
389       errs() << ErrorInfo << '\n';
390       return 1;
391     }
392   }
393
394   // If the output is set to be emitted to standard out, and standard out is a
395   // console, print out a warning message and refuse to do it.  We don't
396   // impress anyone by spewing tons of binary goo to a terminal.
397   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
398     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
399       NoOutput = true;
400
401   if (PassPipeline.getNumOccurrences() > 0) {
402     OutputKind OK = OK_NoOutput;
403     if (!NoOutput)
404       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
405
406     VerifierKind VK = VK_VerifyInAndOut;
407     if (NoVerify)
408       VK = VK_NoVerifier;
409     else if (VerifyEach)
410       VK = VK_VerifyEachPass;
411
412     // The user has asked to use the new pass manager and provided a pipeline
413     // string. Hand off the rest of the functionality to the new code for that
414     // layer.
415     return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
416                            OK, VK)
417                ? 0
418                : 1;
419   }
420
421   // Create a PassManager to hold and optimize the collection of passes we are
422   // about to build.
423   //
424   PassManager Passes;
425
426   // Add an appropriate TargetLibraryInfo pass for the module's triple.
427   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
428
429   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
430   if (DisableSimplifyLibCalls)
431     TLI->disableAllFunctions();
432   Passes.add(TLI);
433
434   // Add an appropriate DataLayout instance for this module.
435   const DataLayout *DL = M.get()->getDataLayout();
436   if (!DL && !DefaultDataLayout.empty()) {
437     M->setDataLayout(DefaultDataLayout);
438     DL = M.get()->getDataLayout();
439   }
440
441   if (DL)
442     Passes.add(new DataLayoutPass(M.get()));
443
444   Triple ModuleTriple(M->getTargetTriple());
445   TargetMachine *Machine = 0;
446   if (ModuleTriple.getArch())
447     Machine = GetTargetMachine(Triple(ModuleTriple));
448   std::unique_ptr<TargetMachine> TM(Machine);
449
450   // Add internal analysis passes from the target machine.
451   if (TM.get())
452     TM->addAnalysisPasses(Passes);
453
454   std::unique_ptr<FunctionPassManager> FPasses;
455   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
456     FPasses.reset(new FunctionPassManager(M.get()));
457     if (DL)
458       FPasses->add(new DataLayoutPass(M.get()));
459     if (TM.get())
460       TM->addAnalysisPasses(*FPasses);
461
462   }
463
464   if (PrintBreakpoints) {
465     // Default to standard output.
466     if (!Out) {
467       if (OutputFilename.empty())
468         OutputFilename = "-";
469
470       std::string ErrorInfo;
471       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
472                                      sys::fs::F_None));
473       if (!ErrorInfo.empty()) {
474         errs() << ErrorInfo << '\n';
475         return 1;
476       }
477     }
478     Passes.add(createBreakpointPrinter(Out->os()));
479     NoOutput = true;
480   }
481
482   // If the -strip-debug command line option was specified, add it.  If
483   // -std-compile-opts was also specified, it will handle StripDebug.
484   if (StripDebug && !StandardCompileOpts)
485     addPass(Passes, createStripSymbolsPass(true));
486
487   // Create a new optimization pass for each one specified on the command line
488   for (unsigned i = 0; i < PassList.size(); ++i) {
489     // Check to see if -std-compile-opts was specified before this option.  If
490     // so, handle it.
491     if (StandardCompileOpts &&
492         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
493       AddStandardCompilePasses(Passes);
494       StandardCompileOpts = false;
495     }
496
497     if (StandardLinkOpts &&
498         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
499       AddStandardLinkPasses(Passes);
500       StandardLinkOpts = false;
501     }
502
503     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
504       AddOptimizationPasses(Passes, *FPasses, 1, 0);
505       OptLevelO1 = false;
506     }
507
508     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
509       AddOptimizationPasses(Passes, *FPasses, 2, 0);
510       OptLevelO2 = false;
511     }
512
513     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
514       AddOptimizationPasses(Passes, *FPasses, 2, 1);
515       OptLevelOs = false;
516     }
517
518     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
519       AddOptimizationPasses(Passes, *FPasses, 2, 2);
520       OptLevelOz = false;
521     }
522
523     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
524       AddOptimizationPasses(Passes, *FPasses, 3, 0);
525       OptLevelO3 = false;
526     }
527
528     const PassInfo *PassInf = PassList[i];
529     Pass *P = 0;
530     if (PassInf->getTargetMachineCtor())
531       P = PassInf->getTargetMachineCtor()(TM.get());
532     else if (PassInf->getNormalCtor())
533       P = PassInf->getNormalCtor()();
534     else
535       errs() << argv[0] << ": cannot create pass: "
536              << PassInf->getPassName() << "\n";
537     if (P) {
538       PassKind Kind = P->getPassKind();
539       addPass(Passes, P);
540
541       if (AnalyzeOnly) {
542         switch (Kind) {
543         case PT_BasicBlock:
544           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
545           break;
546         case PT_Region:
547           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
548           break;
549         case PT_Loop:
550           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
551           break;
552         case PT_Function:
553           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
554           break;
555         case PT_CallGraphSCC:
556           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
557           break;
558         default:
559           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
560           break;
561         }
562       }
563     }
564
565     if (PrintEachXForm)
566       Passes.add(createPrintModulePass(errs()));
567   }
568
569   // If -std-compile-opts was specified at the end of the pass list, add them.
570   if (StandardCompileOpts) {
571     AddStandardCompilePasses(Passes);
572     StandardCompileOpts = false;
573   }
574
575   if (StandardLinkOpts) {
576     AddStandardLinkPasses(Passes);
577     StandardLinkOpts = false;
578   }
579
580   if (OptLevelO1)
581     AddOptimizationPasses(Passes, *FPasses, 1, 0);
582
583   if (OptLevelO2)
584     AddOptimizationPasses(Passes, *FPasses, 2, 0);
585
586   if (OptLevelOs)
587     AddOptimizationPasses(Passes, *FPasses, 2, 1);
588
589   if (OptLevelOz)
590     AddOptimizationPasses(Passes, *FPasses, 2, 2);
591
592   if (OptLevelO3)
593     AddOptimizationPasses(Passes, *FPasses, 3, 0);
594
595   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
596     FPasses->doInitialization();
597     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
598       FPasses->run(*F);
599     FPasses->doFinalization();
600   }
601
602   // Check that the module is well formed on completion of optimization
603   if (!NoVerify && !VerifyEach)
604     Passes.add(createVerifierPass());
605
606   // Write bitcode or assembly to the output as the last step...
607   if (!NoOutput && !AnalyzeOnly) {
608     if (OutputAssembly)
609       Passes.add(createPrintModulePass(Out->os()));
610     else
611       Passes.add(createBitcodeWriterPass(Out->os()));
612   }
613
614   // Before executing passes, print the final values of the LLVM options.
615   cl::PrintOptionValues();
616
617   // Now that we have all of the passes ready, run them.
618   Passes.run(*M.get());
619
620   // Declare success.
621   if (!NoOutput || PrintBreakpoints)
622     Out->keep();
623
624   return 0;
625 }