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