9227e1c6b359788fc0ace21baa8f267449fa5249
[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/Analysis/Verifier.h"
22 #include "llvm/Support/IRReader.h"
23 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
24 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/PluginLoader.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/System/Host.h"
33 #include "llvm/System/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 emited 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
100 static cl::opt<bool>
101 DisableRedZone("disable-red-zone",
102   cl::desc("Do not emit code that uses the red zone."),
103   cl::init(false));
104
105 static cl::opt<bool>
106 NoImplicitFloats("no-implicit-float",
107   cl::desc("Don't generate implicit floating point instructions (x86-only)"),
108   cl::init(false));
109
110 // GetFileNameRoot - Helper function to get the basename of a filename.
111 static inline std::string
112 GetFileNameRoot(const std::string &InputFilename) {
113   std::string IFN = InputFilename;
114   std::string outputFilename;
115   int Len = IFN.length();
116   if ((Len > 2) &&
117       IFN[Len-3] == '.' &&
118       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
119        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
120     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
121   } else {
122     outputFilename = IFN;
123   }
124   return outputFilename;
125 }
126
127 static formatted_raw_ostream *GetOutputStream(const char *TargetName,
128                                               Triple::OSType OS,
129                                               const char *ProgName) {
130   if (OutputFilename != "") {
131     if (OutputFilename == "-")
132       return new formatted_raw_ostream(outs(),
133                                        formatted_raw_ostream::PRESERVE_STREAM);
134
135     // Make sure that the Out file gets unlinked from the disk if we get a
136     // SIGINT
137     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
138
139     std::string error;
140     raw_fd_ostream *FDOut =
141       new raw_fd_ostream(OutputFilename.c_str(), error,
142                          raw_fd_ostream::F_Binary);
143     if (!error.empty()) {
144       errs() << error << '\n';
145       delete FDOut;
146       return 0;
147     }
148     formatted_raw_ostream *Out =
149       new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
150
151     return Out;
152   }
153
154   if (InputFilename == "-") {
155     OutputFilename = "-";
156     return new formatted_raw_ostream(outs(),
157                                      formatted_raw_ostream::PRESERVE_STREAM);
158   }
159
160   OutputFilename = GetFileNameRoot(InputFilename);
161
162   bool Binary = false;
163   switch (FileType) {
164   default: assert(0 && "Unknown file type");
165   case TargetMachine::CGFT_AssemblyFile:
166     if (TargetName[0] == 'c') {
167       if (TargetName[1] == 0)
168         OutputFilename += ".cbe.c";
169       else if (TargetName[1] == 'p' && TargetName[2] == 'p')
170         OutputFilename += ".cpp";
171       else
172         OutputFilename += ".s";
173     } else
174       OutputFilename += ".s";
175     break;
176   case TargetMachine::CGFT_ObjectFile:
177     if (OS == Triple::Win32)
178       OutputFilename += ".obj";
179     else
180       OutputFilename += ".o";
181     Binary = true;
182     break;
183   case TargetMachine::CGFT_Null:
184     OutputFilename += ".null";
185     Binary = true;
186     break;
187   }
188
189   // Make sure that the Out file gets unlinked from the disk if we get a
190   // SIGINT
191   sys::RemoveFileOnSignal(sys::Path(OutputFilename));
192
193   std::string error;
194   unsigned OpenFlags = 0;
195   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
196   raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
197                                              OpenFlags);
198   if (!error.empty()) {
199     errs() << error << '\n';
200     delete FDOut;
201     return 0;
202   }
203
204   formatted_raw_ostream *Out =
205     new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
206
207   return Out;
208 }
209
210 // main - Entry point for the llc compiler.
211 //
212 int main(int argc, char **argv) {
213   sys::PrintStackTraceOnErrorSignal();
214   PrettyStackTraceProgram X(argc, argv);
215
216   // Enable debug stream buffering.
217   EnableDebugBuffering = true;
218
219   LLVMContext &Context = getGlobalContext();
220   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
221
222   // Initialize targets first, so that --version shows registered targets.
223   InitializeAllTargets();
224   InitializeAllAsmPrinters();
225   InitializeAllAsmParsers();
226
227   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
228   
229   // Load the module to be compiled...
230   SMDiagnostic Err;
231   std::auto_ptr<Module> M;
232
233   M.reset(ParseIRFile(InputFilename, Err, Context));
234   if (M.get() == 0) {
235     Err.Print(argv[0], errs());
236     return 1;
237   }
238   Module &mod = *M.get();
239
240   // If we are supposed to override the target triple, do so now.
241   if (!TargetTriple.empty())
242     mod.setTargetTriple(TargetTriple);
243
244   Triple TheTriple(mod.getTargetTriple());
245   if (TheTriple.getTriple().empty())
246     TheTriple.setTriple(sys::getHostTriple());
247
248   // Allocate target machine.  First, check whether the user has explicitly
249   // specified an architecture to compile for. If so we have to look it up by
250   // name, because it might be a backend that has no mapping to a target triple.
251   const Target *TheTarget = 0;
252   if (!MArch.empty()) {
253     for (TargetRegistry::iterator it = TargetRegistry::begin(),
254            ie = TargetRegistry::end(); it != ie; ++it) {
255       if (MArch == it->getName()) {
256         TheTarget = &*it;
257         break;
258       }
259     }
260
261     if (!TheTarget) {
262       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
263       return 1;
264     }
265
266     // Adjust the triple to match (if known), otherwise stick with the
267     // module/host triple.
268     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
269     if (Type != Triple::UnknownArch)
270       TheTriple.setArch(Type);
271   } else {
272     std::string Err;
273     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
274     if (TheTarget == 0) {
275       errs() << argv[0] << ": error auto-selecting target for module '"
276              << Err << "'.  Please use the -march option to explicitly "
277              << "pick a target.\n";
278       return 1;
279     }
280   }
281
282   // Package up features to be passed to target/subtarget
283   std::string FeaturesStr;
284   if (MCPU.size() || MAttrs.size()) {
285     SubtargetFeatures Features;
286     Features.setCPU(MCPU);
287     for (unsigned i = 0; i != MAttrs.size(); ++i)
288       Features.AddFeature(MAttrs[i]);
289     FeaturesStr = Features.getString();
290   }
291
292   std::auto_ptr<TargetMachine> 
293     target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
294   assert(target.get() && "Could not allocate target machine!");
295   TargetMachine &Target = *target.get();
296
297   // Figure out where we are going to send the output...
298   formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(),
299                                                TheTriple.getOS(), argv[0]);
300   if (Out == 0) return 1;
301
302   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
303   switch (OptLevel) {
304   default:
305     errs() << argv[0] << ": invalid optimization level.\n";
306     return 1;
307   case ' ': break;
308   case '0': OLvl = CodeGenOpt::None; break;
309   case '1': OLvl = CodeGenOpt::Less; break;
310   case '2': OLvl = CodeGenOpt::Default; break;
311   case '3': OLvl = CodeGenOpt::Aggressive; break;
312   }
313
314   // Request that addPassesToEmitFile run the Verifier after running
315   // passes which modify the IR.
316 #ifndef NDEBUG
317   bool DisableVerify = false;
318 #else
319   bool DisableVerify = true;
320 #endif
321
322   // Build up all of the passes that we want to do to the module.
323   PassManager PM;
324
325   // Add the target data from the target machine, if it exists, or the module.
326   if (const TargetData *TD = Target.getTargetData())
327     PM.add(new TargetData(*TD));
328   else
329     PM.add(new TargetData(&mod));
330
331   if (!NoVerify)
332     PM.add(createVerifierPass());
333
334   // Override default to generate verbose assembly.
335   Target.setAsmVerbosityDefault(true);
336
337   if (RelaxAll) {
338     if (FileType != TargetMachine::CGFT_ObjectFile)
339       errs() << argv[0]
340              << ": warning: ignoring -mc-relax-all because filetype != obj";
341     else
342       Target.setMCRelaxAll(true);
343   }
344
345   // Ask the target to add backend passes as necessary.
346   if (Target.addPassesToEmitFile(PM, *Out, FileType, OLvl,
347                                  DisableVerify)) {
348     errs() << argv[0] << ": target does not support generation of this"
349            << " file type!\n";
350     delete Out;
351     // And the Out file is empty and useless, so remove it now.
352     sys::Path(OutputFilename).eraseFromDisk();
353     return 1;
354   }
355
356   PM.run(mod);
357
358   // Delete the ostream.
359   delete Out;
360
361   return 0;
362 }