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