Object file output from llc isn't experimental anymore.
[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"),
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 DisableFPElim("disable-fp-elim",
150   cl::desc("Disable frame pointer elimination optimization"),
151   cl::init(false));
152
153 static cl::opt<bool>
154 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
155   cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
156   cl::init(false));
157
158 static cl::opt<bool>
159 DisableExcessPrecision("disable-excess-fp-precision",
160   cl::desc("Disable optimizations that may increase FP precision"),
161   cl::init(false));
162
163 static cl::opt<bool>
164 EnableUnsafeFPMath("enable-unsafe-fp-math",
165   cl::desc("Enable optimizations that may decrease FP precision"),
166   cl::init(false));
167
168 static cl::opt<bool>
169 EnableNoInfsFPMath("enable-no-infs-fp-math",
170   cl::desc("Enable FP math optimizations that assume no +-Infs"),
171   cl::init(false));
172
173 static cl::opt<bool>
174 EnableNoNaNsFPMath("enable-no-nans-fp-math",
175   cl::desc("Enable FP math optimizations that assume no NaNs"),
176   cl::init(false));
177
178 static cl::opt<bool>
179 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
180   cl::Hidden,
181   cl::desc("Force codegen to assume rounding mode can change dynamically"),
182   cl::init(false));
183
184 static cl::opt<bool>
185 GenerateSoftFloatCalls("soft-float",
186   cl::desc("Generate software floating point library calls"),
187   cl::init(false));
188
189 static cl::opt<llvm::FloatABI::ABIType>
190 FloatABIForCalls("float-abi",
191   cl::desc("Choose float ABI type"),
192   cl::init(FloatABI::Default),
193   cl::values(
194     clEnumValN(FloatABI::Default, "default",
195                "Target default float ABI type"),
196     clEnumValN(FloatABI::Soft, "soft",
197                "Soft float ABI (implied by -soft-float)"),
198     clEnumValN(FloatABI::Hard, "hard",
199                "Hard float ABI (uses FP registers)"),
200     clEnumValEnd));
201
202 static cl::opt<bool>
203 DontPlaceZerosInBSS("nozero-initialized-in-bss",
204   cl::desc("Don't place zero-initialized symbols into bss section"),
205   cl::init(false));
206
207 static cl::opt<bool>
208 EnableGuaranteedTailCallOpt("tailcallopt",
209   cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
210   cl::init(false));
211
212 static cl::opt<bool>
213 DisableTailCalls("disable-tail-calls",
214   cl::desc("Never emit tail calls"),
215   cl::init(false));
216
217 static cl::opt<unsigned>
218 OverrideStackAlignment("stack-alignment",
219   cl::desc("Override default stack alignment"),
220   cl::init(0));
221
222 static cl::opt<bool>
223 EnableRealignStack("realign-stack",
224   cl::desc("Realign stack if needed"),
225   cl::init(true));
226
227 static cl::opt<bool>
228 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
229   cl::desc("Do not generate jump tables."),
230   cl::init(false));
231
232 static cl::opt<std::string>
233 TrapFuncName("trap-func", cl::Hidden,
234   cl::desc("Emit a call to trap function rather than a trap instruction"),
235   cl::init(""));
236
237 static cl::opt<bool>
238 EnablePIE("enable-pie",
239   cl::desc("Assume the creation of a position independent executable."),
240   cl::init(false));
241
242 static cl::opt<bool>
243 SegmentedStacks("segmented-stacks",
244   cl::desc("Use segmented stacks if possible."),
245   cl::init(false));
246
247
248 // GetFileNameRoot - Helper function to get the basename of a filename.
249 static inline std::string
250 GetFileNameRoot(const std::string &InputFilename) {
251   std::string IFN = InputFilename;
252   std::string outputFilename;
253   int Len = IFN.length();
254   if ((Len > 2) &&
255       IFN[Len-3] == '.' &&
256       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
257        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
258     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
259   } else {
260     outputFilename = IFN;
261   }
262   return outputFilename;
263 }
264
265 static tool_output_file *GetOutputStream(const char *TargetName,
266                                          Triple::OSType OS,
267                                          const char *ProgName) {
268   // If we don't yet have an output filename, make one.
269   if (OutputFilename.empty()) {
270     if (InputFilename == "-")
271       OutputFilename = "-";
272     else {
273       OutputFilename = GetFileNameRoot(InputFilename);
274
275       switch (FileType) {
276       case TargetMachine::CGFT_AssemblyFile:
277         if (TargetName[0] == 'c') {
278           if (TargetName[1] == 0)
279             OutputFilename += ".cbe.c";
280           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
281             OutputFilename += ".cpp";
282           else
283             OutputFilename += ".s";
284         } else
285           OutputFilename += ".s";
286         break;
287       case TargetMachine::CGFT_ObjectFile:
288         if (OS == Triple::Win32)
289           OutputFilename += ".obj";
290         else
291           OutputFilename += ".o";
292         break;
293       case TargetMachine::CGFT_Null:
294         OutputFilename += ".null";
295         break;
296       }
297     }
298   }
299
300   // Decide if we need "binary" output.
301   bool Binary = false;
302   switch (FileType) {
303   case TargetMachine::CGFT_AssemblyFile:
304     break;
305   case TargetMachine::CGFT_ObjectFile:
306   case TargetMachine::CGFT_Null:
307     Binary = true;
308     break;
309   }
310
311   // Open the file.
312   std::string error;
313   unsigned OpenFlags = 0;
314   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
315   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
316                                                  OpenFlags);
317   if (!error.empty()) {
318     errs() << error << '\n';
319     delete FDOut;
320     return 0;
321   }
322
323   return FDOut;
324 }
325
326 // main - Entry point for the llc compiler.
327 //
328 int main(int argc, char **argv) {
329   sys::PrintStackTraceOnErrorSignal();
330   PrettyStackTraceProgram X(argc, argv);
331
332   // Enable debug stream buffering.
333   EnableDebugBuffering = true;
334
335   LLVMContext &Context = getGlobalContext();
336   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
337
338   // Initialize targets first, so that --version shows registered targets.
339   InitializeAllTargets();
340   InitializeAllTargetMCs();
341   InitializeAllAsmPrinters();
342   InitializeAllAsmParsers();
343
344   // Register the target printer for --version.
345   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
346
347   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
348
349   // Load the module to be compiled...
350   SMDiagnostic Err;
351   std::auto_ptr<Module> M;
352
353   M.reset(ParseIRFile(InputFilename, Err, Context));
354   if (M.get() == 0) {
355     Err.print(argv[0], errs());
356     return 1;
357   }
358   Module &mod = *M.get();
359
360   // If we are supposed to override the target triple, do so now.
361   if (!TargetTriple.empty())
362     mod.setTargetTriple(Triple::normalize(TargetTriple));
363
364   // Figure out the target triple.
365   Triple TheTriple(mod.getTargetTriple());
366   if (TheTriple.getTriple().empty())
367     TheTriple.setTriple(sys::getDefaultTargetTriple());
368
369   // Get the target specific parser.
370   std::string Error;
371   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
372                                                          Error);
373   if (!TheTarget) {
374     errs() << argv[0] << ": " << Error;
375     return 1;
376   }
377
378   // Package up features to be passed to target/subtarget
379   std::string FeaturesStr;
380   if (MAttrs.size()) {
381     SubtargetFeatures Features;
382     for (unsigned i = 0; i != MAttrs.size(); ++i)
383       Features.AddFeature(MAttrs[i]);
384     FeaturesStr = Features.getString();
385   }
386
387   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
388   switch (OptLevel) {
389   default:
390     errs() << argv[0] << ": invalid optimization level.\n";
391     return 1;
392   case ' ': break;
393   case '0': OLvl = CodeGenOpt::None; break;
394   case '1': OLvl = CodeGenOpt::Less; break;
395   case '2': OLvl = CodeGenOpt::Default; break;
396   case '3': OLvl = CodeGenOpt::Aggressive; break;
397   }
398
399   TargetOptions Options;
400   Options.LessPreciseFPMADOption = EnableFPMAD;
401   Options.NoFramePointerElim = DisableFPElim;
402   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
403   Options.NoExcessFPPrecision = DisableExcessPrecision;
404   Options.UnsafeFPMath = EnableUnsafeFPMath;
405   Options.NoInfsFPMath = EnableNoInfsFPMath;
406   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
407   Options.HonorSignDependentRoundingFPMathOption =
408       EnableHonorSignDependentRoundingFPMath;
409   Options.UseSoftFloat = GenerateSoftFloatCalls;
410   if (FloatABIForCalls != FloatABI::Default)
411     Options.FloatABIType = FloatABIForCalls;
412   Options.NoZerosInBSS = DontPlaceZerosInBSS;
413   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
414   Options.DisableTailCalls = DisableTailCalls;
415   Options.StackAlignmentOverride = OverrideStackAlignment;
416   Options.RealignStack = EnableRealignStack;
417   Options.DisableJumpTables = DisableSwitchTables;
418   Options.TrapFuncName = TrapFuncName;
419   Options.PositionIndependentExecutable = EnablePIE;
420   Options.EnableSegmentedStacks = SegmentedStacks;
421
422   std::auto_ptr<TargetMachine>
423     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
424                                           MCPU, FeaturesStr, Options,
425                                           RelocModel, CMModel, OLvl));
426   assert(target.get() && "Could not allocate target machine!");
427   TargetMachine &Target = *target.get();
428
429   if (DisableDotLoc)
430     Target.setMCUseLoc(false);
431
432   if (DisableCFI)
433     Target.setMCUseCFI(false);
434
435   if (EnableDwarfDirectory)
436     Target.setMCUseDwarfDirectory(true);
437
438   if (GenerateSoftFloatCalls)
439     FloatABIForCalls = FloatABI::Soft;
440
441   // Disable .loc support for older OS X versions.
442   if (TheTriple.isMacOSX() &&
443       TheTriple.isMacOSXVersionLT(10, 6))
444     Target.setMCUseLoc(false);
445
446   // Figure out where we are going to send the output...
447   OwningPtr<tool_output_file> Out
448     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
449   if (!Out) return 1;
450
451   // Build up all of the passes that we want to do to the module.
452   PassManager PM;
453
454   // Add the target data from the target machine, if it exists, or the module.
455   if (const TargetData *TD = Target.getTargetData())
456     PM.add(new TargetData(*TD));
457   else
458     PM.add(new TargetData(&mod));
459
460   // Override default to generate verbose assembly.
461   Target.setAsmVerbosityDefault(true);
462
463   if (RelaxAll) {
464     if (FileType != TargetMachine::CGFT_ObjectFile)
465       errs() << argv[0]
466              << ": warning: ignoring -mc-relax-all because filetype != obj";
467     else
468       Target.setMCRelaxAll(true);
469   }
470
471   {
472     formatted_raw_ostream FOS(Out->os());
473
474     // Ask the target to add backend passes as necessary.
475     if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
476       errs() << argv[0] << ": target does not support generation of this"
477              << " file type!\n";
478       return 1;
479     }
480
481     // Before executing passes, print the final values of the LLVM options.
482     cl::PrintOptionValues();
483
484     PM.run(mod);
485   }
486
487   // Declare success.
488   Out->keep();
489
490   return 0;
491 }