*** empty log message ***
[oota-llvm.git] / tools / opt / opt.cpp
1 //===----------------------------------------------------------------------===//
2 // LLVM 'OPT' UTILITY 
3 //
4 // Optimizations may be specified an arbitrary number of times on the command
5 // line, they are run in the order specified.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Module.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/Bytecode/Reader.h"
12 #include "llvm/Bytecode/WriteBytecodePass.h"
13 #include "llvm/Assembly/PrintModulePass.h"
14 #include "llvm/Analysis/Verifier.h"
15 #include "llvm/Transforms/ConstantMerge.h"
16 #include "llvm/Transforms/CleanupGCCOutput.h"
17 #include "llvm/Transforms/LevelChange.h"
18 #include "llvm/Transforms/FunctionInlining.h"
19 #include "llvm/Transforms/ChangeAllocations.h"
20 #include "llvm/Transforms/Scalar.h"
21 #include "llvm/Transforms/IPO/SimpleStructMutation.h"
22 #include "llvm/Transforms/IPO/Internalize.h"
23 #include "llvm/Transforms/IPO/GlobalDCE.h"
24 #include "llvm/Transforms/IPO/PoolAllocate.h"
25 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
26 #include "llvm/Transforms/Instrumentation/TraceValues.h"
27 #include "llvm/Transforms/Instrumentation/ProfilePaths.h"
28 #include "llvm/Transforms/Instrumentation/EmitFunctions.h"
29 #include "llvm/Target/TargetData.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Signals.h"
32 #include <fstream>
33 #include <memory>
34
35 using std::cerr;
36
37 // FIXME: This should be parameterizable eventually for different target
38 // types...
39 static TargetData TD("opt target");
40
41 // Opts enum - All of the transformations we can do...
42 enum Opts {
43   // Basic optimizations
44   dce, die, constprop, gcse, licm, inlining, constmerge,
45   strip, mstrip, mergereturn, simplifycfg,
46
47   // Miscellaneous Transformations
48   raiseallocs, lowerallocs, funcresolve, cleangcc, lowerrefs,
49
50   // Printing and verifying...
51   print, printm, verify,
52
53   // More powerful optimizations
54   indvars, instcombine, sccp, adce, raise, reassociate, mem2reg, pinodes,
55
56   // Instrumentation
57   trace, tracem, paths, emitfuncs,
58
59   // Interprocedural optimizations...
60   internalize, globaldce, swapstructs, sortstructs, poolalloc,
61 };
62
63 static Pass *createPrintFunctionPass() {
64   return new PrintFunctionPass("Current Function: \n", &cerr);
65 }
66
67 static Pass *createPrintModulePass() {
68   return new PrintModulePass(&cerr);
69 }
70
71 static Pass *createLowerAllocationsPassNT() {
72   return createLowerAllocationsPass(TD);
73 }
74
75 // OptTable - Correlate enum Opts to Pass constructors...
76 //
77 struct {
78   enum Opts OptID;
79   Pass * (*PassCtor)();
80 } OptTable[] = {
81   { dce        , createDeadCodeEliminationPass    },
82   { die        , createDeadInstEliminationPass    },
83   { constprop  , createConstantPropogationPass    }, 
84   { gcse       , createGCSEPass                   },
85   { licm       , createLICMPass                   },
86   { inlining   , createFunctionInliningPass       },
87   { constmerge , createConstantMergePass          },
88   { strip      , createSymbolStrippingPass        },
89   { mstrip     , createFullSymbolStrippingPass    },
90   { mergereturn, createUnifyFunctionExitNodesPass },
91   { simplifycfg, createCFGSimplificationPass      },
92
93   { indvars    , createIndVarSimplifyPass         },
94   { instcombine, createInstructionCombiningPass   },
95   { sccp       , createSCCPPass                   },
96   { adce       , createAggressiveDCEPass          },
97   { raise      , createRaisePointerReferencesPass },
98   /* { reassociate, createReassociatePass            },*/
99   { mem2reg    , createPromoteMemoryToRegister    },
100   { pinodes    , createPiNodeInsertionPass        },
101   { lowerrefs  , createDecomposeMultiDimRefsPass  },
102
103   { trace      , createTraceValuesPassForBasicBlocks },
104   { tracem     , createTraceValuesPassForFunction    },
105   { paths      , createProfilePathsPass              },
106   { emitfuncs  , createEmitFunctionTablePass },
107   { print      , createPrintFunctionPass },
108   { printm     , createPrintModulePass   },
109   { verify     , createVerifierPass      },
110
111   { raiseallocs, createRaiseAllocationsPass   },
112   { lowerallocs, createLowerAllocationsPassNT },
113   { cleangcc   , createCleanupGCCOutputPass   },
114   { funcresolve, createFunctionResolvingPass  },
115
116   { internalize, createInternalizePass  },
117   { globaldce  , createGlobalDCEPass    },
118   { swapstructs, createSwapElementsPass },
119   { sortstructs, createSortElementsPass },
120   { poolalloc  , createPoolAllocatePass },
121 };
122
123
124 // Command line option handling code...
125 //
126 static cl::opt<string>
127 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
128
129 static cl::opt<string>
130 OutputFilename("o", cl::desc("Override output filename"),
131                cl::value_desc("filename"));
132
133 static cl::opt<bool>
134 Force("f", cl::desc("Overwrite output files"));
135
136 static cl::opt<bool>
137 PrintEachXForm("p", cl::desc("Print module after each transformation"));
138
139 static cl::opt<bool>
140 Quiet("q", cl::desc("Don't print modifying pass names"));
141
142 static cl::alias
143 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
144
145 static cl::list<enum Opts>
146 OptimizationList(cl::desc("Optimizations available:"), cl::values(
147   clEnumVal(dce        , "Dead Code Elimination"),
148   clEnumVal(die        , "Dead Instruction Elimination"),
149   clEnumVal(constprop  , "Simple constant propogation"),
150   clEnumVal(gcse       , "Global Common Subexpression Elimination"),
151   clEnumVal(licm       , "Loop Invariant Code Motion"),
152  clEnumValN(inlining   , "inline", "Function integration"),
153   clEnumVal(constmerge , "Merge identical global constants"),
154   clEnumVal(strip      , "Strip symbols"),
155   clEnumVal(mstrip     , "Strip module symbols"),
156   clEnumVal(mergereturn, "Unify function exit nodes"),
157   clEnumVal(simplifycfg, "CFG Simplification"),
158
159   clEnumVal(indvars    , "Simplify Induction Variables"),
160   clEnumVal(instcombine, "Combine redundant instructions"),
161   clEnumVal(sccp       , "Sparse Conditional Constant Propogation"),
162   clEnumVal(adce       , "Aggressive DCE"),
163   clEnumVal(reassociate, "Reassociate expressions"),
164   clEnumVal(mem2reg    , "Promote alloca locations to registers"),
165   clEnumVal(pinodes    , "Insert Pi nodes after definitions"),
166
167   clEnumVal(internalize, "Mark all fn's internal except for main"),
168   clEnumVal(globaldce  , "Remove unreachable globals"),
169   clEnumVal(swapstructs, "Swap structure types around"),
170   clEnumVal(sortstructs, "Sort structure elements"),
171   clEnumVal(poolalloc  , "Pool allocate disjoint datastructures"),
172
173   clEnumVal(raiseallocs, "Raise allocations from calls to instructions"),
174   clEnumVal(lowerallocs, "Lower allocations from instructions to calls (TD)"),
175   clEnumVal(cleangcc   , "Cleanup GCC Output"),
176   clEnumVal(funcresolve, "Resolve calls to foo(...) to foo(<concrete types>)"),
177   clEnumVal(raise      , "Raise to Higher Level"),
178   clEnumVal(trace      , "Insert BB and Function trace code"),
179   clEnumVal(tracem     , "Insert Function trace code only"),
180   clEnumVal(paths      , "Insert path profiling instrumentation"),
181   clEnumVal(emitfuncs  , "Insert function pointer table"),
182   clEnumVal(print      , "Print working function to stderr"),
183   clEnumVal(printm     , "Print working module to stderr"),
184   clEnumVal(verify     , "Verify module is well formed"),
185   clEnumVal(lowerrefs  , "Decompose multi-dimensional structure/array refs to use one index per instruction"),
186 0));
187
188
189
190 int main(int argc, char **argv) {
191   cl::ParseCommandLineOptions(argc, argv,
192                               " llvm .bc -> .bc modular optimizer\n");
193
194   // Load the input module...
195   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
196   if (M.get() == 0) {
197     cerr << "bytecode didn't read correctly.\n";
198     return 1;
199   }
200
201   // Figure out what stream we are supposed to write to...
202   std::ostream *Out = &std::cout;  // Default to printing to stdout...
203   if (OutputFilename != "") {
204     if (!Force && std::ifstream(OutputFilename.c_str())) {
205       // If force is not specified, make sure not to overwrite a file!
206       cerr << "Error opening '" << OutputFilename << "': File exists!\n"
207            << "Use -f command line argument to force output\n";
208       return 1;
209     }
210     Out = new std::ofstream(OutputFilename.c_str());
211
212     if (!Out->good()) {
213       cerr << "Error opening " << OutputFilename << "!\n";
214       return 1;
215     }
216
217     // Make sure that the Output file gets unlink'd from the disk if we get a
218     // SIGINT
219     RemoveFileOnSignal(OutputFilename);
220   }
221
222   // Create a PassManager to hold and optimize the collection of passes we are
223   // about to build...
224   //
225   PassManager Passes;
226
227   // Create a new optimization pass for each one specified on the command line
228   for (unsigned i = 0; i < OptimizationList.size(); ++i) {
229     enum Opts Opt = OptimizationList[i];
230     for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j)
231       if (Opt == OptTable[j].OptID) {
232         Passes.add(OptTable[j].PassCtor());
233         break;
234       }
235
236     if (PrintEachXForm)
237       Passes.add(new PrintModulePass(&std::cerr));
238   }
239
240   // Check that the module is well formed on completion of optimization
241   Passes.add(createVerifierPass());
242
243   // Write bytecode out to disk or cout as the last step...
244   Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
245
246   // Now that we have all of the passes ready, run them.
247   if (Passes.run(*M.get()) && !Quiet)
248     cerr << "Program modified.\n";
249
250   return 0;
251 }