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