Refactor Assembly/Bytecode writer code into Assembly & bytecode libraries
[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/LowerAllocations.h"
12 #include "llvm/Transforms/HoistPHIConstants.h"
13 #include "llvm/Assembly/PrintModulePass.h"
14 #include "llvm/Bytecode/WriteBytecodePass.h"
15 #include "llvm/Transforms/ConstantMerge.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Module.h"
18 #include "llvm/Method.h"
19 #include <memory>
20 #include <string>
21 #include <fstream>
22
23 cl::String InputFilename ("", "Input filename", cl::NoFlags, "-");
24 cl::String OutputFilename("o", "Output filename", cl::NoFlags, "");
25 cl::Flag   Force         ("f", "Overwrite output files");
26 cl::Flag   DumpAsm       ("d", "Print bytecode before native code generation",
27                           cl::Hidden);
28 cl::Flag   DoNotEmitAssembly("noasm", "Do not emit assembly code", cl::Hidden);
29 cl::Flag   TraceBBValues ("trace",
30                           "Trace values at basic block and method exits");
31 cl::Flag   TraceMethodValues("tracem", "Trace values only at method exits");
32
33
34 // GetFileNameRoot - Helper function to get the basename of a filename...
35 static inline string GetFileNameRoot(const string &InputFilename) {
36   string IFN = InputFilename;
37   string outputFilename;
38   int Len = IFN.length();
39   if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
40     outputFilename = string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
41   } else {
42     outputFilename = IFN;
43   }
44   return outputFilename;
45 }
46
47
48 //===---------------------------------------------------------------------===//
49 // GenerateCodeForTarget Pass
50 // 
51 // Native code generation for a specified target.
52 //===---------------------------------------------------------------------===//
53
54 class GenerateCodeForTarget : public Pass {
55   TargetMachine &Target;
56 public:
57   inline GenerateCodeForTarget(TargetMachine &T) : Target(T) {}
58
59   // doPerMethodWork - This method does the actual work of generating code for
60   // the specified method.
61   //
62   bool doPerMethodWork(Method *M) {
63     if (!M->isExternal() && Target.compileMethod(M)) {
64       cerr << "Error compiling " << InputFilename << "!\n";
65       return true;
66     }
67     
68     return false;
69   }
70 };
71
72
73 //===---------------------------------------------------------------------===//
74 // EmitAssembly Pass
75 // 
76 // Write assembly code to specified output stream
77 //===---------------------------------------------------------------------===//
78
79 class EmitAssembly : public Pass {
80   const TargetMachine &Target;   // Target to compile for
81   ostream *Out;                  // Stream to print on
82   bool DeleteStream;             // Delete stream in dtor?
83 public:
84   inline EmitAssembly(const TargetMachine &T, ostream *O, bool D)
85     : Target(T), Out(O), DeleteStream(D) {}
86
87
88   virtual bool doPassFinalization(Module *M) {
89     Target.emitAssembly(M, *Out);
90
91     if (DeleteStream) delete Out;
92     return false;
93   }
94 };
95
96
97 //===---------------------------------------------------------------------===//
98 // Function main()
99 // 
100 // Entry point for the llc compiler.
101 //===---------------------------------------------------------------------===//
102
103 int main(int argc, char **argv) {
104   int retCode = 0;
105   cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
106   
107   // Allocate a target... in the future this will be controllable on the
108   // command line.
109   auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
110   assert(target.get() && "Could not allocate target machine!");
111
112   TargetMachine &Target = *target.get();
113   
114   // Load the module to be compiled...
115   auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
116   if (M.get() == 0) {
117     cerr << "bytecode didn't read correctly.\n";
118     return 1;
119   }
120
121   // Build up all of the passes that we want to do to the module...
122   vector<Pass*> Passes;
123
124   // Hoist constants out of PHI nodes into predecessor BB's
125   Passes.push_back(new HoistPHIConstants());
126
127   if (TraceBBValues || TraceMethodValues) {   // If tracing enabled...
128     // Insert trace code in all methods in the module
129     Passes.push_back(new InsertTraceCode(TraceBBValues, 
130                                          TraceBBValues ||TraceMethodValues));
131
132     // Eliminate duplication in constant pool
133     Passes.push_back(new DynamicConstantMerge());
134       
135     // Then write out the module with tracing code before code generation 
136     assert(InputFilename != "-" &&
137            "files on stdin not supported with tracing");
138     string traceFileName = GetFileNameRoot(InputFilename) + ".trace.bc";
139     ostream *os = new ofstream(traceFileName.c_str(), 
140                                (Force ? 0 : ios::noreplace)|ios::out);
141     if (!os->good()) {
142       cerr << "Error opening " << traceFileName
143            << "! SKIPPING OUTPUT OF TRACE CODE\n";
144       delete os;
145       return 1;
146     }
147     
148     Passes.push_back(new WriteBytecodePass(os, true));
149   }
150   
151   // Replace malloc and free instructions with library calls.
152   // Do this after tracing until lli implements these lib calls.
153   // For now, it will emulate malloc and free internally.
154   Passes.push_back(new LowerAllocations(Target.DataLayout));
155   
156   // If LLVM dumping after transformations is requested, add it to the pipeline
157   if (DumpAsm)
158     Passes.push_back(new PrintModulePass("Code after xformations: \n",&cerr));
159
160   // Generate Target code...
161   Passes.push_back(new GenerateCodeForTarget(Target));
162
163   if (!DoNotEmitAssembly) {                // If asm output is enabled...
164     // Figure out where we are going to send the output...
165     ostream *Out = 0;
166     if (OutputFilename != "") {   // Specified an output filename?
167       Out = new ofstream(OutputFilename.c_str(), 
168                          (Force ? 0 : ios::noreplace)|ios::out);
169     } else {
170       if (InputFilename == "-") {
171         OutputFilename = "-";
172         Out = &cout;
173       } else {
174         string OutputFilename = GetFileNameRoot(InputFilename); 
175         OutputFilename += ".s";
176         Out = new ofstream(OutputFilename.c_str(), 
177                            (Force ? 0 : ios::noreplace)|ios::out);
178         if (!Out->good()) {
179           cerr << "Error opening " << OutputFilename << "!\n";
180           delete Out;
181           return 1;
182         }
183       }
184     }
185     
186     // Output assembly language to the .s file
187     Passes.push_back(new EmitAssembly(Target, Out, Out != &cout));
188   }
189   
190   // Run our queue of passes all at once now, efficiently.  This form of
191   // runAllPasses frees the Pass objects after runAllPasses completes.
192   Pass::runAllPassesAndFree(M.get(), Passes);
193
194   return retCode;
195 }
196
197