added emitfuncs pass, and disabled reassociate pass (needs fixing)
[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 cl::String InputFilename ("", "Load <arg> file to optimize", cl::NoFlags, "-");
127 cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
128 cl::Flag   Force         ("f", "Overwrite output files", cl::NoFlags, false);
129 cl::Flag   PrintEachXForm("p", "Print module after each transformation");
130 cl::Flag   Quiet         ("q", "Don't print modifying pass names", 0, false);
131 cl::Alias  QuietA        ("quiet", "Alias for -q", cl::NoFlags, Quiet);
132 cl::EnumList<enum Opts> OptimizationList(cl::NoFlags,
133   clEnumVal(dce        , "Dead Code Elimination"),
134   clEnumVal(die        , "Dead Instruction Elimination"),
135   clEnumVal(constprop  , "Simple constant propogation"),
136   clEnumVal(gcse       , "Global Common Subexpression Elimination"),
137   clEnumVal(licm       , "Loop Invariant Code Motion"),
138  clEnumValN(inlining   , "inline", "Function integration"),
139   clEnumVal(constmerge , "Merge identical global constants"),
140   clEnumVal(strip      , "Strip symbols"),
141   clEnumVal(mstrip     , "Strip module symbols"),
142   clEnumVal(mergereturn, "Unify function exit nodes"),
143   clEnumVal(simplifycfg, "CFG Simplification"),
144
145   clEnumVal(indvars    , "Simplify Induction Variables"),
146   clEnumVal(instcombine, "Combine redundant instructions"),
147   clEnumVal(sccp       , "Sparse Conditional Constant Propogation"),
148   clEnumVal(adce       , "Aggressive DCE"),
149   clEnumVal(reassociate, "Reassociate expressions"),
150   clEnumVal(mem2reg    , "Promote alloca locations to registers"),
151   clEnumVal(pinodes    , "Insert Pi nodes after definitions"),
152
153   clEnumVal(internalize, "Mark all fn's internal except for main"),
154   clEnumVal(globaldce  , "Remove unreachable globals"),
155   clEnumVal(swapstructs, "Swap structure types around"),
156   clEnumVal(sortstructs, "Sort structure elements"),
157   clEnumVal(poolalloc  , "Pool allocate disjoint datastructures"),
158
159   clEnumVal(raiseallocs, "Raise allocations from calls to instructions"),
160   clEnumVal(lowerallocs, "Lower allocations from instructions to calls (TD)"),
161   clEnumVal(cleangcc   , "Cleanup GCC Output"),
162   clEnumVal(funcresolve, "Resolve calls to foo(...) to foo(<concrete types>)"),
163   clEnumVal(raise      , "Raise to Higher Level"),
164   clEnumVal(trace      , "Insert BB and Function trace code"),
165   clEnumVal(tracem     , "Insert Function trace code only"),
166   clEnumVal(paths      , "Insert path profiling instrumentation"),
167   clEnumVal(emitfuncs  , "Insert function pointer table"),
168   clEnumVal(print      , "Print working function to stderr"),
169   clEnumVal(printm     , "Print working module to stderr"),
170   clEnumVal(verify     , "Verify module is well formed"),
171   clEnumVal(lowerrefs  , "Decompose multi-dimensional structure/array refs to use one index per instruction"),
172 0);
173
174
175
176 int main(int argc, char **argv) {
177   cl::ParseCommandLineOptions(argc, argv,
178                               " llvm .bc -> .bc modular optimizer\n");
179
180   // Load the input module...
181   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
182   if (M.get() == 0) {
183     cerr << "bytecode didn't read correctly.\n";
184     return 1;
185   }
186
187   // Figure out what stream we are supposed to write to...
188   std::ostream *Out = &std::cout;  // Default to printing to stdout...
189   if (OutputFilename != "") {
190     if (!Force && std::ifstream(OutputFilename.c_str())) {
191       // If force is not specified, make sure not to overwrite a file!
192       cerr << "Error opening '" << OutputFilename << "': File exists!\n"
193            << "Use -f command line argument to force output\n";
194       return 1;
195     }
196     Out = new std::ofstream(OutputFilename.c_str());
197
198     if (!Out->good()) {
199       cerr << "Error opening " << OutputFilename << "!\n";
200       return 1;
201     }
202
203     // Make sure that the Output file gets unlink'd from the disk if we get a
204     // SIGINT
205     RemoveFileOnSignal(OutputFilename);
206   }
207
208   // Create a PassManager to hold and optimize the collection of passes we are
209   // about to build...
210   //
211   PassManager Passes;
212
213   // Create a new optimization pass for each one specified on the command line
214   for (unsigned i = 0; i < OptimizationList.size(); ++i) {
215     enum Opts Opt = OptimizationList[i];
216     for (unsigned j = 0; j < sizeof(OptTable)/sizeof(OptTable[0]); ++j)
217       if (Opt == OptTable[j].OptID) {
218         Passes.add(OptTable[j].PassCtor());
219         break;
220       }
221
222     if (PrintEachXForm)
223       Passes.add(new PrintModulePass(&std::cerr));
224   }
225
226   // Check that the module is well formed on completion of optimization
227   Passes.add(createVerifierPass());
228
229   // Write bytecode out to disk or cout as the last step...
230   Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
231
232   // Now that we have all of the passes ready, run them.
233   if (Passes.run(*M.get()) && !Quiet)
234     cerr << "Program modified.\n";
235
236   return 0;
237 }