When the user runs 'llc foo.bc -march=c', write the output to "foo.cbe.c", not
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the llc code generator.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bytecode/Reader.h"
15 #include "llvm/Target/TargetMachineImpls.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Pass.h"
21 #include "Support/CommandLine.h"
22 #include "Support/Signals.h"
23 #include <memory>
24 #include <fstream>
25
26 using namespace llvm;
27
28 // General options for llc.  Other pass-specific options are specified
29 // within the corresponding llc passes, and target-specific options
30 // and back-end code generation options are specified with the target machine.
31 // 
32 static cl::opt<std::string>
33 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
34
35 static cl::opt<std::string>
36 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
37
38 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
39
40 enum ArchName { noarch, X86, Sparc, PowerPC, CBackend };
41
42 static cl::opt<ArchName>
43 Arch("march", cl::desc("Architecture to generate assembly for:"), cl::Prefix,
44      cl::values(clEnumValN(X86,      "x86",     "  IA-32 (Pentium and above)"),
45                 clEnumValN(Sparc,    "sparc",   "  SPARC V9"),
46                 clEnumValN(PowerPC,  "powerpc", "  PowerPC"),
47                 clEnumValN(CBackend, "c",       "  C backend"),
48                 0),
49      cl::init(noarch));
50
51 // GetFileNameRoot - Helper function to get the basename of a filename...
52 static inline std::string
53 GetFileNameRoot(const std::string &InputFilename)
54 {
55   std::string IFN = InputFilename;
56   std::string outputFilename;
57   int Len = IFN.length();
58   if ((Len > 2) &&
59       IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
60     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
61   } else {
62     outputFilename = IFN;
63   }
64   return outputFilename;
65 }
66
67
68 // main - Entry point for the llc compiler.
69 //
70 int main(int argc, char **argv) {
71   cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
72   
73   // Load the module to be compiled...
74   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
75   if (M.get() == 0) {
76     std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
77     return 1;
78   }
79   Module &mod = *M.get();
80
81   // Allocate target machine.  First, check whether the user has
82   // explicitly specified an architecture to compile for.
83   TargetMachine* (*TargetMachineAllocator)(const Module&,
84                                            IntrinsicLowering *) = 0;
85   switch (Arch) {
86   case CBackend:
87     TargetMachineAllocator = allocateCTargetMachine;
88     break;
89   case X86:
90     TargetMachineAllocator = allocateX86TargetMachine;
91     break;
92   case Sparc:
93     TargetMachineAllocator = allocateSparcTargetMachine;
94     break;
95   case PowerPC:
96     TargetMachineAllocator = allocatePowerPCTargetMachine;
97     break;
98   default:
99     // Decide what the default target machine should be, by looking at
100     // the module. This heuristic (ILP32, LE -> IA32; LP64, BE ->
101     // SPARCV9) is kind of gross, but it will work until we have more
102     // sophisticated target information to work from.
103     if (mod.getEndianness()  == Module::LittleEndian &&
104         mod.getPointerSize() == Module::Pointer32) { 
105       TargetMachineAllocator = allocateX86TargetMachine;
106     } else if (mod.getEndianness() == Module::BigEndian &&
107         mod.getPointerSize() == Module::Pointer32) { 
108       TargetMachineAllocator = allocatePowerPCTargetMachine;
109     } else if (mod.getEndianness()  == Module::BigEndian &&
110                mod.getPointerSize() == Module::Pointer64) { 
111       TargetMachineAllocator = allocateSparcTargetMachine;
112     } else {
113       // If the module is target independent, favor a target which matches the
114       // current build system.
115 #if defined(i386) || defined(__i386__) || defined(__x86__)
116       TargetMachineAllocator = allocateX86TargetMachine;
117 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
118       TargetMachineAllocator = allocateSparcTargetMachine;
119 #elif defined(__POWERPC__) || defined(__ppc__) || defined(__APPLE__)
120       TargetMachineAllocator = allocatePowerPCTargetMachine;
121 #else
122       std::cerr << argv[0] << ": module does not specify a target to use.  "
123                 << "You must use the -march option.  If no native target is "
124                 << "available, use -march=c to emit C code.\n";
125       return 1;
126 #endif
127     } 
128     break;
129   }
130   std::auto_ptr<TargetMachine> target(TargetMachineAllocator(mod, 0));
131   assert(target.get() && "Could not allocate target machine!");
132   TargetMachine &Target = *target.get();
133   const TargetData &TD = Target.getTargetData();
134
135   // Build up all of the passes that we want to do to the module...
136   PassManager Passes;
137
138   Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
139                             TD.getPointerAlignment(), TD.getDoubleAlignment()));
140
141   // Figure out where we are going to send the output...
142   std::ostream *Out = 0;
143   if (OutputFilename != "") {
144     if (OutputFilename != "-") {
145       // Specified an output filename?
146       if (!Force && std::ifstream(OutputFilename.c_str())) {
147         // If force is not specified, make sure not to overwrite a file!
148         std::cerr << argv[0] << ": error opening '" << OutputFilename
149                   << "': file exists!\n"
150                   << "Use -f command line argument to force output\n";
151         return 1;
152       }
153       Out = new std::ofstream(OutputFilename.c_str());
154
155       // Make sure that the Out file gets unlinked from the disk if we get a
156       // SIGINT
157       RemoveFileOnSignal(OutputFilename);
158     } else {
159       Out = &std::cout;
160     }
161   } else {
162     if (InputFilename == "-") {
163       OutputFilename = "-";
164       Out = &std::cout;
165     } else {
166       OutputFilename = GetFileNameRoot(InputFilename); 
167
168       if (Arch != CBackend)
169         OutputFilename += ".s";
170       else
171         OutputFilename += ".cbe.c";
172       
173       if (!Force && std::ifstream(OutputFilename.c_str())) {
174         // If force is not specified, make sure not to overwrite a file!
175         std::cerr << argv[0] << ": error opening '" << OutputFilename
176                   << "': file exists!\n"
177                   << "Use -f command line argument to force output\n";
178         return 1;
179       }
180       
181       Out = new std::ofstream(OutputFilename.c_str());
182       if (!Out->good()) {
183         std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
184         delete Out;
185         return 1;
186       }
187       
188       // Make sure that the Out file gets unlinked from the disk if we get a
189       // SIGINT
190       RemoveFileOnSignal(OutputFilename);
191     }
192   }
193
194   // Ask the target to add backend passes as necessary
195   if (Target.addPassesToEmitAssembly(Passes, *Out)) {
196     std::cerr << argv[0] << ": target '" << Target.getName()
197               << "' does not support static compilation!\n";
198     if (Out != &std::cout) delete Out;
199     // And the Out file is empty and useless, so remove it now.
200     std::remove(OutputFilename.c_str());
201     return 1;
202   } else {
203     // Run our queue of passes all at once now, efficiently.
204     Passes.run(*M.get());
205   }
206
207   // Delete the ostream if it's not a stdout stream
208   if (Out != &std::cout) delete Out;
209
210   return 0;
211 }