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