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