Function.h is unnecessary when Module.h is included.
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
2 //
3 // This is the llc compiler driver.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Bytecode/Reader.h"
8 #include "llvm/Target/Sparc.h"
9 #include "llvm/Target/TargetMachine.h"
10 #include "llvm/Transforms/Instrumentation/TraceValues.h"
11 #include "llvm/Transforms/Scalar.h"
12 #include "llvm/Transforms/Utils/Linker.h"
13 #include "llvm/Assembly/PrintModulePass.h"
14 #include "llvm/Bytecode/WriteBytecodePass.h"
15 #include "llvm/Transforms/IPO.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "Support/CommandLine.h"
19 #include "Support/Signals.h"
20 #include <memory>
21 #include <fstream>
22 using std::string;
23 using std::cerr;
24
25 static cl::opt<string>
26 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
27
28 static cl::opt<string>
29 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
30
31 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
32
33 static cl::opt<bool>
34 DumpAsm("d", cl::desc("Print bytecode before native code generation"),
35         cl::Hidden);
36
37 static cl::opt<string>
38 TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"),
39              cl::value_desc("directory"), cl::Hidden);
40
41 enum TraceLevel {
42   TraceOff, TraceFunctions, TraceBasicBlocks
43 };
44
45 static cl::opt<TraceLevel>
46 TraceValues("trace", cl::desc("Trace values through functions or basic blocks"),
47             cl::values(
48   clEnumValN(TraceOff        , "off",        "Disable trace code"),
49   clEnumValN(TraceFunctions  , "function",   "Trace each function"),
50   clEnumValN(TraceBasicBlocks, "basicblock", "Trace each basic block"),
51                        0));
52
53 // GetFileNameRoot - Helper function to get the basename of a filename...
54 static inline string GetFileNameRoot(const string &InputFilename) {
55   string IFN = InputFilename;
56   string outputFilename;
57   int Len = IFN.length();
58   if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
59     outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
60   } else {
61     outputFilename = IFN;
62   }
63   return outputFilename;
64 }
65
66 static void insertTraceCodeFor(Module &M) {
67   PassManager Passes;
68
69   // Insert trace code in all functions in the module
70   switch (TraceValues) {
71   case TraceBasicBlocks:
72     Passes.add(createTraceValuesPassForBasicBlocks());
73     break;
74   case TraceFunctions:
75     Passes.add(createTraceValuesPassForFunction());
76     break;
77   default:
78     assert(0 && "Bad value for TraceValues!");
79     abort();
80   }
81   
82   // Eliminate duplication in constant pool
83   Passes.add(createConstantMergePass());
84
85   // Run passes to insert and clean up trace code...
86   Passes.run(M);
87
88   std::string ErrorMessage;
89
90   // Load the module that contains the runtime helper routines neccesary for
91   // pointer hashing and stuff...  link this module into the program if possible
92   //
93   Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc");
94
95   // Ok, the TraceLibPath didn't contain a valid module.  Try to load the module
96   // from the current LLVM-GCC install directory.  This is kindof a hack, but
97   // allows people to not HAVE to have built the library.
98   //
99   if (TraceModule == 0)
100     TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/"
101                                     "gcc-lib/llvm/3.1/libinstr.bc");
102
103   // If we still didn't get it, cancel trying to link it in...
104   if (TraceModule == 0) {
105     cerr << "Warning, could not load trace routines to link into program!\n";
106   } else {
107
108     // Link in the trace routines... if the link fails, don't panic, because the
109     // compile should still succeed, just the native linker will probably fail.
110     //
111     std::auto_ptr<Module> TraceRoutines(TraceModule);
112     if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage))
113       cerr << "Warning: Error linking in trace routines: "
114            << ErrorMessage << "\n";
115   }
116
117
118   // Write out the module with tracing code just before code generation
119   if (InputFilename != "-") {
120     string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc";
121
122     std::ofstream Out(TraceFilename.c_str());
123     if (!Out.good()) {
124       cerr << "Error opening '" << TraceFilename
125            << "'!: Skipping output of trace code as bytecode\n";
126     } else {
127       cerr << "Emitting trace code to '" << TraceFilename
128            << "' for comparison...\n";
129       WriteBytecodeToFile(&M, Out);
130     }
131   }
132
133 }
134   
135
136 //===---------------------------------------------------------------------===//
137 // Function main()
138 // 
139 // Entry point for the llc compiler.
140 //===---------------------------------------------------------------------===//
141
142 int main(int argc, char **argv) {
143   cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
144   
145   // Allocate a target... in the future this will be controllable on the
146   // command line.
147   std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
148   assert(target.get() && "Could not allocate target machine!");
149
150   TargetMachine &Target = *target.get();
151   
152   // Load the module to be compiled...
153   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
154   if (M.get() == 0) {
155     cerr << argv[0] << ": bytecode didn't read correctly.\n";
156     return 1;
157   }
158
159   if (TraceValues != TraceOff)    // If tracing enabled...
160     insertTraceCodeFor(*M.get()); // Hack up module before using passmanager...
161
162   // Build up all of the passes that we want to do to the module...
163   PassManager Passes;
164
165   // Decompose multi-dimensional refs into a sequence of 1D refs
166   Passes.add(createDecomposeMultiDimRefsPass());
167   
168   // Replace malloc and free instructions with library calls.
169   // Do this after tracing until lli implements these lib calls.
170   // For now, it will emulate malloc and free internally.
171   Passes.add(createLowerAllocationsPass(Target.DataLayout));
172   
173   // If LLVM dumping after transformations is requested, add it to the pipeline
174   if (DumpAsm)
175     Passes.add(new PrintFunctionPass("Code after xformations: \n", &cerr));
176
177   // Strip all of the symbols from the bytecode so that it will be smaller...
178   Passes.add(createSymbolStrippingPass());
179
180   // Figure out where we are going to send the output...
181   std::ostream *Out = 0;
182   if (OutputFilename != "") {   // Specified an output filename?
183     if (!Force && std::ifstream(OutputFilename.c_str())) {
184       // If force is not specified, make sure not to overwrite a file!
185       cerr << argv[0] << ": error opening '" << OutputFilename
186            << "': file exists!\n"
187            << "Use -f command line argument to force output\n";
188       return 1;
189     }
190     Out = new std::ofstream(OutputFilename.c_str());
191
192     // Make sure that the Out file gets unlink'd from the disk if we get a
193     // SIGINT
194     RemoveFileOnSignal(OutputFilename);
195   } else {
196     if (InputFilename == "-") {
197       OutputFilename = "-";
198       Out = &std::cout;
199     } else {
200       string OutputFilename = GetFileNameRoot(InputFilename); 
201       OutputFilename += ".s";
202
203       if (!Force && std::ifstream(OutputFilename.c_str())) {
204         // If force is not specified, make sure not to overwrite a file!
205         cerr << argv[0] << ": error opening '" << OutputFilename
206              << "': file exists!\n"
207              << "Use -f command line argument to force output\n";
208         return 1;
209       }
210
211       Out = new std::ofstream(OutputFilename.c_str());
212       if (!Out->good()) {
213         cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
214         delete Out;
215         return 1;
216       }
217       // Make sure that the Out file gets unlink'd from the disk if we get a
218       // SIGINT
219       RemoveFileOnSignal(OutputFilename);
220     }
221   }
222   
223   Target.addPassesToEmitAssembly(Passes, *Out);
224   
225   // Run our queue of passes all at once now, efficiently.
226   Passes.run(*M.get());
227
228   if (Out != &std::cout) delete Out;
229
230   return 0;
231 }