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