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