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