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