Include original pass name in the PassPrinter's name.
[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/raw_ostream.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       for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
155         Function *F = (*I)->getFunction();
156         if (F)
157           getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 
158                 F->getParent());
159       }
160     }
161     // Get and print pass...
162     return false;
163   }
164
165   virtual const char *getPassName() const { return PassName.c_str(); }
166
167   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168     AU.addRequiredID(PassToPrint->getTypeInfo());
169     AU.setPreservesAll();
170   }
171 };
172
173 char CallGraphSCCPassPrinter::ID = 0;
174
175 struct ModulePassPrinter : public ModulePass {
176   static char ID;
177   const PassInfo *PassToPrint;
178   raw_ostream &Out;
179   std::string PassName;
180
181   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
182     : ModulePass(ID), PassToPrint(PI), Out(out) {
183       std::string PassToPrintName =  PassToPrint->getPassName();
184       PassName = "ModulePass Printer: " + PassToPrintName;
185     }
186
187   virtual bool runOnModule(Module &M) {
188     if (!Quiet) {
189       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
190       getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
191     }
192
193     // Get and print pass...
194     return false;
195   }
196
197   virtual const char *getPassName() const { return PassName.c_str(); }
198
199   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
200     AU.addRequiredID(PassToPrint->getTypeInfo());
201     AU.setPreservesAll();
202   }
203 };
204
205 char ModulePassPrinter::ID = 0;
206 struct FunctionPassPrinter : public FunctionPass {
207   const PassInfo *PassToPrint;
208   raw_ostream &Out;
209   static char ID;
210   std::string PassName;
211
212   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
213     : FunctionPass(ID), PassToPrint(PI), Out(out) {
214       std::string PassToPrintName =  PassToPrint->getPassName();
215       PassName = "FunctionPass Printer: " + PassToPrintName;
216     }
217
218   virtual bool runOnFunction(Function &F) {
219     if (!Quiet) {
220       Out << "Printing analysis '" << PassToPrint->getPassName()
221           << "' for function '" << F.getName() << "':\n";
222     }
223     // Get and print pass...
224     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
225             F.getParent());
226     return false;
227   }
228
229   virtual const char *getPassName() const { return PassName.c_str(); }
230
231   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
232     AU.addRequiredID(PassToPrint->getTypeInfo());
233     AU.setPreservesAll();
234   }
235 };
236
237 char FunctionPassPrinter::ID = 0;
238
239 struct LoopPassPrinter : public LoopPass {
240   static char ID;
241   const PassInfo *PassToPrint;
242   raw_ostream &Out;
243   std::string PassName;
244
245   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
246     LoopPass(ID), PassToPrint(PI), Out(out) {
247       std::string PassToPrintName =  PassToPrint->getPassName();
248       PassName = "LoopPass Printer: " + PassToPrintName;
249     }
250
251
252   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
253     if (!Quiet) {
254       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
255       getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
256                                   L->getHeader()->getParent()->getParent());
257     }
258     // Get and print pass...
259     return false;
260   }
261
262   virtual const char *getPassName() const { return PassName.c_str(); }
263
264   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
265     AU.addRequiredID(PassToPrint->getTypeInfo());
266     AU.setPreservesAll();
267   }
268 };
269
270 char LoopPassPrinter::ID = 0;
271
272 struct BasicBlockPassPrinter : public BasicBlockPass {
273   const PassInfo *PassToPrint;
274   raw_ostream &Out;
275   static char ID;
276   std::string PassName;
277
278   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
279     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
280       std::string PassToPrintName =  PassToPrint->getPassName();
281       PassName = "BasicBlockPass Printer: " + PassToPrintName;
282     }
283
284   virtual bool runOnBasicBlock(BasicBlock &BB) {
285     if (!Quiet) {
286       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
287           << "': Pass " << PassToPrint->getPassName() << ":\n";
288     }
289
290     // Get and print pass...
291     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 
292             BB.getParent()->getParent());
293     return false;
294   }
295
296   virtual const char *getPassName() const { return PassName.c_str(); }
297
298   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
299     AU.addRequiredID(PassToPrint->getTypeInfo());
300     AU.setPreservesAll();
301   }
302 };
303
304 char BasicBlockPassPrinter::ID = 0;
305 inline void addPass(PassManagerBase &PM, Pass *P) {
306   // Add the pass to the pass manager...
307   PM.add(P);
308
309   // If we are verifying all of the intermediate steps, add the verifier...
310   if (VerifyEach) PM.add(createVerifierPass());
311 }
312
313 /// AddOptimizationPasses - This routine adds optimization passes
314 /// based on selected optimization level, OptLevel. This routine
315 /// duplicates llvm-gcc behaviour.
316 ///
317 /// OptLevel - Optimization Level
318 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
319                            unsigned OptLevel) {
320   createStandardFunctionPasses(&FPM, OptLevel);
321
322   llvm::Pass *InliningPass = 0;
323   if (DisableInline) {
324     // No inlining pass
325   } else if (OptLevel) {
326     unsigned Threshold = 200;
327     if (OptLevel > 2)
328       Threshold = 250;
329     InliningPass = createFunctionInliningPass(Threshold);
330   } else {
331     InliningPass = createAlwaysInlinerPass();
332   }
333   createStandardModulePasses(&MPM, OptLevel,
334                              /*OptimizeSize=*/ false,
335                              UnitAtATime,
336                              /*UnrollLoops=*/ OptLevel > 1,
337                              !DisableSimplifyLibCalls,
338                              /*HaveExceptions=*/ true,
339                              InliningPass);
340 }
341
342 void AddStandardCompilePasses(PassManagerBase &PM) {
343   PM.add(createVerifierPass());                  // Verify that input is correct
344
345   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
346
347   // If the -strip-debug command line option was specified, do it.
348   if (StripDebug)
349     addPass(PM, createStripSymbolsPass(true));
350
351   if (DisableOptimizations) return;
352
353   llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
354
355   // -std-compile-opts adds the same module passes as -O3.
356   createStandardModulePasses(&PM, 3,
357                              /*OptimizeSize=*/ false,
358                              /*UnitAtATime=*/ true,
359                              /*UnrollLoops=*/ true,
360                              /*SimplifyLibCalls=*/ true,
361                              /*HaveExceptions=*/ true,
362                              InliningPass);
363 }
364
365 void AddStandardLinkPasses(PassManagerBase &PM) {
366   PM.add(createVerifierPass());                  // Verify that input is correct
367
368   // If the -strip-debug command line option was specified, do it.
369   if (StripDebug)
370     addPass(PM, createStripSymbolsPass(true));
371
372   if (DisableOptimizations) return;
373
374   createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
375                           /*RunInliner=*/ !DisableInline,
376                           /*VerifyEach=*/ VerifyEach);
377 }
378
379 } // anonymous namespace
380
381
382 //===----------------------------------------------------------------------===//
383 // main for opt
384 //
385 int main(int argc, char **argv) {
386   sys::PrintStackTraceOnErrorSignal();
387   llvm::PrettyStackTraceProgram X(argc, argv);
388
389   if (AnalyzeOnly && NoOutput) {
390     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
391     return 1;
392   }
393   
394   // Enable debug stream buffering.
395   EnableDebugBuffering = true;
396
397   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
398   LLVMContext &Context = getGlobalContext();
399   
400   cl::ParseCommandLineOptions(argc, argv,
401     "llvm .bc -> .bc modular optimizer and analysis printer\n");
402
403   // Allocate a full target machine description only if necessary.
404   // FIXME: The choice of target should be controllable on the command line.
405   std::auto_ptr<TargetMachine> target;
406
407   SMDiagnostic Err;
408
409   // Load the input module...
410   std::auto_ptr<Module> M;
411   M.reset(ParseIRFile(InputFilename, Err, Context));
412
413   if (M.get() == 0) {
414     Err.Print(argv[0], errs());
415     return 1;
416   }
417
418   // Figure out what stream we are supposed to write to...
419   OwningPtr<tool_output_file> Out;
420   if (NoOutput) {
421     if (!OutputFilename.empty())
422       errs() << "WARNING: The -o (output filename) option is ignored when\n"
423                 "the --disable-output option is used.\n";
424   } else {
425     // Default to standard output.
426     if (OutputFilename.empty())
427       OutputFilename = "-";
428
429     std::string ErrorInfo;
430     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
431                                    raw_fd_ostream::F_Binary));
432     if (!ErrorInfo.empty()) {
433       errs() << ErrorInfo << '\n';
434       return 1;
435     }
436   }
437
438   // If the output is set to be emitted to standard out, and standard out is a
439   // console, print out a warning message and refuse to do it.  We don't
440   // impress anyone by spewing tons of binary goo to a terminal.
441   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
442     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
443       NoOutput = true;
444
445   // Create a PassManager to hold and optimize the collection of passes we are
446   // about to build...
447   //
448   PassManager Passes;
449
450   // Add an appropriate TargetData instance for this module...
451   TargetData *TD = 0;
452   const std::string &ModuleDataLayout = M.get()->getDataLayout();
453   if (!ModuleDataLayout.empty())
454     TD = new TargetData(ModuleDataLayout);
455   else if (!DefaultDataLayout.empty())
456     TD = new TargetData(DefaultDataLayout);
457
458   if (TD)
459     Passes.add(TD);
460
461   OwningPtr<PassManager> FPasses;
462   if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
463     FPasses.reset(new PassManager());
464     if (TD)
465       FPasses->add(new TargetData(*TD));
466   }
467
468   // If the -strip-debug command line option was specified, add it.  If
469   // -std-compile-opts was also specified, it will handle StripDebug.
470   if (StripDebug && !StandardCompileOpts)
471     addPass(Passes, createStripSymbolsPass(true));
472
473   // Create a new optimization pass for each one specified on the command line
474   for (unsigned i = 0; i < PassList.size(); ++i) {
475     // Check to see if -std-compile-opts was specified before this option.  If
476     // so, handle it.
477     if (StandardCompileOpts &&
478         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
479       AddStandardCompilePasses(Passes);
480       StandardCompileOpts = false;
481     }
482
483     if (StandardLinkOpts &&
484         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
485       AddStandardLinkPasses(Passes);
486       StandardLinkOpts = false;
487     }
488
489     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
490       AddOptimizationPasses(Passes, *FPasses, 1);
491       OptLevelO1 = false;
492     }
493
494     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
495       AddOptimizationPasses(Passes, *FPasses, 2);
496       OptLevelO2 = false;
497     }
498
499     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
500       AddOptimizationPasses(Passes, *FPasses, 3);
501       OptLevelO3 = false;
502     }
503
504     const PassInfo *PassInf = PassList[i];
505     Pass *P = 0;
506     if (PassInf->getNormalCtor())
507       P = PassInf->getNormalCtor()();
508     else
509       errs() << argv[0] << ": cannot create pass: "
510              << PassInf->getPassName() << "\n";
511     if (P) {
512       PassKind Kind = P->getPassKind();
513       addPass(Passes, P);
514
515       if (AnalyzeOnly) {
516         switch (Kind) {
517         case PT_BasicBlock:
518           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
519           break;
520         case PT_Loop:
521           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
522           break;
523         case PT_Function:
524           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
525           break;
526         case PT_CallGraphSCC:
527           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
528           break;
529         default:
530           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
531           break;
532         }
533       }
534     }
535
536     if (PrintEachXForm)
537       Passes.add(createPrintModulePass(&errs()));
538   }
539
540   // If -std-compile-opts was specified at the end of the pass list, add them.
541   if (StandardCompileOpts) {
542     AddStandardCompilePasses(Passes);
543     StandardCompileOpts = false;
544   }
545
546   if (StandardLinkOpts) {
547     AddStandardLinkPasses(Passes);
548     StandardLinkOpts = false;
549   }
550
551   if (OptLevelO1)
552     AddOptimizationPasses(Passes, *FPasses, 1);
553
554   if (OptLevelO2)
555     AddOptimizationPasses(Passes, *FPasses, 2);
556
557   if (OptLevelO3)
558     AddOptimizationPasses(Passes, *FPasses, 3);
559
560   if (OptLevelO1 || OptLevelO2 || OptLevelO3)
561     FPasses->run(*M.get());
562
563   // Check that the module is well formed on completion of optimization
564   if (!NoVerify && !VerifyEach)
565     Passes.add(createVerifierPass());
566
567   // Write bitcode or assembly to the output as the last step...
568   if (!NoOutput && !AnalyzeOnly) {
569     if (OutputAssembly)
570       Passes.add(createPrintModulePass(&Out->os()));
571     else
572       Passes.add(createBitcodeWriterPass(Out->os()));
573   }
574
575   // Now that we have all of the passes ready, run them.
576   Passes.run(*M.get());
577
578   // Declare success.
579   if (!NoOutput)
580     Out->keep();
581
582   return 0;
583 }