a54d319bfd89cefbcfd04c89b255598d78508a04
[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 "llvm/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/PassNameParser.h"
27 #include "llvm/System/Signals.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/ToolOutputFile.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/LinkAllVMCore.h"
38 #include <memory>
39 #include <algorithm>
40 using namespace llvm;
41
42 // The OptimizationList is automatically populated with registered Passes by the
43 // PassNameParser.
44 //
45 static cl::list<const PassInfo*, bool, PassNameParser>
46 PassList(cl::desc("Optimizations available:"));
47
48 // Other command line options...
49 //
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
52     cl::init("-"), cl::value_desc("filename"));
53
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Override output filename"),
56                cl::value_desc("filename"));
57
58 static cl::opt<bool>
59 Force("f", cl::desc("Enable binary output on terminals"));
60
61 static cl::opt<bool>
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
63
64 static cl::opt<bool>
65 NoOutput("disable-output",
66          cl::desc("Do not write result bitcode file"), cl::Hidden);
67
68 static cl::opt<bool>
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
70
71 static cl::opt<bool>
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
73
74 static cl::opt<bool>
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
76
77 static cl::opt<bool>
78 StripDebug("strip-debug",
79            cl::desc("Strip debugger symbol info from translation unit"));
80
81 static cl::opt<bool>
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
83
84 static cl::opt<bool>
85 DisableOptimizations("disable-opt",
86                      cl::desc("Do not run any optimization passes"));
87
88 static cl::opt<bool>
89 DisableInternalize("disable-internalize",
90                    cl::desc("Do not mark all symbols as internal"));
91
92 static cl::opt<bool>
93 StandardCompileOpts("std-compile-opts",
94                    cl::desc("Include the standard compile time optimizations"));
95
96 static cl::opt<bool>
97 StandardLinkOpts("std-link-opts",
98                  cl::desc("Include the standard link time optimizations"));
99
100 static cl::opt<bool>
101 OptLevelO1("O1",
102            cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
103
104 static cl::opt<bool>
105 OptLevelO2("O2",
106            cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
107
108 static cl::opt<bool>
109 OptLevelO3("O3",
110            cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
111
112 static cl::opt<bool>
113 UnitAtATime("funit-at-a-time",
114             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
115             cl::init(true));
116
117 static cl::opt<bool>
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119                         cl::desc("Disable simplify-libcalls"));
120
121 static cl::opt<bool>
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
123
124 static cl::alias
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
126
127 static cl::opt<bool>
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
129
130 static cl::opt<std::string>
131 DefaultDataLayout("default-data-layout", 
132           cl::desc("data layout string to use if not specified by module"),
133           cl::value_desc("layout-string"), cl::init(""));
134
135 // ---------- Define Printers for module and function passes ------------
136 namespace {
137
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
139   static char ID;
140   const PassInfo *PassToPrint;
141   raw_ostream &Out;
142   std::string PassName;
143
144   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
145     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
146       std::string PassToPrintName =  PassToPrint->getPassName();
147       PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
148     }
149
150   virtual bool runOnSCC(CallGraphSCC &SCC) {
151     if (!Quiet)
152       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
153
154     // Get and print pass...
155     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
156       Function *F = (*I)->getFunction();
157       if (F)
158         getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
159                                                               F->getParent());
160     }
161     return false;
162   }
163
164   virtual const char *getPassName() const { return PassName.c_str(); }
165
166   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
167     AU.addRequiredID(PassToPrint->getTypeInfo());
168     AU.setPreservesAll();
169   }
170 };
171
172 char CallGraphSCCPassPrinter::ID = 0;
173
174 struct ModulePassPrinter : public ModulePass {
175   static char ID;
176   const PassInfo *PassToPrint;
177   raw_ostream &Out;
178   std::string PassName;
179
180   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
181     : ModulePass(ID), PassToPrint(PI), Out(out) {
182       std::string PassToPrintName =  PassToPrint->getPassName();
183       PassName = "ModulePass Printer: " + PassToPrintName;
184     }
185
186   virtual bool runOnModule(Module &M) {
187     if (!Quiet)
188       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
189
190     // Get and print pass...
191     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
192     return false;
193   }
194
195   virtual const char *getPassName() const { return PassName.c_str(); }
196
197   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
198     AU.addRequiredID(PassToPrint->getTypeInfo());
199     AU.setPreservesAll();
200   }
201 };
202
203 char ModulePassPrinter::ID = 0;
204 struct FunctionPassPrinter : public FunctionPass {
205   const PassInfo *PassToPrint;
206   raw_ostream &Out;
207   static char ID;
208   std::string PassName;
209
210   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
211     : FunctionPass(ID), PassToPrint(PI), Out(out) {
212       std::string PassToPrintName =  PassToPrint->getPassName();
213       PassName = "FunctionPass Printer: " + PassToPrintName;
214     }
215
216   virtual bool runOnFunction(Function &F) {
217     if (!Quiet)
218       Out << "Printing analysis '" << PassToPrint->getPassName()
219           << "' for function '" << F.getName() << "':\n";
220
221     // Get and print pass...
222     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
223             F.getParent());
224     return false;
225   }
226
227   virtual const char *getPassName() const { return PassName.c_str(); }
228
229   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
230     AU.addRequiredID(PassToPrint->getTypeInfo());
231     AU.setPreservesAll();
232   }
233 };
234
235 char FunctionPassPrinter::ID = 0;
236
237 struct LoopPassPrinter : public LoopPass {
238   static char ID;
239   const PassInfo *PassToPrint;
240   raw_ostream &Out;
241   std::string PassName;
242
243   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
244     LoopPass(ID), PassToPrint(PI), Out(out) {
245       std::string PassToPrintName =  PassToPrint->getPassName();
246       PassName = "LoopPass Printer: " + PassToPrintName;
247     }
248
249
250   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
251     if (!Quiet)
252       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
253
254     // Get and print pass...
255     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
256                         L->getHeader()->getParent()->getParent());
257     return false;
258   }
259
260   virtual const char *getPassName() const { return PassName.c_str(); }
261
262   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
263     AU.addRequiredID(PassToPrint->getTypeInfo());
264     AU.setPreservesAll();
265   }
266 };
267
268 char LoopPassPrinter::ID = 0;
269
270 struct BasicBlockPassPrinter : public BasicBlockPass {
271   const PassInfo *PassToPrint;
272   raw_ostream &Out;
273   static char ID;
274   std::string PassName;
275
276   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
277     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
278       std::string PassToPrintName =  PassToPrint->getPassName();
279       PassName = "BasicBlockPass Printer: " + PassToPrintName;
280     }
281
282   virtual bool runOnBasicBlock(BasicBlock &BB) {
283     if (!Quiet)
284       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
285           << "': Pass " << PassToPrint->getPassName() << ":\n";
286
287     // Get and print pass...
288     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 
289             BB.getParent()->getParent());
290     return false;
291   }
292
293   virtual const char *getPassName() const { return PassName.c_str(); }
294
295   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
296     AU.addRequiredID(PassToPrint->getTypeInfo());
297     AU.setPreservesAll();
298   }
299 };
300
301 char BasicBlockPassPrinter::ID = 0;
302 inline void addPass(PassManagerBase &PM, Pass *P) {
303   // Add the pass to the pass manager...
304   PM.add(P);
305
306   // If we are verifying all of the intermediate steps, add the verifier...
307   if (VerifyEach) PM.add(createVerifierPass());
308 }
309
310 /// AddOptimizationPasses - This routine adds optimization passes
311 /// based on selected optimization level, OptLevel. This routine
312 /// duplicates llvm-gcc behaviour.
313 ///
314 /// OptLevel - Optimization Level
315 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
316                            unsigned OptLevel) {
317   createStandardFunctionPasses(&FPM, OptLevel);
318
319   llvm::Pass *InliningPass = 0;
320   if (DisableInline) {
321     // No inlining pass
322   } else if (OptLevel) {
323     unsigned Threshold = 200;
324     if (OptLevel > 2)
325       Threshold = 250;
326     InliningPass = createFunctionInliningPass(Threshold);
327   } else {
328     InliningPass = createAlwaysInlinerPass();
329   }
330   createStandardModulePasses(&MPM, OptLevel,
331                              /*OptimizeSize=*/ false,
332                              UnitAtATime,
333                              /*UnrollLoops=*/ OptLevel > 1,
334                              !DisableSimplifyLibCalls,
335                              /*HaveExceptions=*/ true,
336                              InliningPass);
337 }
338
339 void AddStandardCompilePasses(PassManagerBase &PM) {
340   PM.add(createVerifierPass());                  // Verify that input is correct
341
342   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
343
344   // If the -strip-debug command line option was specified, do it.
345   if (StripDebug)
346     addPass(PM, createStripSymbolsPass(true));
347
348   if (DisableOptimizations) return;
349
350   llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
351
352   // -std-compile-opts adds the same module passes as -O3.
353   createStandardModulePasses(&PM, 3,
354                              /*OptimizeSize=*/ false,
355                              /*UnitAtATime=*/ true,
356                              /*UnrollLoops=*/ true,
357                              /*SimplifyLibCalls=*/ true,
358                              /*HaveExceptions=*/ true,
359                              InliningPass);
360 }
361
362 void AddStandardLinkPasses(PassManagerBase &PM) {
363   PM.add(createVerifierPass());                  // Verify that input is correct
364
365   // If the -strip-debug command line option was specified, do it.
366   if (StripDebug)
367     addPass(PM, createStripSymbolsPass(true));
368
369   if (DisableOptimizations) return;
370
371   createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
372                           /*RunInliner=*/ !DisableInline,
373                           /*VerifyEach=*/ VerifyEach);
374 }
375
376 } // anonymous namespace
377
378
379 //===----------------------------------------------------------------------===//
380 // main for opt
381 //
382 int main(int argc, char **argv) {
383   sys::PrintStackTraceOnErrorSignal();
384   llvm::PrettyStackTraceProgram X(argc, argv);
385
386   if (AnalyzeOnly && NoOutput) {
387     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
388     return 1;
389   }
390   
391   // Enable debug stream buffering.
392   EnableDebugBuffering = true;
393
394   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
395   LLVMContext &Context = getGlobalContext();
396   
397   cl::ParseCommandLineOptions(argc, argv,
398     "llvm .bc -> .bc modular optimizer and analysis printer\n");
399
400   // Allocate a full target machine description only if necessary.
401   // FIXME: The choice of target should be controllable on the command line.
402   std::auto_ptr<TargetMachine> target;
403
404   SMDiagnostic Err;
405
406   // Load the input module...
407   std::auto_ptr<Module> M;
408   M.reset(ParseIRFile(InputFilename, Err, Context));
409
410   if (M.get() == 0) {
411     Err.Print(argv[0], errs());
412     return 1;
413   }
414
415   // Figure out what stream we are supposed to write to...
416   OwningPtr<tool_output_file> Out;
417   if (NoOutput) {
418     if (!OutputFilename.empty())
419       errs() << "WARNING: The -o (output filename) option is ignored when\n"
420                 "the --disable-output option is used.\n";
421   } else {
422     // Default to standard output.
423     if (OutputFilename.empty())
424       OutputFilename = "-";
425
426     std::string ErrorInfo;
427     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
428                                    raw_fd_ostream::F_Binary));
429     if (!ErrorInfo.empty()) {
430       errs() << ErrorInfo << '\n';
431       return 1;
432     }
433   }
434
435   // If the output is set to be emitted to standard out, and standard out is a
436   // console, print out a warning message and refuse to do it.  We don't
437   // impress anyone by spewing tons of binary goo to a terminal.
438   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
439     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
440       NoOutput = true;
441
442   // Create a PassManager to hold and optimize the collection of passes we are
443   // about to build...
444   //
445   PassManager Passes;
446
447   // Add an appropriate TargetData instance for this module...
448   TargetData *TD = 0;
449   const std::string &ModuleDataLayout = M.get()->getDataLayout();
450   if (!ModuleDataLayout.empty())
451     TD = new TargetData(ModuleDataLayout);
452   else if (!DefaultDataLayout.empty())
453     TD = new TargetData(DefaultDataLayout);
454
455   if (TD)
456     Passes.add(TD);
457
458   OwningPtr<PassManager> FPasses;
459   if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
460     FPasses.reset(new PassManager());
461     if (TD)
462       FPasses->add(new TargetData(*TD));
463   }
464
465   // If the -strip-debug command line option was specified, add it.  If
466   // -std-compile-opts was also specified, it will handle StripDebug.
467   if (StripDebug && !StandardCompileOpts)
468     addPass(Passes, createStripSymbolsPass(true));
469
470   // Create a new optimization pass for each one specified on the command line
471   for (unsigned i = 0; i < PassList.size(); ++i) {
472     // Check to see if -std-compile-opts was specified before this option.  If
473     // so, handle it.
474     if (StandardCompileOpts &&
475         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
476       AddStandardCompilePasses(Passes);
477       StandardCompileOpts = false;
478     }
479
480     if (StandardLinkOpts &&
481         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
482       AddStandardLinkPasses(Passes);
483       StandardLinkOpts = false;
484     }
485
486     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
487       AddOptimizationPasses(Passes, *FPasses, 1);
488       OptLevelO1 = false;
489     }
490
491     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
492       AddOptimizationPasses(Passes, *FPasses, 2);
493       OptLevelO2 = false;
494     }
495
496     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
497       AddOptimizationPasses(Passes, *FPasses, 3);
498       OptLevelO3 = false;
499     }
500
501     const PassInfo *PassInf = PassList[i];
502     Pass *P = 0;
503     if (PassInf->getNormalCtor())
504       P = PassInf->getNormalCtor()();
505     else
506       errs() << argv[0] << ": cannot create pass: "
507              << PassInf->getPassName() << "\n";
508     if (P) {
509       PassKind Kind = P->getPassKind();
510       addPass(Passes, P);
511
512       if (AnalyzeOnly) {
513         switch (Kind) {
514         case PT_BasicBlock:
515           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
516           break;
517         case PT_Loop:
518           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
519           break;
520         case PT_Function:
521           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
522           break;
523         case PT_CallGraphSCC:
524           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
525           break;
526         default:
527           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
528           break;
529         }
530       }
531     }
532
533     if (PrintEachXForm)
534       Passes.add(createPrintModulePass(&errs()));
535   }
536
537   // If -std-compile-opts was specified at the end of the pass list, add them.
538   if (StandardCompileOpts) {
539     AddStandardCompilePasses(Passes);
540     StandardCompileOpts = false;
541   }
542
543   if (StandardLinkOpts) {
544     AddStandardLinkPasses(Passes);
545     StandardLinkOpts = false;
546   }
547
548   if (OptLevelO1)
549     AddOptimizationPasses(Passes, *FPasses, 1);
550
551   if (OptLevelO2)
552     AddOptimizationPasses(Passes, *FPasses, 2);
553
554   if (OptLevelO3)
555     AddOptimizationPasses(Passes, *FPasses, 3);
556
557   if (OptLevelO1 || OptLevelO2 || OptLevelO3)
558     FPasses->run(*M.get());
559
560   // Check that the module is well formed on completion of optimization
561   if (!NoVerify && !VerifyEach)
562     Passes.add(createVerifierPass());
563
564   // Write bitcode or assembly to the output as the last step...
565   if (!NoOutput && !AnalyzeOnly) {
566     if (OutputAssembly)
567       Passes.add(createPrintModulePass(&Out->os()));
568     else
569       Passes.add(createBitcodeWriterPass(Out->os()));
570   }
571
572   // Now that we have all of the passes ready, run them.
573   Passes.run(*M.get());
574
575   // Declare success.
576   if (!NoOutput)
577     Out->keep();
578
579   return 0;
580 }