Changed llvm_ostream et all to OStream. llvm_cerr, llvm_cout, llvm_null, are
[oota-llvm.git] / tools / opt / opt.cpp
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/PassManager.h"
17 #include "llvm/Bytecode/Reader.h"
18 #include "llvm/Bytecode/WriteBytecodePass.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/PassNameParser.h"
24 #include "llvm/System/Signals.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/PluginLoader.h"
27 #include "llvm/Support/Streams.h"
28 #include "llvm/Support/SystemUtils.h"
29 #include "llvm/Support/Timer.h"
30 #include "llvm/LinkAllPasses.h"
31 #include "llvm/LinkAllVMCore.h"
32 #include <iostream>
33 #include <fstream>
34 #include <memory>
35 #include <algorithm>
36 using namespace llvm;
37
38 // The OptimizationList is automatically populated with registered Passes by the
39 // PassNameParser.
40 //
41 static cl::list<const PassInfo*, bool, PassNameParser>
42 PassList(cl::desc("Optimizations available:"));
43
44 static cl::opt<bool> NoCompress("disable-compression", cl::init(false),
45        cl::desc("Don't compress the generated bytecode"));
46
47 // Other command line options...
48 //
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bytecode 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 bytecode 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 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
72
73 static cl::alias
74 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
75
76 static cl::opt<bool>
77 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
78
79 static Timer BytecodeLoadTimer("Bytecode Loader");
80
81 // ---------- Define Printers for module and function passes ------------
82 namespace {
83
84 struct ModulePassPrinter : public ModulePass {
85   const PassInfo *PassToPrint;
86   ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
87
88   virtual bool runOnModule(Module &M) {
89     if (!Quiet) {
90       cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
91       getAnalysisID<Pass>(PassToPrint).print(cout, &M);
92     }
93
94     // Get and print pass...
95     return false;
96   }
97
98   virtual const char *getPassName() const { return "'Pass' Printer"; }
99
100   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
101     AU.addRequiredID(PassToPrint);
102     AU.setPreservesAll();
103   }
104 };
105
106 struct FunctionPassPrinter : public FunctionPass {
107   const PassInfo *PassToPrint;
108   FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
109
110   virtual bool runOnFunction(Function &F) {
111     if (!Quiet) {
112       cout << "Printing analysis '" << PassToPrint->getPassName()
113            << "' for function '" << F.getName() << "':\n";
114     }
115     // Get and print pass...
116     getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
117     return false;
118   }
119
120   virtual const char *getPassName() const { return "FunctionPass Printer"; }
121
122   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
123     AU.addRequiredID(PassToPrint);
124     AU.setPreservesAll();
125   }
126 };
127
128 struct BasicBlockPassPrinter : public BasicBlockPass {
129   const PassInfo *PassToPrint;
130   BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
131
132   virtual bool runOnBasicBlock(BasicBlock &BB) {
133     if (!Quiet) {
134       cout << "Printing Analysis info for BasicBlock '" << BB.getName()
135            << "': Pass " << PassToPrint->getPassName() << ":\n";
136     }
137
138     // Get and print pass...
139     getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
140     return false;
141   }
142
143   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
144
145   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146     AU.addRequiredID(PassToPrint);
147     AU.setPreservesAll();
148   }
149 };
150
151 } // anonymous namespace
152
153
154 //===----------------------------------------------------------------------===//
155 // main for opt
156 //
157 int main(int argc, char **argv) {
158   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
159   try {
160     cl::ParseCommandLineOptions(argc, argv,
161       " llvm .bc -> .bc modular optimizer and analysis printer \n");
162     sys::PrintStackTraceOnErrorSignal();
163
164     // Allocate a full target machine description only if necessary.
165     // FIXME: The choice of target should be controllable on the command line.
166     std::auto_ptr<TargetMachine> target;
167
168     std::string ErrorMessage;
169
170     // Load the input module...
171     std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
172     if (M.get() == 0) {
173       cerr << argv[0] << ": ";
174       if (ErrorMessage.size())
175         cerr << ErrorMessage << "\n";
176       else
177         cerr << "bytecode didn't read correctly.\n";
178       return 1;
179     }
180
181     // Figure out what stream we are supposed to write to...
182     // FIXME: cout is not binary!
183     std::ostream *Out = &std::cout;  // Default to printing to stdout...
184     if (OutputFilename != "-") {
185       if (!Force && std::ifstream(OutputFilename.c_str())) {
186         // If force is not specified, make sure not to overwrite a file!
187         cerr << argv[0] << ": error opening '" << OutputFilename
188              << "': file exists!\n"
189              << "Use -f command line argument to force output\n";
190         return 1;
191       }
192       std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
193                                    std::ios::binary;
194       Out = new std::ofstream(OutputFilename.c_str(), io_mode);
195
196       if (!Out->good()) {
197         cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
198         return 1;
199       }
200
201       // Make sure that the Output file gets unlinked from the disk if we get a
202       // SIGINT
203       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
204     }
205
206     // If the output is set to be emitted to standard out, and standard out is a
207     // console, print out a warning message and refuse to do it.  We don't
208     // impress anyone by spewing tons of binary goo to a terminal.
209     if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
210       NoOutput = true;
211     }
212
213     // Create a PassManager to hold and optimize the collection of passes we are
214     // about to build...
215     //
216     PassManager Passes;
217
218     // Add an appropriate TargetData instance for this module...
219     Passes.add(new TargetData(M.get()));
220
221     // Create a new optimization pass for each one specified on the command line
222     for (unsigned i = 0; i < PassList.size(); ++i) {
223       const PassInfo *PassInf = PassList[i];
224       Pass *P = 0;
225       if (PassInf->getNormalCtor())
226         P = PassInf->getNormalCtor()();
227       else
228         cerr << argv[0] << ": cannot create pass: "
229              << PassInf->getPassName() << "\n";
230       if (P) {
231         Passes.add(P);
232         
233         if (AnalyzeOnly) {
234           if (dynamic_cast<BasicBlockPass*>(P))
235             Passes.add(new BasicBlockPassPrinter(PassInf));
236           else if (dynamic_cast<FunctionPass*>(P))
237             Passes.add(new FunctionPassPrinter(PassInf));
238           else
239             Passes.add(new ModulePassPrinter(PassInf));
240         }
241       }
242       
243       if (PrintEachXForm)
244         Passes.add(new PrintModulePass(&cerr));
245     }
246
247     // Check that the module is well formed on completion of optimization
248     if (!NoVerify)
249       Passes.add(createVerifierPass());
250
251     // Write bytecode out to disk or cout as the last step...
252     OStream L(*Out);
253     if (!NoOutput && !AnalyzeOnly)
254       Passes.add(new WriteBytecodePass(&L, false, !NoCompress));
255
256     // Now that we have all of the passes ready, run them.
257     Passes.run(*M.get());
258
259     return 0;
260
261   } catch (const std::string& msg) {
262     cerr << argv[0] << ": " << msg << "\n";
263   } catch (...) {
264     cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
265   }
266   return 1;
267 }