2ce1e542765ae711ed6ef4568550ffa3a1627123
[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 };
41
42 static cl::opt<ArchName>
43 Arch("march", cl::desc("Architecture to generate assembly for:"), cl::Prefix,
44      cl::values(clEnumVal(x86, "  IA-32 (Pentium and above)"),
45                 clEnumValN(Sparc, "sparc", "  SPARC V9"),
46                 clEnumValN(PowerPC, "powerpc", "  PowerPC"),
47                 0),
48      cl::init(noarch));
49
50 // GetFileNameRoot - Helper function to get the basename of a filename...
51 static inline std::string
52 GetFileNameRoot(const std::string &InputFilename)
53 {
54   std::string IFN = InputFilename;
55   std::string outputFilename;
56   int Len = IFN.length();
57   if ((Len > 2) &&
58       IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
59     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
60   } else {
61     outputFilename = IFN;
62   }
63   return outputFilename;
64 }
65
66
67 // main - Entry point for the llc compiler.
68 //
69 int main(int argc, char **argv) {
70   cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
71   
72   // Load the module to be compiled...
73   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
74   if (M.get() == 0) {
75     std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
76     return 1;
77   }
78   Module &mod = *M.get();
79
80   // Allocate target machine.  First, check whether the user has
81   // explicitly specified an architecture to compile for.
82   TargetMachine* (*TargetMachineAllocator)(const Module&,
83                                            IntrinsicLowering *) = 0;
84   switch (Arch) {
85   case x86:
86     TargetMachineAllocator = allocateX86TargetMachine;
87     break;
88   case Sparc:
89     TargetMachineAllocator = allocateSparcTargetMachine;
90     break;
91   case PowerPC:
92     TargetMachineAllocator = allocatePowerPCTargetMachine;
93     break;
94   default:
95     // Decide what the default target machine should be, by looking at
96     // the module. This heuristic (ILP32, LE -> IA32; LP64, BE ->
97     // SPARCV9) is kind of gross, but it will work until we have more
98     // sophisticated target information to work from.
99     if (mod.getEndianness()  == Module::LittleEndian &&
100         mod.getPointerSize() == Module::Pointer32) { 
101       TargetMachineAllocator = allocateX86TargetMachine;
102     } else if (mod.getEndianness() == Module::BigEndian &&
103         mod.getPointerSize() == Module::Pointer32) { 
104       TargetMachineAllocator = allocatePowerPCTargetMachine;
105     } else if (mod.getEndianness()  == Module::BigEndian &&
106                mod.getPointerSize() == Module::Pointer64) { 
107       TargetMachineAllocator = allocateSparcTargetMachine;
108     } else {
109       // If the module is target independent, favor a target which matches the
110       // current build system.
111 #if defined(i386) || defined(__i386__) || defined(__x86__)
112       TargetMachineAllocator = allocateX86TargetMachine;
113 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
114       TargetMachineAllocator = allocateSparcTargetMachine;
115 #elif defined(__POWERPC__) || defined(__ppc__) || defined(__APPLE__)
116       TargetMachineAllocator = allocatePowerPCTargetMachine;
117 #else
118       std::cerr << argv[0] << ": module does not specify a target to use.  "
119                 << "You must use the -march option.\n";
120       return 1;
121 #endif
122     } 
123     break;
124   }
125   std::auto_ptr<TargetMachine> target(TargetMachineAllocator(mod, 0));
126   assert(target.get() && "Could not allocate target machine!");
127   TargetMachine &Target = *target.get();
128   const TargetData &TD = Target.getTargetData();
129
130   // Build up all of the passes that we want to do to the module...
131   PassManager Passes;
132
133   Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
134                             TD.getPointerAlignment(), TD.getDoubleAlignment()));
135
136   // Figure out where we are going to send the output...
137   std::ostream *Out = 0;
138   if (OutputFilename != "") {
139     if (OutputFilename != "-") {
140       // Specified an output filename?
141       if (!Force && std::ifstream(OutputFilename.c_str())) {
142         // If force is not specified, make sure not to overwrite a file!
143         std::cerr << argv[0] << ": error opening '" << OutputFilename
144                   << "': file exists!\n"
145                   << "Use -f command line argument to force output\n";
146         return 1;
147       }
148       Out = new std::ofstream(OutputFilename.c_str());
149
150       // Make sure that the Out file gets unlinked from the disk if we get a
151       // SIGINT
152       RemoveFileOnSignal(OutputFilename);
153     } else {
154       Out = &std::cout;
155     }
156   } else {
157     if (InputFilename == "-") {
158       OutputFilename = "-";
159       Out = &std::cout;
160     } else {
161       OutputFilename = GetFileNameRoot(InputFilename); 
162       OutputFilename += ".s";
163       
164       if (!Force && std::ifstream(OutputFilename.c_str())) {
165         // If force is not specified, make sure not to overwrite a file!
166         std::cerr << argv[0] << ": error opening '" << OutputFilename
167                   << "': file exists!\n"
168                   << "Use -f command line argument to force output\n";
169         return 1;
170       }
171       
172       Out = new std::ofstream(OutputFilename.c_str());
173       if (!Out->good()) {
174         std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
175         delete Out;
176         return 1;
177       }
178       
179       // Make sure that the Out file gets unlinked from the disk if we get a
180       // SIGINT
181       RemoveFileOnSignal(OutputFilename);
182     }
183   }
184
185   // Ask the target to add backend passes as necessary
186   if (Target.addPassesToEmitAssembly(Passes, *Out)) {
187     std::cerr << argv[0] << ": target '" << Target.getName()
188               << "' does not support static compilation!\n";
189     if (Out != &std::cout) delete Out;
190     // And the Out file is empty and useless, so remove it now.
191     std::remove(OutputFilename.c_str());
192     return 1;
193   } else {
194     // Run our queue of passes all at once now, efficiently.
195     Passes.run(*M.get());
196   }
197
198   // Delete the ostream if it's not a stdout stream
199   if (Out != &std::cout) delete Out;
200
201   return 0;
202 }