For PR885:
[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/Assembly/Parser.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Bytecode/WriteBytecodePass.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/System/Signals.h"
26 #include "llvm/Support/PluginLoader.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 <fstream>
32 #include <memory>
33 #include <algorithm>
34
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,
41                 FilteredPassNameParser<PassInfo::Optimization> >
42 OptimizationList(cl::desc("Optimizations available:"));
43
44
45 // Other command line options...
46 //
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input bytecode file>"), 
49     cl::init("-"), cl::value_desc("filename"));
50
51 static cl::opt<std::string>
52 OutputFilename("o", cl::desc("Override output filename"),
53                cl::value_desc("filename"), cl::init("-"));
54
55 static cl::opt<bool>
56 Force("f", cl::desc("Overwrite output files"));
57
58 static cl::opt<bool>
59 PrintEachXForm("p", cl::desc("Print module after each transformation"));
60
61 static cl::opt<bool>
62 NoOutput("disable-output",
63          cl::desc("Do not write result bytecode file"), cl::Hidden);
64
65 static cl::opt<bool>
66 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
67
68 static cl::opt<bool>
69 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
70
71 static cl::alias
72 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
73
74 static cl::opt<bool>
75 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
76
77 // The AnalysesList is automatically populated with registered Passes by the
78 // PassNameParser.
79 static 
80   cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::Analysis> >
81   AnalysesList(cl::desc("Analyses available:"));
82
83 static Timer BytecodeLoadTimer("Bytecode Loader");
84
85 // ---------- Define Printers for module and function passes ------------
86 namespace {
87
88 struct ModulePassPrinter : public ModulePass {
89   const PassInfo *PassToPrint;
90   ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
91
92   virtual bool runOnModule(Module &M) {
93     if (!Quiet) {
94       std::cout << "Printing analysis '" << PassToPrint->getPassName() 
95                 << "':\n";
96       getAnalysisID<Pass>(PassToPrint).print(std::cout, &M);
97     }
98
99     // Get and print pass...
100     return false;
101   }
102
103   virtual const char *getPassName() const { return "'Pass' Printer"; }
104
105   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106     AU.addRequiredID(PassToPrint);
107     AU.setPreservesAll();
108   }
109 };
110
111 struct FunctionPassPrinter : public FunctionPass {
112   const PassInfo *PassToPrint;
113   FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
114
115   virtual bool runOnFunction(Function &F) {
116     if (!Quiet) {
117       std::cout << "Printing analysis '" << PassToPrint->getPassName()
118                 << "' for function '" << F.getName() << "':\n";
119     }
120     // Get and print pass...
121     getAnalysisID<Pass>(PassToPrint).print(std::cout, F.getParent());
122     return false;
123   }
124
125   virtual const char *getPassName() const { return "FunctionPass Printer"; }
126
127   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
128     AU.addRequiredID(PassToPrint);
129     AU.setPreservesAll();
130   }
131 };
132
133 struct BasicBlockPassPrinter : public BasicBlockPass {
134   const PassInfo *PassToPrint;
135   BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
136
137   virtual bool runOnBasicBlock(BasicBlock &BB) {
138     if (!Quiet) {
139       std::cout << "Printing Analysis info for BasicBlock '" << BB.getName()
140                 << "': Pass " << PassToPrint->getPassName() << ":\n";
141     }
142
143     // Get and print pass...
144     getAnalysisID<Pass>(PassToPrint).print(
145       std::cout, BB.getParent()->getParent());
146     return false;
147   }
148
149   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
150
151   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152     AU.addRequiredID(PassToPrint);
153     AU.setPreservesAll();
154   }
155 };
156
157 } // anonymous namespace
158
159
160 //===----------------------------------------------------------------------===//
161 // main for opt
162 //
163 int main(int argc, char **argv) {
164   try {
165     cl::ParseCommandLineOptions(argc, argv,
166       " llvm .bc -> .bc modular optimizer and analysis printer \n");
167     sys::PrintStackTraceOnErrorSignal();
168
169     if (AnalyzeOnly) {
170       Module *CurMod = 0;
171 #if 0
172       TimeRegion RegionTimer(BytecodeLoadTimer);
173 #endif
174       CurMod = ParseBytecodeFile(InputFilename);
175       ParseError Err;
176       if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename,&Err))){
177         std::cerr << argv[0] << ": " << Err.getMessage() << "\n"; 
178         return 1;
179       }
180
181       // Create a PassManager to hold and optimize the collection of passes we 
182       // are about to build...
183       PassManager Passes;
184
185       // Add an appropriate TargetData instance for this module...
186       Passes.add(new TargetData(CurMod));
187
188       // Make sure the input LLVM is well formed.
189       if (!NoVerify)
190         Passes.add(createVerifierPass());
191
192       // Create a new optimization pass for each one specified on the 
193       // command line
194       for (unsigned i = 0; i < AnalysesList.size(); ++i) {
195         const PassInfo *Analysis = AnalysesList[i];
196
197         if (Analysis->getNormalCtor()) {
198           Pass *P = Analysis->getNormalCtor()();
199           Passes.add(P);
200
201           if (BasicBlockPass *BBP = dynamic_cast<BasicBlockPass*>(P))
202             Passes.add(new BasicBlockPassPrinter(Analysis));
203           else if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P))
204             Passes.add(new FunctionPassPrinter(Analysis));
205           else
206             Passes.add(new ModulePassPrinter(Analysis));
207
208         } else
209           std::cerr << argv[0] << ": cannot create pass: "
210                     << Analysis->getPassName() << "\n";
211       }
212
213       Passes.run(*CurMod);
214
215       delete CurMod;
216       return 0;
217     }
218
219     // Allocate a full target machine description only if necessary...
220     // FIXME: The choice of target should be controllable on the command line.
221     std::auto_ptr<TargetMachine> target;
222
223     TargetMachine* TM = NULL;
224     std::string ErrorMessage;
225
226     // Load the input module...
227     std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
228     if (M.get() == 0) {
229       std::cerr << argv[0] << ": ";
230       if (ErrorMessage.size())
231         std::cerr << ErrorMessage << "\n";
232       else
233         std::cerr << "bytecode didn't read correctly.\n";
234       return 1;
235     }
236
237     // Figure out what stream we are supposed to write to...
238     // FIXME: cout is not binary!
239     std::ostream *Out = &std::cout;  // Default to printing to stdout...
240     if (OutputFilename != "-") {
241       if (!Force && std::ifstream(OutputFilename.c_str())) {
242         // If force is not specified, make sure not to overwrite a file!
243         std::cerr << argv[0] << ": error opening '" << OutputFilename
244                   << "': file exists!\n"
245                   << "Use -f command line argument to force output\n";
246         return 1;
247       }
248       std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
249                                    std::ios::binary;
250       Out = new std::ofstream(OutputFilename.c_str(), io_mode);
251
252       if (!Out->good()) {
253         std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
254         return 1;
255       }
256
257       // Make sure that the Output file gets unlinked from the disk if we get a
258       // SIGINT
259       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
260     }
261
262     // If the output is set to be emitted to standard out, and standard out is a
263     // console, print out a warning message and refuse to do it.  We don't
264     // impress anyone by spewing tons of binary goo to a terminal.
265     if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
266       NoOutput = true;
267     }
268
269     // Create a PassManager to hold and optimize the collection of passes we are
270     // about to build...
271     //
272     PassManager Passes;
273
274     // Add an appropriate TargetData instance for this module...
275     Passes.add(new TargetData(M.get()));
276
277     // Create a new optimization pass for each one specified on the command line
278     for (unsigned i = 0; i < OptimizationList.size(); ++i) {
279       const PassInfo *Opt = OptimizationList[i];
280
281       if (Opt->getNormalCtor())
282         Passes.add(Opt->getNormalCtor()());
283       else if (Opt->getTargetCtor()) {
284 #if 0
285         if (target.get() == NULL)
286           target.reset(allocateSparcTargetMachine()); // FIXME: target option
287 #endif
288         assert(target.get() && "Could not allocate target machine!");
289         Passes.add(Opt->getTargetCtor()(*target.get()));
290       } else
291         std::cerr << argv[0] << ": cannot create pass: " << Opt->getPassName()
292                   << "\n";
293
294       if (PrintEachXForm)
295         Passes.add(new PrintModulePass(&std::cerr));
296     }
297
298     // Check that the module is well formed on completion of optimization
299     if (!NoVerify)
300       Passes.add(createVerifierPass());
301
302     // Write bytecode out to disk or cout as the last step...
303     if (!NoOutput)
304       Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
305
306     // Now that we have all of the passes ready, run them.
307     Passes.run(*M.get());
308
309     return 0;
310
311   } catch (const std::string& msg) {
312     std::cerr << argv[0] << ": " << msg << "\n";
313   } catch (...) {
314     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
315   }
316   return 1;
317 }