Switch opt to using StandardPasses.h
[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/Module.h"
16 #include "llvm/ModuleProvider.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/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/PluginLoader.h"
31 #include "llvm/Support/StandardPasses.h"
32 #include "llvm/Support/Streams.h"
33 #include "llvm/Support/SystemUtils.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/LinkAllPasses.h"
36 #include "llvm/LinkAllVMCore.h"
37 #include <iostream>
38 #include <fstream>
39 #include <memory>
40 #include <algorithm>
41 using namespace llvm;
42
43 // The OptimizationList is automatically populated with registered Passes by the
44 // PassNameParser.
45 //
46 static cl::list<const PassInfo*, bool, PassNameParser>
47 PassList(cl::desc("Optimizations available:"));
48
49 // Other command line options...
50 //
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 
53     cl::init("-"), cl::value_desc("filename"));
54
55 static cl::opt<std::string>
56 OutputFilename("o", cl::desc("Override output filename"),
57                cl::value_desc("filename"), cl::init("-"));
58
59 static cl::opt<bool>
60 Force("f", cl::desc("Overwrite output files"));
61
62 static cl::opt<bool>
63 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64
65 static cl::opt<bool>
66 NoOutput("disable-output",
67          cl::desc("Do not write result bitcode file"), cl::Hidden);
68
69 static cl::opt<bool>
70 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
71
72 static cl::opt<bool>
73 VerifyEach("verify-each", cl::desc("Verify after each transform"));
74
75 static cl::opt<bool>
76 StripDebug("strip-debug",
77            cl::desc("Strip debugger symbol info from translation unit"));
78
79 static cl::opt<bool>
80 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
81
82 static cl::opt<bool> 
83 DisableOptimizations("disable-opt", 
84                      cl::desc("Do not run any optimization passes"));
85
86 static cl::opt<bool>
87 StandardCompileOpts("std-compile-opts", 
88                    cl::desc("Include the standard compile time optimizations"));
89
90 static cl::opt<bool>
91 OptLevelO1("O1",
92            cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
93
94 static cl::opt<bool>
95 OptLevelO2("O2",
96            cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
97
98 static cl::opt<bool>
99 OptLevelO3("O3",
100            cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
101
102 static cl::opt<bool>
103 UnitAtATime("funit-at-a-time",
104             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"));
105
106 static cl::opt<bool>
107 DisableSimplifyLibCalls("disable-simplify-libcalls",
108                         cl::desc("Disable simplify-libcalls"));
109
110 static cl::opt<bool>
111 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
112
113 static cl::alias
114 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
115
116 static cl::opt<bool>
117 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
118
119 // ---------- Define Printers for module and function passes ------------
120 namespace {
121
122 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
123   static char ID;
124   const PassInfo *PassToPrint;
125   CallGraphSCCPassPrinter(const PassInfo *PI) : 
126     CallGraphSCCPass(&ID), PassToPrint(PI) {}
127
128   virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) {
129     if (!Quiet) {
130       cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
131
132       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
133         Function *F = SCC[i]->getFunction();
134         if (F) 
135           getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent());
136       }
137     }
138     // Get and print pass...
139     return false;
140   }
141   
142   virtual const char *getPassName() const { return "'Pass' Printer"; }
143
144   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
145     AU.addRequiredID(PassToPrint);
146     AU.setPreservesAll();
147   }
148 };
149
150 char CallGraphSCCPassPrinter::ID = 0;
151
152 struct ModulePassPrinter : public ModulePass {
153   static char ID;
154   const PassInfo *PassToPrint;
155   ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
156                                           PassToPrint(PI) {}
157
158   virtual bool runOnModule(Module &M) {
159     if (!Quiet) {
160       cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
161       getAnalysisID<Pass>(PassToPrint).print(cout, &M);
162     }
163
164     // Get and print pass...
165     return false;
166   }
167
168   virtual const char *getPassName() const { return "'Pass' Printer"; }
169
170   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
171     AU.addRequiredID(PassToPrint);
172     AU.setPreservesAll();
173   }
174 };
175
176 char ModulePassPrinter::ID = 0;
177 struct FunctionPassPrinter : public FunctionPass {
178   const PassInfo *PassToPrint;
179   static char ID;
180   FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
181                                             PassToPrint(PI) {}
182
183   virtual bool runOnFunction(Function &F) {
184     if (!Quiet) { 
185       cout << "Printing analysis '" << PassToPrint->getPassName()
186            << "' for function '" << F.getName() << "':\n";
187     }
188     // Get and print pass...
189     getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
190     return false;
191   }
192
193   virtual const char *getPassName() const { return "FunctionPass Printer"; }
194
195   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
196     AU.addRequiredID(PassToPrint);
197     AU.setPreservesAll();
198   }
199 };
200
201 char FunctionPassPrinter::ID = 0;
202
203 struct LoopPassPrinter : public LoopPass {
204   static char ID;
205   const PassInfo *PassToPrint;
206   LoopPassPrinter(const PassInfo *PI) : 
207     LoopPass(&ID), PassToPrint(PI) {}
208
209   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
210     if (!Quiet) {
211       cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
212       getAnalysisID<Pass>(PassToPrint).print(cout, 
213                                   L->getHeader()->getParent()->getParent());
214     }
215     // Get and print pass...
216     return false;
217   }
218   
219   virtual const char *getPassName() const { return "'Pass' Printer"; }
220
221   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222     AU.addRequiredID(PassToPrint);
223     AU.setPreservesAll();
224   }
225 };
226
227 char LoopPassPrinter::ID = 0;
228
229 struct BasicBlockPassPrinter : public BasicBlockPass {
230   const PassInfo *PassToPrint;
231   static char ID;
232   BasicBlockPassPrinter(const PassInfo *PI) 
233     : BasicBlockPass(&ID), PassToPrint(PI) {}
234
235   virtual bool runOnBasicBlock(BasicBlock &BB) {
236     if (!Quiet) {
237       cout << "Printing Analysis info for BasicBlock '" << BB.getName()
238            << "': Pass " << PassToPrint->getPassName() << ":\n";
239     }
240
241     // Get and print pass...
242     getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
243     return false;
244   }
245
246   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
247
248   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
249     AU.addRequiredID(PassToPrint);
250     AU.setPreservesAll();
251   }
252 };
253
254 char BasicBlockPassPrinter::ID = 0;
255 inline void addPass(PassManager &PM, Pass *P) {
256   // Add the pass to the pass manager...
257   PM.add(P);
258
259   // If we are verifying all of the intermediate steps, add the verifier...
260   if (VerifyEach) PM.add(createVerifierPass());
261 }
262
263 /// AddOptimizationPasses - This routine adds optimization passes 
264 /// based on selected optimization level, OptLevel. This routine 
265 /// duplicates llvm-gcc behaviour.
266 ///
267 /// OptLevel - Optimization Level
268 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
269                            unsigned OptLevel) {
270   createStandardFunctionPasses(&FPM, OptLevel);
271
272   llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
273   createStandardModulePasses(&MPM, OptLevel,
274                              /*OptimizeSize=*/ false,
275                              UnitAtATime,
276                              /*UnrollLoops=*/ OptLevel > 1,
277                              !DisableSimplifyLibCalls,
278                              /*HaveExceptions=*/ true,
279                              InliningPass);
280 }
281
282 void AddStandardCompilePasses(PassManager &PM) {
283   PM.add(createVerifierPass());                  // Verify that input is correct
284
285   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
286
287   // If the -strip-debug command line option was specified, do it.
288   if (StripDebug)
289     addPass(PM, createStripSymbolsPass(true));
290
291   if (DisableOptimizations) return;
292
293   llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
294
295   // -std-compile-opts adds the same module passes as -O3.
296   createStandardModulePasses(&PM, 3, 
297                              /*OptimizeSize=*/ false,
298                              /*UnitAtATime=*/ true,
299                              /*UnrollLoops=*/ true,
300                              /*SimplifyLibCalls=*/ true,
301                              /*HaveExceptions=*/ true,
302                              InliningPass);
303 }
304
305 } // anonymous namespace
306
307
308 //===----------------------------------------------------------------------===//
309 // main for opt
310 //
311 int main(int argc, char **argv) {
312   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
313   try {
314     cl::ParseCommandLineOptions(argc, argv,
315       "llvm .bc -> .bc modular optimizer and analysis printer\n");
316     sys::PrintStackTraceOnErrorSignal();
317
318     // Allocate a full target machine description only if necessary.
319     // FIXME: The choice of target should be controllable on the command line.
320     std::auto_ptr<TargetMachine> target;
321
322     std::string ErrorMessage;
323
324     // Load the input module...
325     std::auto_ptr<Module> M;
326     if (MemoryBuffer *Buffer
327           = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
328       M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
329       delete Buffer;
330     }
331     
332     if (M.get() == 0) {
333       cerr << argv[0] << ": ";
334       if (ErrorMessage.size())
335         cerr << ErrorMessage << "\n";
336       else
337         cerr << "bitcode didn't read correctly.\n";
338       return 1;
339     }
340
341     // Figure out what stream we are supposed to write to...
342     // FIXME: cout is not binary!
343     std::ostream *Out = &std::cout;  // Default to printing to stdout...
344     if (OutputFilename != "-") {
345       if (!Force && std::ifstream(OutputFilename.c_str())) {
346         // If force is not specified, make sure not to overwrite a file!
347         cerr << argv[0] << ": error opening '" << OutputFilename
348              << "': file exists!\n"
349              << "Use -f command line argument to force output\n";
350         return 1;
351       }
352       std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
353                                    std::ios::binary;
354       Out = new std::ofstream(OutputFilename.c_str(), io_mode);
355
356       if (!Out->good()) {
357         cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
358         return 1;
359       }
360
361       // Make sure that the Output file gets unlinked from the disk if we get a
362       // SIGINT
363       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
364     }
365
366     // If the output is set to be emitted to standard out, and standard out is a
367     // console, print out a warning message and refuse to do it.  We don't
368     // impress anyone by spewing tons of binary goo to a terminal.
369     if (!Force && !NoOutput && CheckBitcodeOutputToConsole(Out,!Quiet)) {
370       NoOutput = true;
371     }
372
373     // Create a PassManager to hold and optimize the collection of passes we are
374     // about to build...
375     //
376     PassManager Passes;
377
378     // Add an appropriate TargetData instance for this module...
379     Passes.add(new TargetData(M.get()));
380
381     FunctionPassManager *FPasses = NULL;
382     if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
383       FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
384       FPasses->add(new TargetData(M.get()));
385     }
386       
387     // If the -strip-debug command line option was specified, add it.  If
388     // -std-compile-opts was also specified, it will handle StripDebug.
389     if (StripDebug && !StandardCompileOpts)
390       addPass(Passes, createStripSymbolsPass(true));
391
392     // Create a new optimization pass for each one specified on the command line
393     for (unsigned i = 0; i < PassList.size(); ++i) {
394       // Check to see if -std-compile-opts was specified before this option.  If
395       // so, handle it.
396       if (StandardCompileOpts && 
397           StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
398         AddStandardCompilePasses(Passes);
399         StandardCompileOpts = false;
400       }
401       
402       if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
403         AddOptimizationPasses(Passes, *FPasses, 1);
404         OptLevelO1 = false;
405       }
406
407       if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
408         AddOptimizationPasses(Passes, *FPasses, 2);
409         OptLevelO2 = false;
410       }
411
412       if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
413         AddOptimizationPasses(Passes, *FPasses, 3);
414         OptLevelO3 = false;
415       }
416
417       const PassInfo *PassInf = PassList[i];
418       Pass *P = 0;
419       if (PassInf->getNormalCtor())
420         P = PassInf->getNormalCtor()();
421       else
422         cerr << argv[0] << ": cannot create pass: "
423              << PassInf->getPassName() << "\n";
424       if (P) {
425         bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
426         bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
427         bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
428         bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
429
430         addPass(Passes, P);
431
432         if (AnalyzeOnly) {
433           if (isBBPass)
434             Passes.add(new BasicBlockPassPrinter(PassInf));
435           else if (isLPass)
436             Passes.add(new LoopPassPrinter(PassInf));
437           else if (isFPass)
438             Passes.add(new FunctionPassPrinter(PassInf));
439           else if (isCGSCCPass)
440             Passes.add(new CallGraphSCCPassPrinter(PassInf));
441           else
442             Passes.add(new ModulePassPrinter(PassInf));
443         }
444       }
445       
446       if (PrintEachXForm)
447         Passes.add(createPrintModulePass(&errs()));
448     }
449     
450     // If -std-compile-opts was specified at the end of the pass list, add them.
451     if (StandardCompileOpts) {
452       AddStandardCompilePasses(Passes);
453       StandardCompileOpts = false;
454     }    
455
456     if (OptLevelO1) {
457         AddOptimizationPasses(Passes, *FPasses, 1);
458       }
459
460     if (OptLevelO2) {
461         AddOptimizationPasses(Passes, *FPasses, 2);
462       }
463
464     if (OptLevelO3) {
465         AddOptimizationPasses(Passes, *FPasses, 3);
466       }
467
468     if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
469       for (Module::iterator I = M.get()->begin(), E = M.get()->end();
470            I != E; ++I)
471         FPasses->run(*I);
472     }
473
474     // Check that the module is well formed on completion of optimization
475     if (!NoVerify && !VerifyEach)
476       Passes.add(createVerifierPass());
477
478     // Write bitcode out to disk or cout as the last step...
479     if (!NoOutput && !AnalyzeOnly)
480       Passes.add(CreateBitcodeWriterPass(*Out));
481
482     // Now that we have all of the passes ready, run them.
483     Passes.run(*M.get());
484
485     // Delete the ofstream.
486     if (Out != &std::cout) 
487       delete Out;
488     return 0;
489
490   } catch (const std::string& msg) {
491     cerr << argv[0] << ": " << msg << "\n";
492   } catch (...) {
493     cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
494   }
495   llvm_shutdown();
496   return 1;
497 }