Fix opt -o option. Don't pass a pointer to an auto variable which is going
[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/PluginLoader.h"
26 #include "llvm/Support/Streams.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/LinkAllPasses.h"
30 #include "llvm/LinkAllVMCore.h"
31 #include <iostream>
32 #include <fstream>
33 #include <memory>
34 #include <algorithm>
35 using namespace llvm;
36
37 // The OptimizationList is automatically populated with registered Passes by the
38 // PassNameParser.
39 //
40 static cl::list<const PassInfo*, bool, PassNameParser>
41 PassList(cl::desc("Optimizations available:"));
42
43 static cl::opt<bool> NoCompress("disable-compression", cl::init(false),
44        cl::desc("Don't compress the generated bytecode"));
45
46 // Other command line options...
47 //
48 static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input bytecode file>"), 
50     cl::init("-"), cl::value_desc("filename"));
51
52 static cl::opt<std::string>
53 OutputFilename("o", cl::desc("Override output filename"),
54                cl::value_desc("filename"), cl::init("-"));
55
56 static cl::opt<bool>
57 Force("f", cl::desc("Overwrite output files"));
58
59 static cl::opt<bool>
60 PrintEachXForm("p", cl::desc("Print module after each transformation"));
61
62 static cl::opt<bool>
63 NoOutput("disable-output",
64          cl::desc("Do not write result bytecode file"), cl::Hidden);
65
66 static cl::opt<bool>
67 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
68
69 static cl::opt<bool>
70 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
71
72 static cl::alias
73 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
74
75 static cl::opt<bool>
76 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
77
78 static Timer BytecodeLoadTimer("Bytecode Loader");
79
80 // ---------- Define Printers for module and function passes ------------
81 namespace {
82
83 struct ModulePassPrinter : public ModulePass {
84   const PassInfo *PassToPrint;
85   ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
86
87   virtual bool runOnModule(Module &M) {
88     if (!Quiet) {
89       llvm_cout << "Printing analysis '" << PassToPrint->getPassName() 
90                 << "':\n";
91       getAnalysisID<Pass>(PassToPrint).print(llvm_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       llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
113                 << "' for function '" << F.getName() << "':\n";
114     }
115     // Get and print pass...
116     getAnalysisID<Pass>(PassToPrint).print(llvm_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       llvm_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(
140       llvm_cout, BB.getParent()->getParent());
141     return false;
142   }
143
144   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
145
146   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
147     AU.addRequiredID(PassToPrint);
148     AU.setPreservesAll();
149   }
150 };
151
152 } // anonymous namespace
153
154
155 //===----------------------------------------------------------------------===//
156 // main for opt
157 //
158 int main(int argc, char **argv) {
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       llvm_cerr << argv[0] << ": ";
174       if (ErrorMessage.size())
175         llvm_cerr << ErrorMessage << "\n";
176       else
177         llvm_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         llvm_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         llvm_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 if (PassInf->getTargetCtor()) {
228         assert(target.get() && "Could not allocate target machine!");
229         P = PassInf->getTargetCtor()(*target.get());
230       } else
231         llvm_cerr << argv[0] << ": cannot create pass: "
232                   << PassInf->getPassName() << "\n";
233       if (P) {
234         Passes.add(P);
235         
236         if (AnalyzeOnly) {
237           if (dynamic_cast<BasicBlockPass*>(P))
238             Passes.add(new BasicBlockPassPrinter(PassInf));
239           else if (dynamic_cast<FunctionPass*>(P))
240             Passes.add(new FunctionPassPrinter(PassInf));
241           else
242             Passes.add(new ModulePassPrinter(PassInf));
243         }
244       }
245       
246       if (PrintEachXForm)
247         Passes.add(new PrintModulePass(&llvm_cerr));
248     }
249
250     // Check that the module is well formed on completion of optimization
251     if (!NoVerify)
252       Passes.add(createVerifierPass());
253
254     // Write bytecode out to disk or cout as the last step...
255     llvm_ostream L(*Out);
256     if (!NoOutput && !AnalyzeOnly)
257       Passes.add(new WriteBytecodePass(&L, false, !NoCompress));
258
259     // Now that we have all of the passes ready, run them.
260     Passes.run(*M.get());
261
262     return 0;
263
264   } catch (const std::string& msg) {
265     llvm_cerr << argv[0] << ": " << msg << "\n";
266   } catch (...) {
267     llvm_cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
268   }
269   return 1;
270 }