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