1 //===----------------------------------------------------------------------===//
4 // Optimizations may be specified an arbitrary number of times on the command
5 // line, they are run in the order specified.
7 //===----------------------------------------------------------------------===//
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"
37 // FIXME: This should be parameterizable eventually for different target
39 static TargetData TD("opt target");
41 // Opts enum - All of the transformations we can do...
43 // Basic optimizations
44 dce, die, constprop, gcse, licm, inlining, constmerge,
45 strip, mstrip, mergereturn, simplifycfg,
47 // Miscellaneous Transformations
48 raiseallocs, lowerallocs, funcresolve, cleangcc, lowerrefs,
50 // Printing and verifying...
51 print, printm, verify,
53 // More powerful optimizations
54 indvars, instcombine, sccp, adce, raise, reassociate, mem2reg, pinodes,
57 trace, tracem, paths, emitfuncs,
59 // Interprocedural optimizations...
60 internalize, globaldce, swapstructs, sortstructs, poolalloc,
63 static Pass *createPrintFunctionPass() {
64 return new PrintFunctionPass("Current Function: \n", &cerr);
67 static Pass *createPrintModulePass() {
68 return new PrintModulePass(&cerr);
71 static Pass *createLowerAllocationsPassNT() {
72 return createLowerAllocationsPass(TD);
75 // OptTable - Correlate enum Opts to Pass constructors...
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 },
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 },
103 { trace , createTraceValuesPassForBasicBlocks },
104 { tracem , createTraceValuesPassForFunction },
105 { paths , createProfilePathsPass },
106 { emitfuncs , createEmitFunctionTablePass },
107 { print , createPrintFunctionPass },
108 { printm , createPrintModulePass },
109 { verify , createVerifierPass },
111 { raiseallocs, createRaiseAllocationsPass },
112 { lowerallocs, createLowerAllocationsPassNT },
113 { cleangcc , createCleanupGCCOutputPass },
114 { funcresolve, createFunctionResolvingPass },
116 { internalize, createInternalizePass },
117 { globaldce , createGlobalDCEPass },
118 { swapstructs, createSwapElementsPass },
119 { sortstructs, createSortElementsPass },
120 { poolalloc , createPoolAllocatePass },
124 // Command line option handling code...
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"),
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"),
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"),
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"),
176 int main(int argc, char **argv) {
177 cl::ParseCommandLineOptions(argc, argv,
178 " llvm .bc -> .bc modular optimizer\n");
180 // Load the input module...
181 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
183 cerr << "bytecode didn't read correctly.\n";
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";
196 Out = new std::ofstream(OutputFilename.c_str());
199 cerr << "Error opening " << OutputFilename << "!\n";
203 // Make sure that the Output file gets unlink'd from the disk if we get a
205 RemoveFileOnSignal(OutputFilename);
208 // Create a PassManager to hold and optimize the collection of passes we are
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());
223 Passes.add(new PrintModulePass(&std::cerr));
226 // Check that the module is well formed on completion of optimization
227 Passes.add(createVerifierPass());
229 // Write bytecode out to disk or cout as the last step...
230 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
232 // Now that we have all of the passes ready, run them.
233 if (Passes.run(*M.get()) && !Quiet)
234 cerr << "Program modified.\n";