Fix it so llvm-objdump -arch does accept x86 and x86-64 as valid arch names.
[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/MC/SubtargetFeature.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/Support/TargetRegistry.h"
35 #include "llvm/Support/TargetSelect.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include <memory>
39 using namespace llvm;
40
41 // General options for llc.  Other pass-specific options are specified
42 // within the corresponding llc passes, and target-specific options
43 // and back-end code generation options are specified with the target machine.
44 //
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
47
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
50
51 // Determine optimization level.
52 static cl::opt<char>
53 OptLevel("O",
54          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
55                   "(default = '-O2')"),
56          cl::Prefix,
57          cl::ZeroOrMore,
58          cl::init(' '));
59
60 static cl::opt<std::string>
61 TargetTriple("mtriple", cl::desc("Override target triple for module"));
62
63 static cl::opt<std::string>
64 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
65
66 static cl::opt<std::string>
67 MCPU("mcpu",
68   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
69   cl::value_desc("cpu-name"),
70   cl::init(""));
71
72 static cl::list<std::string>
73 MAttrs("mattr",
74   cl::CommaSeparated,
75   cl::desc("Target specific attributes (-mattr=help for details)"),
76   cl::value_desc("a1,+a2,-a3,..."));
77
78 static cl::opt<Reloc::Model>
79 RelocModel("relocation-model",
80              cl::desc("Choose relocation model"),
81              cl::init(Reloc::Default),
82              cl::values(
83             clEnumValN(Reloc::Default, "default",
84                        "Target default relocation model"),
85             clEnumValN(Reloc::Static, "static",
86                        "Non-relocatable code"),
87             clEnumValN(Reloc::PIC_, "pic",
88                        "Fully relocatable, position independent code"),
89             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
90                        "Relocatable external references, non-relocatable code"),
91             clEnumValEnd));
92
93 static cl::opt<llvm::CodeModel::Model>
94 CMModel("code-model",
95         cl::desc("Choose code model"),
96         cl::init(CodeModel::Default),
97         cl::values(clEnumValN(CodeModel::Default, "default",
98                               "Target default code model"),
99                    clEnumValN(CodeModel::Small, "small",
100                               "Small code model"),
101                    clEnumValN(CodeModel::Kernel, "kernel",
102                               "Kernel code model"),
103                    clEnumValN(CodeModel::Medium, "medium",
104                               "Medium code model"),
105                    clEnumValN(CodeModel::Large, "large",
106                               "Large code model"),
107                    clEnumValEnd));
108
109 static cl::opt<bool>
110 RelaxAll("mc-relax-all",
111   cl::desc("When used with filetype=obj, "
112            "relax all fixups in the emitted object file"));
113
114 cl::opt<TargetMachine::CodeGenFileType>
115 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
116   cl::desc("Choose a file type (not all types are supported by all targets):"),
117   cl::values(
118        clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
119                   "Emit an assembly ('.s') file"),
120        clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
121                   "Emit a native object ('.o') file [experimental]"),
122        clEnumValN(TargetMachine::CGFT_Null, "null",
123                   "Emit nothing, for performance testing"),
124        clEnumValEnd));
125
126 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
127                        cl::desc("Do not verify input module"));
128
129 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
130                             cl::desc("Do not use .loc entries"));
131
132 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
133                          cl::desc("Do not use .cfi_* directives"));
134
135 cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
136     cl::desc("Use .file directives with an explicit directory."));
137
138 static cl::opt<bool>
139 DisableRedZone("disable-red-zone",
140   cl::desc("Do not emit code that uses the red zone."),
141   cl::init(false));
142
143 static cl::opt<bool>
144 EnableFPMAD("enable-fp-mad",
145   cl::desc("Enable less precise MAD instructions to be generated"),
146   cl::init(false));
147
148 static cl::opt<bool>
149 PrintCode("print-machineinstrs",
150   cl::desc("Print generated machine code"),
151   cl::init(false));
152
153 static cl::opt<bool>
154 DisableFPElim("disable-fp-elim",
155   cl::desc("Disable frame pointer elimination optimization"),
156   cl::init(false));
157
158 static cl::opt<bool>
159 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
160   cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
161   cl::init(false));
162
163 static cl::opt<bool>
164 DisableExcessPrecision("disable-excess-fp-precision",
165   cl::desc("Disable optimizations that may increase FP precision"),
166   cl::init(false));
167
168 static cl::opt<bool>
169 EnableUnsafeFPMath("enable-unsafe-fp-math",
170   cl::desc("Enable optimizations that may decrease FP precision"),
171   cl::init(false));
172
173 static cl::opt<bool>
174 EnableNoInfsFPMath("enable-no-infs-fp-math",
175   cl::desc("Enable FP math optimizations that assume no +-Infs"),
176   cl::init(false));
177
178 static cl::opt<bool>
179 EnableNoNaNsFPMath("enable-no-nans-fp-math",
180   cl::desc("Enable FP math optimizations that assume no NaNs"),
181   cl::init(false));
182
183 static cl::opt<bool>
184 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
185   cl::Hidden,
186   cl::desc("Force codegen to assume rounding mode can change dynamically"),
187   cl::init(false));
188
189 static cl::opt<bool>
190 GenerateSoftFloatCalls("soft-float",
191   cl::desc("Generate software floating point library calls"),
192   cl::init(false));
193
194 static cl::opt<llvm::FloatABI::ABIType>
195 FloatABIForCalls("float-abi",
196   cl::desc("Choose float ABI type"),
197   cl::init(FloatABI::Default),
198   cl::values(
199     clEnumValN(FloatABI::Default, "default",
200                "Target default float ABI type"),
201     clEnumValN(FloatABI::Soft, "soft",
202                "Soft float ABI (implied by -soft-float)"),
203     clEnumValN(FloatABI::Hard, "hard",
204                "Hard float ABI (uses FP registers)"),
205     clEnumValEnd));
206
207 static cl::opt<bool>
208 DontPlaceZerosInBSS("nozero-initialized-in-bss",
209   cl::desc("Don't place zero-initialized symbols into bss section"),
210   cl::init(false));
211
212 static cl::opt<bool>
213 EnableGuaranteedTailCallOpt("tailcallopt",
214   cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
215   cl::init(false));
216
217 static cl::opt<bool>
218 DisableTailCalls("disable-tail-calls",
219   cl::desc("Never emit tail calls"),
220   cl::init(false));
221
222 static cl::opt<unsigned>
223 OverrideStackAlignment("stack-alignment",
224   cl::desc("Override default stack alignment"),
225   cl::init(0));
226
227 static cl::opt<bool>
228 EnableRealignStack("realign-stack",
229   cl::desc("Realign stack if needed"),
230   cl::init(true));
231
232 static cl::opt<bool>
233 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
234   cl::desc("Do not generate jump tables."),
235   cl::init(false));
236
237 static cl::opt<std::string>
238 TrapFuncName("trap-func", cl::Hidden,
239   cl::desc("Emit a call to trap function rather than a trap instruction"),
240   cl::init(""));
241
242 static cl::opt<bool>
243 EnablePIE("enable-pie",
244   cl::desc("Assume the creation of a position independent executable."),
245   cl::init(false));
246
247 static cl::opt<bool>
248 SegmentedStacks("segmented-stacks",
249   cl::desc("Use segmented stacks if possible."),
250   cl::init(false));
251
252
253 // GetFileNameRoot - Helper function to get the basename of a filename.
254 static inline std::string
255 GetFileNameRoot(const std::string &InputFilename) {
256   std::string IFN = InputFilename;
257   std::string outputFilename;
258   int Len = IFN.length();
259   if ((Len > 2) &&
260       IFN[Len-3] == '.' &&
261       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
262        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
263     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
264   } else {
265     outputFilename = IFN;
266   }
267   return outputFilename;
268 }
269
270 static tool_output_file *GetOutputStream(const char *TargetName,
271                                          Triple::OSType OS,
272                                          const char *ProgName) {
273   // If we don't yet have an output filename, make one.
274   if (OutputFilename.empty()) {
275     if (InputFilename == "-")
276       OutputFilename = "-";
277     else {
278       OutputFilename = GetFileNameRoot(InputFilename);
279
280       switch (FileType) {
281       case TargetMachine::CGFT_AssemblyFile:
282         if (TargetName[0] == 'c') {
283           if (TargetName[1] == 0)
284             OutputFilename += ".cbe.c";
285           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
286             OutputFilename += ".cpp";
287           else
288             OutputFilename += ".s";
289         } else
290           OutputFilename += ".s";
291         break;
292       case TargetMachine::CGFT_ObjectFile:
293         if (OS == Triple::Win32)
294           OutputFilename += ".obj";
295         else
296           OutputFilename += ".o";
297         break;
298       case TargetMachine::CGFT_Null:
299         OutputFilename += ".null";
300         break;
301       }
302     }
303   }
304
305   // Decide if we need "binary" output.
306   bool Binary = false;
307   switch (FileType) {
308   case TargetMachine::CGFT_AssemblyFile:
309     break;
310   case TargetMachine::CGFT_ObjectFile:
311   case TargetMachine::CGFT_Null:
312     Binary = true;
313     break;
314   }
315
316   // Open the file.
317   std::string error;
318   unsigned OpenFlags = 0;
319   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
320   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
321                                                  OpenFlags);
322   if (!error.empty()) {
323     errs() << error << '\n';
324     delete FDOut;
325     return 0;
326   }
327
328   return FDOut;
329 }
330
331 // main - Entry point for the llc compiler.
332 //
333 int main(int argc, char **argv) {
334   sys::PrintStackTraceOnErrorSignal();
335   PrettyStackTraceProgram X(argc, argv);
336
337   // Enable debug stream buffering.
338   EnableDebugBuffering = true;
339
340   LLVMContext &Context = getGlobalContext();
341   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
342
343   // Initialize targets first, so that --version shows registered targets.
344   InitializeAllTargets();
345   InitializeAllTargetMCs();
346   InitializeAllAsmPrinters();
347   InitializeAllAsmParsers();
348
349   // Register the target printer for --version.
350   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
351
352   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
353
354   // Load the module to be compiled...
355   SMDiagnostic Err;
356   std::auto_ptr<Module> M;
357
358   M.reset(ParseIRFile(InputFilename, Err, Context));
359   if (M.get() == 0) {
360     Err.print(argv[0], errs());
361     return 1;
362   }
363   Module &mod = *M.get();
364
365   // If we are supposed to override the target triple, do so now.
366   if (!TargetTriple.empty())
367     mod.setTargetTriple(Triple::normalize(TargetTriple));
368
369   // Figure out the target triple.
370   Triple TheTriple(mod.getTargetTriple());
371   if (TheTriple.getTriple().empty())
372     TheTriple.setTriple(sys::getDefaultTargetTriple());
373
374   // Get the target specific parser.
375   std::string Error;
376   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
377                                                          Error);
378   if (!TheTarget) {
379     errs() << argv[0] << ": " << Error;
380     return 1;
381   }
382
383   // Package up features to be passed to target/subtarget
384   std::string FeaturesStr;
385   if (MAttrs.size()) {
386     SubtargetFeatures Features;
387     for (unsigned i = 0; i != MAttrs.size(); ++i)
388       Features.AddFeature(MAttrs[i]);
389     FeaturesStr = Features.getString();
390   }
391
392   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
393   switch (OptLevel) {
394   default:
395     errs() << argv[0] << ": invalid optimization level.\n";
396     return 1;
397   case ' ': break;
398   case '0': OLvl = CodeGenOpt::None; break;
399   case '1': OLvl = CodeGenOpt::Less; break;
400   case '2': OLvl = CodeGenOpt::Default; break;
401   case '3': OLvl = CodeGenOpt::Aggressive; break;
402   }
403
404   TargetOptions Options;
405   Options.LessPreciseFPMADOption = EnableFPMAD;
406   Options.PrintMachineCode = PrintCode;
407   Options.NoFramePointerElim = DisableFPElim;
408   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
409   Options.NoExcessFPPrecision = DisableExcessPrecision;
410   Options.UnsafeFPMath = EnableUnsafeFPMath;
411   Options.NoInfsFPMath = EnableNoInfsFPMath;
412   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
413   Options.HonorSignDependentRoundingFPMathOption =
414       EnableHonorSignDependentRoundingFPMath;
415   Options.UseSoftFloat = GenerateSoftFloatCalls;
416   if (FloatABIForCalls != FloatABI::Default)
417     Options.FloatABIType = FloatABIForCalls;
418   Options.NoZerosInBSS = DontPlaceZerosInBSS;
419   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
420   Options.DisableTailCalls = DisableTailCalls;
421   Options.StackAlignmentOverride = OverrideStackAlignment;
422   Options.RealignStack = EnableRealignStack;
423   Options.DisableJumpTables = DisableSwitchTables;
424   Options.TrapFuncName = TrapFuncName;
425   Options.PositionIndependentExecutable = EnablePIE;
426   Options.EnableSegmentedStacks = SegmentedStacks;
427
428   std::auto_ptr<TargetMachine>
429     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
430                                           MCPU, FeaturesStr, Options,
431                                           RelocModel, CMModel, OLvl));
432   assert(target.get() && "Could not allocate target machine!");
433   TargetMachine &Target = *target.get();
434
435   if (DisableDotLoc)
436     Target.setMCUseLoc(false);
437
438   if (DisableCFI)
439     Target.setMCUseCFI(false);
440
441   if (EnableDwarfDirectory)
442     Target.setMCUseDwarfDirectory(true);
443
444   if (GenerateSoftFloatCalls)
445     FloatABIForCalls = FloatABI::Soft;
446
447   // Disable .loc support for older OS X versions.
448   if (TheTriple.isMacOSX() &&
449       TheTriple.isMacOSXVersionLT(10, 6))
450     Target.setMCUseLoc(false);
451
452   // Figure out where we are going to send the output...
453   OwningPtr<tool_output_file> Out
454     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
455   if (!Out) return 1;
456
457   // Build up all of the passes that we want to do to the module.
458   PassManager PM;
459
460   // Add the target data from the target machine, if it exists, or the module.
461   if (const TargetData *TD = Target.getTargetData())
462     PM.add(new TargetData(*TD));
463   else
464     PM.add(new TargetData(&mod));
465
466   // Override default to generate verbose assembly.
467   Target.setAsmVerbosityDefault(true);
468
469   if (RelaxAll) {
470     if (FileType != TargetMachine::CGFT_ObjectFile)
471       errs() << argv[0]
472              << ": warning: ignoring -mc-relax-all because filetype != obj";
473     else
474       Target.setMCRelaxAll(true);
475   }
476
477   {
478     formatted_raw_ostream FOS(Out->os());
479
480     // Ask the target to add backend passes as necessary.
481     if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
482       errs() << argv[0] << ": target does not support generation of this"
483              << " file type!\n";
484       return 1;
485     }
486
487     // Before executing passes, print the final values of the LLVM options.
488     cl::PrintOptionValues();
489
490     PM.run(mod);
491   }
492
493   // Declare success.
494   Out->keep();
495
496   return 0;
497 }