llc: Eliminate a use of getDarwinMajorNumber().
[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 is distributed under the University of Illinois Open Source
6 // 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 bitcode.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Pass.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Support/IRReader.h"
22 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
23 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/FormattedStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/PluginLoader.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/ToolOutputFile.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/Signals.h"
34 #include "llvm/Target/SubtargetFeature.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Target/TargetSelect.h"
39 #include <memory>
40 using namespace llvm;
41
42 // General options for llc.  Other pass-specific options are specified
43 // within the corresponding llc passes, and target-specific options
44 // and back-end code generation options are specified with the target machine.
45 //
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52 // Determine optimization level.
53 static cl::opt<char>
54 OptLevel("O",
55          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
56                   "(default = '-O2')"),
57          cl::Prefix,
58          cl::ZeroOrMore,
59          cl::init(' '));
60
61 static cl::opt<std::string>
62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
63
64 static cl::opt<std::string>
65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
66
67 static cl::opt<std::string>
68 MCPU("mcpu",
69   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70   cl::value_desc("cpu-name"),
71   cl::init(""));
72
73 static cl::list<std::string>
74 MAttrs("mattr",
75   cl::CommaSeparated,
76   cl::desc("Target specific attributes (-mattr=help for details)"),
77   cl::value_desc("a1,+a2,-a3,..."));
78
79 static cl::opt<bool>
80 RelaxAll("mc-relax-all",
81   cl::desc("When used with filetype=obj, "
82            "relax all fixups in the emitted object file"));
83
84 cl::opt<TargetMachine::CodeGenFileType>
85 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
86   cl::desc("Choose a file type (not all types are supported by all targets):"),
87   cl::values(
88        clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
89                   "Emit an assembly ('.s') file"),
90        clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
91                   "Emit a native object ('.o') file [experimental]"),
92        clEnumValN(TargetMachine::CGFT_Null, "null",
93                   "Emit nothing, for performance testing"),
94        clEnumValEnd));
95
96 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
97                        cl::desc("Do not verify input module"));
98
99 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
100                             cl::desc("Do not use .loc entries"));
101
102 static cl::opt<bool>
103 DisableRedZone("disable-red-zone",
104   cl::desc("Do not emit code that uses the red zone."),
105   cl::init(false));
106
107 static cl::opt<bool>
108 NoImplicitFloats("no-implicit-float",
109   cl::desc("Don't generate implicit floating point instructions (x86-only)"),
110   cl::init(false));
111
112 // GetFileNameRoot - Helper function to get the basename of a filename.
113 static inline std::string
114 GetFileNameRoot(const std::string &InputFilename) {
115   std::string IFN = InputFilename;
116   std::string outputFilename;
117   int Len = IFN.length();
118   if ((Len > 2) &&
119       IFN[Len-3] == '.' &&
120       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
121        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
122     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
123   } else {
124     outputFilename = IFN;
125   }
126   return outputFilename;
127 }
128
129 static tool_output_file *GetOutputStream(const char *TargetName,
130                                          Triple::OSType OS,
131                                          const char *ProgName) {
132   // If we don't yet have an output filename, make one.
133   if (OutputFilename.empty()) {
134     if (InputFilename == "-")
135       OutputFilename = "-";
136     else {
137       OutputFilename = GetFileNameRoot(InputFilename);
138
139       switch (FileType) {
140       default: assert(0 && "Unknown file type");
141       case TargetMachine::CGFT_AssemblyFile:
142         if (TargetName[0] == 'c') {
143           if (TargetName[1] == 0)
144             OutputFilename += ".cbe.c";
145           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
146             OutputFilename += ".cpp";
147           else
148             OutputFilename += ".s";
149         } else
150           OutputFilename += ".s";
151         break;
152       case TargetMachine::CGFT_ObjectFile:
153         if (OS == Triple::Win32)
154           OutputFilename += ".obj";
155         else
156           OutputFilename += ".o";
157         break;
158       case TargetMachine::CGFT_Null:
159         OutputFilename += ".null";
160         break;
161       }
162     }
163   }
164
165   // Decide if we need "binary" output.
166   bool Binary = false;
167   switch (FileType) {
168   default: assert(0 && "Unknown file type");
169   case TargetMachine::CGFT_AssemblyFile:
170     break;
171   case TargetMachine::CGFT_ObjectFile:
172   case TargetMachine::CGFT_Null:
173     Binary = true;
174     break;
175   }
176
177   // Open the file.
178   std::string error;
179   unsigned OpenFlags = 0;
180   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
181   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
182                                                  OpenFlags);
183   if (!error.empty()) {
184     errs() << error << '\n';
185     delete FDOut;
186     return 0;
187   }
188
189   return FDOut;
190 }
191
192 // main - Entry point for the llc compiler.
193 //
194 int main(int argc, char **argv) {
195   sys::PrintStackTraceOnErrorSignal();
196   PrettyStackTraceProgram X(argc, argv);
197
198   // Enable debug stream buffering.
199   EnableDebugBuffering = true;
200
201   LLVMContext &Context = getGlobalContext();
202   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
203
204   // Initialize targets first, so that --version shows registered targets.
205   InitializeAllTargets();
206   InitializeAllAsmPrinters();
207   InitializeAllAsmParsers();
208
209   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
210
211   // Load the module to be compiled...
212   SMDiagnostic Err;
213   std::auto_ptr<Module> M;
214
215   M.reset(ParseIRFile(InputFilename, Err, Context));
216   if (M.get() == 0) {
217     Err.Print(argv[0], errs());
218     return 1;
219   }
220   Module &mod = *M.get();
221
222   // If we are supposed to override the target triple, do so now.
223   if (!TargetTriple.empty())
224     mod.setTargetTriple(Triple::normalize(TargetTriple));
225
226   Triple TheTriple(mod.getTargetTriple());
227   if (TheTriple.getTriple().empty())
228     TheTriple.setTriple(sys::getHostTriple());
229
230   // Allocate target machine.  First, check whether the user has explicitly
231   // specified an architecture to compile for. If so we have to look it up by
232   // name, because it might be a backend that has no mapping to a target triple.
233   const Target *TheTarget = 0;
234   if (!MArch.empty()) {
235     for (TargetRegistry::iterator it = TargetRegistry::begin(),
236            ie = TargetRegistry::end(); it != ie; ++it) {
237       if (MArch == it->getName()) {
238         TheTarget = &*it;
239         break;
240       }
241     }
242
243     if (!TheTarget) {
244       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
245       return 1;
246     }
247
248     // Adjust the triple to match (if known), otherwise stick with the
249     // module/host triple.
250     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
251     if (Type != Triple::UnknownArch)
252       TheTriple.setArch(Type);
253   } else {
254     std::string Err;
255     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
256     if (TheTarget == 0) {
257       errs() << argv[0] << ": error auto-selecting target for module '"
258              << Err << "'.  Please use the -march option to explicitly "
259              << "pick a target.\n";
260       return 1;
261     }
262   }
263
264   // Package up features to be passed to target/subtarget
265   std::string FeaturesStr;
266   if (MCPU.size() || MAttrs.size()) {
267     SubtargetFeatures Features;
268     Features.setCPU(MCPU);
269     for (unsigned i = 0; i != MAttrs.size(); ++i)
270       Features.AddFeature(MAttrs[i]);
271     FeaturesStr = Features.getString();
272   }
273
274   std::auto_ptr<TargetMachine>
275     target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
276   assert(target.get() && "Could not allocate target machine!");
277   TargetMachine &Target = *target.get();
278
279   if (DisableDotLoc)
280     Target.setMCUseLoc(false);
281
282   // Disable .loc support for older OS X versions.
283   if (TheTriple.isOSX() && TheTriple.isOSXVersionLT(10, 5))
284     Target.setMCUseLoc(false);
285
286   // Figure out where we are going to send the output...
287   OwningPtr<tool_output_file> Out
288     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
289   if (!Out) return 1;
290
291   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
292   switch (OptLevel) {
293   default:
294     errs() << argv[0] << ": invalid optimization level.\n";
295     return 1;
296   case ' ': break;
297   case '0': OLvl = CodeGenOpt::None; break;
298   case '1': OLvl = CodeGenOpt::Less; break;
299   case '2': OLvl = CodeGenOpt::Default; break;
300   case '3': OLvl = CodeGenOpt::Aggressive; break;
301   }
302
303   // Build up all of the passes that we want to do to the module.
304   PassManager PM;
305
306   // Add the target data from the target machine, if it exists, or the module.
307   if (const TargetData *TD = Target.getTargetData())
308     PM.add(new TargetData(*TD));
309   else
310     PM.add(new TargetData(&mod));
311
312   // Override default to generate verbose assembly.
313   Target.setAsmVerbosityDefault(true);
314
315   if (RelaxAll) {
316     if (FileType != TargetMachine::CGFT_ObjectFile)
317       errs() << argv[0]
318              << ": warning: ignoring -mc-relax-all because filetype != obj";
319     else
320       Target.setMCRelaxAll(true);
321   }
322
323   {
324     formatted_raw_ostream FOS(Out->os());
325
326     // Ask the target to add backend passes as necessary.
327     if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
328       errs() << argv[0] << ": target does not support generation of this"
329              << " file type!\n";
330       return 1;
331     }
332
333     // Before executing passes, print the final values of the LLVM options.
334     cl::PrintOptionValues();
335
336     PM.run(mod);
337   }
338
339   // Declare success.
340   Out->keep();
341
342   return 0;
343 }