Add facility to create a target.
[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/Module.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/CallGraphSCCPass.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/CallGraph.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetMachineRegistry.h"
26 #include "llvm/Target/SubtargetFeature.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/Streams.h"
33 #include "llvm/Support/SystemUtils.h"
34 #include "llvm/LinkAllPasses.h"
35 #include "llvm/LinkAllVMCore.h"
36 #include <iostream>
37 #include <fstream>
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("Overwrite output files"));
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 StandardCompileOpts("std-compile-opts", 
87                    cl::desc("Include the standard compile time optimizations"));
88
89 static cl::opt<bool>
90 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
91
92 static cl::alias
93 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
94
95 static cl::opt<bool>
96 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
97
98 static cl::opt<const TargetMachineRegistry::entry*, false,
99                TargetMachineRegistry::Parser>
100 MArch("march", cl::desc("Architecture to generate code for:"));
101
102 static cl::opt<std::string>
103 MCPU("mcpu", 
104   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
105   cl::value_desc("cpu-name"),
106   cl::init(""));
107
108 static cl::list<std::string>
109 MAttrs("mattr", 
110   cl::CommaSeparated,
111   cl::desc("Target specific attributes (-mattr=help for details)"),
112   cl::value_desc("a1,+a2,-a3,..."));
113
114 // ---------- Define Printers for module and function passes ------------
115 namespace {
116
117 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
118   static char ID;
119   const PassInfo *PassToPrint;
120   CallGraphSCCPassPrinter(const PassInfo *PI) : 
121     CallGraphSCCPass((intptr_t)&ID), PassToPrint(PI) {}
122
123   virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) {
124     if (!Quiet) {
125       cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
126
127       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
128         Function *F = SCC[i]->getFunction();
129         if (F) 
130           getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent());
131       }
132     }
133     // Get and print pass...
134     return false;
135   }
136   
137   virtual const char *getPassName() const { return "'Pass' Printer"; }
138
139   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
140     AU.addRequiredID(PassToPrint);
141     AU.setPreservesAll();
142   }
143 };
144
145 char CallGraphSCCPassPrinter::ID = 0;
146
147 struct ModulePassPrinter : public ModulePass {
148   static char ID;
149   const PassInfo *PassToPrint;
150   ModulePassPrinter(const PassInfo *PI) : ModulePass((intptr_t)&ID),
151                                           PassToPrint(PI) {}
152
153   virtual bool runOnModule(Module &M) {
154     if (!Quiet) {
155       cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
156       getAnalysisID<Pass>(PassToPrint).print(cout, &M);
157     }
158
159     // Get and print pass...
160     return false;
161   }
162
163   virtual const char *getPassName() const { return "'Pass' Printer"; }
164
165   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166     AU.addRequiredID(PassToPrint);
167     AU.setPreservesAll();
168   }
169 };
170
171 char ModulePassPrinter::ID = 0;
172 struct FunctionPassPrinter : public FunctionPass {
173   const PassInfo *PassToPrint;
174   static char ID;
175   FunctionPassPrinter(const PassInfo *PI) : FunctionPass((intptr_t)&ID),
176                                             PassToPrint(PI) {}
177
178   virtual bool runOnFunction(Function &F) {
179     if (!Quiet) { 
180       cout << "Printing analysis '" << PassToPrint->getPassName()
181            << "' for function '" << F.getName() << "':\n";
182     }
183     // Get and print pass...
184     getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
185     return false;
186   }
187
188   virtual const char *getPassName() const { return "FunctionPass Printer"; }
189
190   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
191     AU.addRequiredID(PassToPrint);
192     AU.setPreservesAll();
193   }
194 };
195
196 char FunctionPassPrinter::ID = 0;
197
198 struct LoopPassPrinter : public LoopPass {
199   static char ID;
200   const PassInfo *PassToPrint;
201   LoopPassPrinter(const PassInfo *PI) : 
202     LoopPass((intptr_t)&ID), PassToPrint(PI) {}
203
204   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
205     if (!Quiet) {
206       cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
207       getAnalysisID<Pass>(PassToPrint).print(cout, 
208                                   L->getHeader()->getParent()->getParent());
209     }
210     // Get and print pass...
211     return false;
212   }
213   
214   virtual const char *getPassName() const { return "'Pass' Printer"; }
215
216   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
217     AU.addRequiredID(PassToPrint);
218     AU.setPreservesAll();
219   }
220 };
221
222 char LoopPassPrinter::ID = 0;
223
224 struct BasicBlockPassPrinter : public BasicBlockPass {
225   const PassInfo *PassToPrint;
226   static char ID;
227   BasicBlockPassPrinter(const PassInfo *PI) 
228     : BasicBlockPass((intptr_t)&ID), PassToPrint(PI) {}
229
230   virtual bool runOnBasicBlock(BasicBlock &BB) {
231     if (!Quiet) {
232       cout << "Printing Analysis info for BasicBlock '" << BB.getName()
233            << "': Pass " << PassToPrint->getPassName() << ":\n";
234     }
235
236     // Get and print pass...
237     getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
238     return false;
239   }
240
241   virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
242
243   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
244     AU.addRequiredID(PassToPrint);
245     AU.setPreservesAll();
246   }
247 };
248
249 char BasicBlockPassPrinter::ID = 0;
250 inline void addPass(PassManager &PM, Pass *P) {
251   // Add the pass to the pass manager...
252   PM.add(P);
253
254   // If we are verifying all of the intermediate steps, add the verifier...
255   if (VerifyEach) PM.add(createVerifierPass());
256 }
257
258 void AddStandardCompilePasses(PassManager &PM) {
259   PM.add(createVerifierPass());                  // Verify that input is correct
260
261   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
262
263   // If the -strip-debug command line option was specified, do it.
264   if (StripDebug)
265     addPass(PM, createStripSymbolsPass(true));
266
267   if (DisableOptimizations) return;
268
269   addPass(PM, createRaiseAllocationsPass());     // call %malloc -> malloc inst
270   addPass(PM, createCFGSimplificationPass());    // Clean up disgusting code
271   addPass(PM, createPromoteMemoryToRegisterPass());// Kill useless allocas
272   addPass(PM, createGlobalOptimizerPass());      // Optimize out global vars
273   addPass(PM, createGlobalDCEPass());            // Remove unused fns and globs
274   addPass(PM, createIPConstantPropagationPass());// IP Constant Propagation
275   addPass(PM, createDeadArgEliminationPass());   // Dead argument elimination
276   addPass(PM, createInstructionCombiningPass()); // Clean up after IPCP & DAE
277   addPass(PM, createCFGSimplificationPass());    // Clean up after IPCP & DAE
278
279   addPass(PM, createPruneEHPass());              // Remove dead EH info
280
281   if (!DisableInline)
282     addPass(PM, createFunctionInliningPass());   // Inline small functions
283   addPass(PM, createArgumentPromotionPass());    // Scalarize uninlined fn args
284
285   addPass(PM, createSimplifyLibCallsPass());     // Library Call Optimizations
286   addPass(PM, createInstructionCombiningPass()); // Cleanup for scalarrepl.
287   addPass(PM, createJumpThreadingPass());        // Thread jumps.
288   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
289   addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
290   addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
291   addPass(PM, createCondPropagationPass());      // Propagate conditionals
292
293   addPass(PM, createTailCallEliminationPass());  // Eliminate tail calls
294   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
295   addPass(PM, createReassociatePass());          // Reassociate expressions
296   addPass(PM, createLoopRotatePass());
297   addPass(PM, createLICMPass());                 // Hoist loop invariants
298   addPass(PM, createLoopUnswitchPass());         // Unswitch loops.
299   addPass(PM, createLoopIndexSplitPass());       // Index split loops.
300   // FIXME : Removing instcombine causes nestedloop regression.
301   addPass(PM, createInstructionCombiningPass()); 
302   addPass(PM, createIndVarSimplifyPass());       // Canonicalize indvars
303   addPass(PM, createLoopDeletionPass());         // Delete dead loops
304   addPass(PM, createLoopUnrollPass());           // Unroll small loops
305   addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
306   addPass(PM, createGVNPass());                  // Remove redundancies
307   addPass(PM, createMemCpyOptPass());            // Remove memcpy / form memset
308   addPass(PM, createSCCPPass());                 // Constant prop with SCCP
309
310   // Run instcombine after redundancy elimination to exploit opportunities
311   // opened up by them.
312   addPass(PM, createInstructionCombiningPass());
313   addPass(PM, createCondPropagationPass());      // Propagate conditionals
314
315   addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
316   addPass(PM, createAggressiveDCEPass());        // Delete dead instructions
317   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
318   addPass(PM, createStripDeadPrototypesPass());  // Get rid of dead prototypes
319   addPass(PM, createDeadTypeEliminationPass());  // Eliminate dead types
320   addPass(PM, createConstantMergePass());        // Merge dup global constants
321 }
322
323 } // anonymous namespace
324
325
326 //===----------------------------------------------------------------------===//
327 // main for opt
328 //
329
330 TargetMachine *getTargetMachine(Module &Mod) {
331
332   if (MArch == 0) {
333     std::string Err;
334     MArch = 
335       TargetMachineRegistry::getClosestStaticTargetForModule(Mod, Err);
336     if (MArch == 0) {
337       std::cerr << "Error auto-selecting target for module '"
338                 << Err << "'.  Please use the -march option to explicitly "
339                 << "pick a target.\n";
340       return NULL;
341     }
342   }
343   
344   // Package up features to be passed to target/subtarget
345   std::string FeaturesStr;
346   if (MCPU.size() || MAttrs.size()) {
347     SubtargetFeatures Features;
348     Features.setCPU(MCPU);
349     for (unsigned i = 0; i != MAttrs.size(); ++i)
350       Features.AddFeature(MAttrs[i]);
351     FeaturesStr = Features.getString();
352   }
353   
354   TargetMachine *Target = MArch->CtorFn(Mod, FeaturesStr);
355   assert(Target && "Could not allocate target machine!");
356   return Target;
357 }
358
359 int main(int argc, char **argv) {
360   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
361   try {
362     cl::ParseCommandLineOptions(argc, argv,
363       "llvm .bc -> .bc modular optimizer and analysis printer\n");
364     sys::PrintStackTraceOnErrorSignal();
365
366     std::string ErrorMessage;
367
368     // Load the input module...
369     std::auto_ptr<Module> M;
370     if (MemoryBuffer *Buffer
371           = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
372       M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
373       delete Buffer;
374     }
375     
376     if (M.get() == 0) {
377       cerr << argv[0] << ": ";
378       if (ErrorMessage.size())
379         cerr << ErrorMessage << "\n";
380       else
381         cerr << "bitcode didn't read correctly.\n";
382       return 1;
383     }
384
385     // Figure out what stream we are supposed to write to...
386     // FIXME: cout is not binary!
387     std::ostream *Out = &std::cout;  // Default to printing to stdout...
388     if (OutputFilename != "-") {
389       if (!Force && std::ifstream(OutputFilename.c_str())) {
390         // If force is not specified, make sure not to overwrite a file!
391         cerr << argv[0] << ": error opening '" << OutputFilename
392              << "': file exists!\n"
393              << "Use -f command line argument to force output\n";
394         return 1;
395       }
396       std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
397                                    std::ios::binary;
398       Out = new std::ofstream(OutputFilename.c_str(), io_mode);
399
400       if (!Out->good()) {
401         cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
402         return 1;
403       }
404
405       // Make sure that the Output file gets unlinked from the disk if we get a
406       // SIGINT
407       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
408     }
409
410     // If the output is set to be emitted to standard out, and standard out is a
411     // console, print out a warning message and refuse to do it.  We don't
412     // impress anyone by spewing tons of binary goo to a terminal.
413     if (!Force && !NoOutput && CheckBitcodeOutputToConsole(Out,!Quiet)) {
414       NoOutput = true;
415     }
416
417     // Create a PassManager to hold and optimize the collection of passes we are
418     // about to build...
419     //
420     PassManager Passes;
421
422     // Add an appropriate TargetData instance for this module...
423     Passes.add(new TargetData(M.get()));
424
425     // If the -strip-debug command line option was specified, add it.  If
426     // -std-compile-opts was also specified, it will handle StripDebug.
427     if (StripDebug && !StandardCompileOpts)
428       addPass(Passes, createStripSymbolsPass(true));
429
430     // Create a new optimization pass for each one specified on the command line
431     for (unsigned i = 0; i < PassList.size(); ++i) {
432       // Check to see if -std-compile-opts was specified before this option.  If
433       // so, handle it.
434       if (StandardCompileOpts && 
435           StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
436         AddStandardCompilePasses(Passes);
437         StandardCompileOpts = false;
438       }
439       
440       const PassInfo *PassInf = PassList[i];
441       Pass *P = 0;
442       if (PassInf->getNormalCtor())
443         P = PassInf->getNormalCtor()();
444       else
445         cerr << argv[0] << ": cannot create pass: "
446              << PassInf->getPassName() << "\n";
447       if (P) {
448         addPass(Passes, P);
449         
450         if (AnalyzeOnly) {
451           if (dynamic_cast<BasicBlockPass*>(P))
452             Passes.add(new BasicBlockPassPrinter(PassInf));
453           else if (dynamic_cast<LoopPass*>(P))
454             Passes.add(new  LoopPassPrinter(PassInf));
455           else if (dynamic_cast<FunctionPass*>(P))
456             Passes.add(new FunctionPassPrinter(PassInf));
457           else if (dynamic_cast<CallGraphSCCPass*>(P))
458             Passes.add(new CallGraphSCCPassPrinter(PassInf));
459           else
460             Passes.add(new ModulePassPrinter(PassInf));
461         }
462       }
463       
464       if (PrintEachXForm)
465         Passes.add(new PrintModulePass(&cerr));
466     }
467     
468     // If -std-compile-opts was specified at the end of the pass list, add them.
469     if (StandardCompileOpts) {
470       AddStandardCompilePasses(Passes);
471       StandardCompileOpts = false;
472     }    
473
474     // Check that the module is well formed on completion of optimization
475     if (!NoVerify && !VerifyEach)
476       Passes.add(createVerifierPass());
477
478     // Write bitcode out to disk or cout as the last step...
479     if (!NoOutput && !AnalyzeOnly)
480       Passes.add(CreateBitcodeWriterPass(*Out));
481
482     // Now that we have all of the passes ready, run them.
483     Passes.run(*M.get());
484
485     // Delete the ofstream.
486     if (Out != &std::cout) 
487       delete Out;
488     return 0;
489
490   } catch (const std::string& msg) {
491     cerr << argv[0] << ": " << msg << "\n";
492   } catch (...) {
493     cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
494   }
495   llvm_shutdown();
496   return 1;
497 }