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