Teach LLVM about a PIE option which, when enabled on top of PIC, makes
[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 EnableJITExceptionHandling("jit-enable-eh",
214   cl::desc("Emit exception handling information"),
215   cl::init(false));
216
217 // In debug builds, make this default to true.
218 #ifdef NDEBUG
219 #define EMIT_DEBUG false
220 #else
221 #define EMIT_DEBUG true
222 #endif
223 static cl::opt<bool>
224 EmitJitDebugInfo("jit-emit-debug",
225   cl::desc("Emit debug information to debugger"),
226   cl::init(EMIT_DEBUG));
227 #undef EMIT_DEBUG
228
229 static cl::opt<bool>
230 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
231   cl::Hidden,
232   cl::desc("Emit debug info objfiles to disk"),
233   cl::init(false));
234
235 static cl::opt<bool>
236 EnableGuaranteedTailCallOpt("tailcallopt",
237   cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
238   cl::init(false));
239
240 static cl::opt<bool>
241 DisableTailCalls("disable-tail-calls",
242   cl::desc("Never emit tail calls"),
243   cl::init(false));
244
245 static cl::opt<unsigned>
246 OverrideStackAlignment("stack-alignment",
247   cl::desc("Override default stack alignment"),
248   cl::init(0));
249
250 static cl::opt<bool>
251 EnableRealignStack("realign-stack",
252   cl::desc("Realign stack if needed"),
253   cl::init(true));
254
255 static cl::opt<bool>
256 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
257   cl::desc("Do not generate jump tables."),
258   cl::init(false));
259
260 static cl::opt<std::string>
261 TrapFuncName("trap-func", cl::Hidden,
262   cl::desc("Emit a call to trap function rather than a trap instruction"),
263   cl::init(""));
264
265 static cl::opt<bool>
266 EnablePIE("enable-pie",
267   cl::desc("Assume the creation of a position independent executable."),
268   cl::init(false));
269
270 static cl::opt<bool>
271 SegmentedStacks("segmented-stacks",
272   cl::desc("Use segmented stacks if possible."),
273   cl::init(false));
274
275
276 // GetFileNameRoot - Helper function to get the basename of a filename.
277 static inline std::string
278 GetFileNameRoot(const std::string &InputFilename) {
279   std::string IFN = InputFilename;
280   std::string outputFilename;
281   int Len = IFN.length();
282   if ((Len > 2) &&
283       IFN[Len-3] == '.' &&
284       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
285        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
286     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
287   } else {
288     outputFilename = IFN;
289   }
290   return outputFilename;
291 }
292
293 static tool_output_file *GetOutputStream(const char *TargetName,
294                                          Triple::OSType OS,
295                                          const char *ProgName) {
296   // If we don't yet have an output filename, make one.
297   if (OutputFilename.empty()) {
298     if (InputFilename == "-")
299       OutputFilename = "-";
300     else {
301       OutputFilename = GetFileNameRoot(InputFilename);
302
303       switch (FileType) {
304       case TargetMachine::CGFT_AssemblyFile:
305         if (TargetName[0] == 'c') {
306           if (TargetName[1] == 0)
307             OutputFilename += ".cbe.c";
308           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
309             OutputFilename += ".cpp";
310           else
311             OutputFilename += ".s";
312         } else
313           OutputFilename += ".s";
314         break;
315       case TargetMachine::CGFT_ObjectFile:
316         if (OS == Triple::Win32)
317           OutputFilename += ".obj";
318         else
319           OutputFilename += ".o";
320         break;
321       case TargetMachine::CGFT_Null:
322         OutputFilename += ".null";
323         break;
324       }
325     }
326   }
327
328   // Decide if we need "binary" output.
329   bool Binary = false;
330   switch (FileType) {
331   case TargetMachine::CGFT_AssemblyFile:
332     break;
333   case TargetMachine::CGFT_ObjectFile:
334   case TargetMachine::CGFT_Null:
335     Binary = true;
336     break;
337   }
338
339   // Open the file.
340   std::string error;
341   unsigned OpenFlags = 0;
342   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
343   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
344                                                  OpenFlags);
345   if (!error.empty()) {
346     errs() << error << '\n';
347     delete FDOut;
348     return 0;
349   }
350
351   return FDOut;
352 }
353
354 // main - Entry point for the llc compiler.
355 //
356 int main(int argc, char **argv) {
357   sys::PrintStackTraceOnErrorSignal();
358   PrettyStackTraceProgram X(argc, argv);
359
360   // Enable debug stream buffering.
361   EnableDebugBuffering = true;
362
363   LLVMContext &Context = getGlobalContext();
364   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
365
366   // Initialize targets first, so that --version shows registered targets.
367   InitializeAllTargets();
368   InitializeAllTargetMCs();
369   InitializeAllAsmPrinters();
370   InitializeAllAsmParsers();
371
372   // Register the target printer for --version.
373   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
374
375   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
376
377   // Load the module to be compiled...
378   SMDiagnostic Err;
379   std::auto_ptr<Module> M;
380
381   M.reset(ParseIRFile(InputFilename, Err, Context));
382   if (M.get() == 0) {
383     Err.print(argv[0], errs());
384     return 1;
385   }
386   Module &mod = *M.get();
387
388   // If we are supposed to override the target triple, do so now.
389   if (!TargetTriple.empty())
390     mod.setTargetTriple(Triple::normalize(TargetTriple));
391
392   Triple TheTriple(mod.getTargetTriple());
393   if (TheTriple.getTriple().empty())
394     TheTriple.setTriple(sys::getDefaultTargetTriple());
395
396   // Allocate target machine.  First, check whether the user has explicitly
397   // specified an architecture to compile for. If so we have to look it up by
398   // name, because it might be a backend that has no mapping to a target triple.
399   const Target *TheTarget = 0;
400   if (!MArch.empty()) {
401     for (TargetRegistry::iterator it = TargetRegistry::begin(),
402            ie = TargetRegistry::end(); it != ie; ++it) {
403       if (MArch == it->getName()) {
404         TheTarget = &*it;
405         break;
406       }
407     }
408
409     if (!TheTarget) {
410       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
411       return 1;
412     }
413
414     // Adjust the triple to match (if known), otherwise stick with the
415     // module/host triple.
416     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
417     if (Type != Triple::UnknownArch)
418       TheTriple.setArch(Type);
419   } else {
420     std::string Err;
421     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
422     if (TheTarget == 0) {
423       errs() << argv[0] << ": error auto-selecting target for module '"
424              << Err << "'.  Please use the -march option to explicitly "
425              << "pick a target.\n";
426       return 1;
427     }
428   }
429
430   // Package up features to be passed to target/subtarget
431   std::string FeaturesStr;
432   if (MAttrs.size()) {
433     SubtargetFeatures Features;
434     for (unsigned i = 0; i != MAttrs.size(); ++i)
435       Features.AddFeature(MAttrs[i]);
436     FeaturesStr = Features.getString();
437   }
438
439   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
440   switch (OptLevel) {
441   default:
442     errs() << argv[0] << ": invalid optimization level.\n";
443     return 1;
444   case ' ': break;
445   case '0': OLvl = CodeGenOpt::None; break;
446   case '1': OLvl = CodeGenOpt::Less; break;
447   case '2': OLvl = CodeGenOpt::Default; break;
448   case '3': OLvl = CodeGenOpt::Aggressive; break;
449   }
450
451   TargetOptions Options;
452   Options.LessPreciseFPMADOption = EnableFPMAD;
453   Options.PrintMachineCode = PrintCode;
454   Options.NoFramePointerElim = DisableFPElim;
455   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
456   Options.NoExcessFPPrecision = DisableExcessPrecision;
457   Options.UnsafeFPMath = EnableUnsafeFPMath;
458   Options.NoInfsFPMath = EnableNoInfsFPMath;
459   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
460   Options.HonorSignDependentRoundingFPMathOption =
461       EnableHonorSignDependentRoundingFPMath;
462   Options.UseSoftFloat = GenerateSoftFloatCalls;
463   if (FloatABIForCalls != FloatABI::Default)
464     Options.FloatABIType = FloatABIForCalls;
465   Options.NoZerosInBSS = DontPlaceZerosInBSS;
466   Options.JITExceptionHandling = EnableJITExceptionHandling;
467   Options.JITEmitDebugInfo = EmitJitDebugInfo;
468   Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
469   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
470   Options.DisableTailCalls = DisableTailCalls;
471   Options.StackAlignmentOverride = OverrideStackAlignment;
472   Options.RealignStack = EnableRealignStack;
473   Options.DisableJumpTables = DisableSwitchTables;
474   Options.TrapFuncName = TrapFuncName;
475   Options.PositionIndependentExecutable = EnablePIE;
476   Options.EnableSegmentedStacks = SegmentedStacks;
477
478   std::auto_ptr<TargetMachine>
479     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
480                                           MCPU, FeaturesStr, Options,
481                                           RelocModel, CMModel, OLvl));
482   assert(target.get() && "Could not allocate target machine!");
483   TargetMachine &Target = *target.get();
484
485   if (DisableDotLoc)
486     Target.setMCUseLoc(false);
487
488   if (DisableCFI)
489     Target.setMCUseCFI(false);
490
491   if (EnableDwarfDirectory)
492     Target.setMCUseDwarfDirectory(true);
493
494   if (GenerateSoftFloatCalls)
495     FloatABIForCalls = FloatABI::Soft;
496
497   // Disable .loc support for older OS X versions.
498   if (TheTriple.isMacOSX() &&
499       TheTriple.isMacOSXVersionLT(10, 6))
500     Target.setMCUseLoc(false);
501
502   // Figure out where we are going to send the output...
503   OwningPtr<tool_output_file> Out
504     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
505   if (!Out) return 1;
506
507   // Build up all of the passes that we want to do to the module.
508   PassManager PM;
509
510   // Add the target data from the target machine, if it exists, or the module.
511   if (const TargetData *TD = Target.getTargetData())
512     PM.add(new TargetData(*TD));
513   else
514     PM.add(new TargetData(&mod));
515
516   // Override default to generate verbose assembly.
517   Target.setAsmVerbosityDefault(true);
518
519   if (RelaxAll) {
520     if (FileType != TargetMachine::CGFT_ObjectFile)
521       errs() << argv[0]
522              << ": warning: ignoring -mc-relax-all because filetype != obj";
523     else
524       Target.setMCRelaxAll(true);
525   }
526
527   {
528     formatted_raw_ostream FOS(Out->os());
529
530     // Ask the target to add backend passes as necessary.
531     if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
532       errs() << argv[0] << ": target does not support generation of this"
533              << " file type!\n";
534       return 1;
535     }
536
537     // Before executing passes, print the final values of the LLVM options.
538     cl::PrintOptionValues();
539
540     PM.run(mod);
541   }
542
543   // Declare success.
544   Out->keep();
545
546   return 0;
547 }