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