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