1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
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.
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51 // Determine optimization level.
54 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
60 static cl::opt<std::string>
61 TargetTriple("mtriple", cl::desc("Override target triple for module"));
63 static cl::opt<std::string>
64 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
66 static cl::opt<std::string>
68 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
69 cl::value_desc("cpu-name"),
72 static cl::list<std::string>
75 cl::desc("Target specific attributes (-mattr=help for details)"),
76 cl::value_desc("a1,+a2,-a3,..."));
78 static cl::opt<Reloc::Model>
79 RelocModel("relocation-model",
80 cl::desc("Choose relocation model"),
81 cl::init(Reloc::Default),
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"),
93 static cl::opt<llvm::CodeModel::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",
101 clEnumValN(CodeModel::Kernel, "kernel",
102 "Kernel code model"),
103 clEnumValN(CodeModel::Medium, "medium",
104 "Medium code model"),
105 clEnumValN(CodeModel::Large, "large",
110 RelaxAll("mc-relax-all",
111 cl::desc("When used with filetype=obj, "
112 "relax all fixups in the emitted object file"));
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):"),
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"),
126 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
127 cl::desc("Do not verify input module"));
129 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
130 cl::desc("Do not use .loc entries"));
132 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
133 cl::desc("Do not use .cfi_* directives"));
135 cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
136 cl::desc("Use .file directives with an explicit directory."));
139 DisableRedZone("disable-red-zone",
140 cl::desc("Do not emit code that uses the red zone."),
144 EnableFPMAD("enable-fp-mad",
145 cl::desc("Enable less precise MAD instructions to be generated"),
149 PrintCode("print-machineinstrs",
150 cl::desc("Print generated machine code"),
154 DisableFPElim("disable-fp-elim",
155 cl::desc("Disable frame pointer elimination optimization"),
159 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
160 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
164 DisableExcessPrecision("disable-excess-fp-precision",
165 cl::desc("Disable optimizations that may increase FP precision"),
169 EnableUnsafeFPMath("enable-unsafe-fp-math",
170 cl::desc("Enable optimizations that may decrease FP precision"),
174 EnableNoInfsFPMath("enable-no-infs-fp-math",
175 cl::desc("Enable FP math optimizations that assume no +-Infs"),
179 EnableNoNaNsFPMath("enable-no-nans-fp-math",
180 cl::desc("Enable FP math optimizations that assume no NaNs"),
184 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
186 cl::desc("Force codegen to assume rounding mode can change dynamically"),
190 GenerateSoftFloatCalls("soft-float",
191 cl::desc("Generate software floating point library calls"),
194 static cl::opt<llvm::FloatABI::ABIType>
195 FloatABIForCalls("float-abi",
196 cl::desc("Choose float ABI type"),
197 cl::init(FloatABI::Default),
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)"),
208 DontPlaceZerosInBSS("nozero-initialized-in-bss",
209 cl::desc("Don't place zero-initialized symbols into bss section"),
213 EnableJITExceptionHandling("jit-enable-eh",
214 cl::desc("Emit exception handling information"),
217 // In debug builds, make this default to true.
219 #define EMIT_DEBUG false
221 #define EMIT_DEBUG true
224 EmitJitDebugInfo("jit-emit-debug",
225 cl::desc("Emit debug information to debugger"),
226 cl::init(EMIT_DEBUG));
230 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
232 cl::desc("Emit debug info objfiles to disk"),
236 EnableGuaranteedTailCallOpt("tailcallopt",
237 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
240 static cl::opt<unsigned>
241 OverrideStackAlignment("stack-alignment",
242 cl::desc("Override default stack alignment"),
246 EnableRealignStack("realign-stack",
247 cl::desc("Realign stack if needed"),
251 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
252 cl::desc("Do not generate jump tables."),
256 EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
257 cl::desc("Use strong PHI elimination."),
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"),
266 SegmentedStacks("segmented-stacks",
267 cl::desc("Use segmented stacks if possible."),
271 // GetFileNameRoot - Helper function to get the basename of a filename.
272 static inline std::string
273 GetFileNameRoot(const std::string &InputFilename) {
274 std::string IFN = InputFilename;
275 std::string outputFilename;
276 int Len = IFN.length();
279 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
280 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
281 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
283 outputFilename = IFN;
285 return outputFilename;
288 static tool_output_file *GetOutputStream(const char *TargetName,
290 const char *ProgName) {
291 // If we don't yet have an output filename, make one.
292 if (OutputFilename.empty()) {
293 if (InputFilename == "-")
294 OutputFilename = "-";
296 OutputFilename = GetFileNameRoot(InputFilename);
299 case TargetMachine::CGFT_AssemblyFile:
300 if (TargetName[0] == 'c') {
301 if (TargetName[1] == 0)
302 OutputFilename += ".cbe.c";
303 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
304 OutputFilename += ".cpp";
306 OutputFilename += ".s";
308 OutputFilename += ".s";
310 case TargetMachine::CGFT_ObjectFile:
311 if (OS == Triple::Win32)
312 OutputFilename += ".obj";
314 OutputFilename += ".o";
316 case TargetMachine::CGFT_Null:
317 OutputFilename += ".null";
323 // Decide if we need "binary" output.
326 case TargetMachine::CGFT_AssemblyFile:
328 case TargetMachine::CGFT_ObjectFile:
329 case TargetMachine::CGFT_Null:
336 unsigned OpenFlags = 0;
337 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
338 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
340 if (!error.empty()) {
341 errs() << error << '\n';
349 // main - Entry point for the llc compiler.
351 int main(int argc, char **argv) {
352 sys::PrintStackTraceOnErrorSignal();
353 PrettyStackTraceProgram X(argc, argv);
355 // Enable debug stream buffering.
356 EnableDebugBuffering = true;
358 LLVMContext &Context = getGlobalContext();
359 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
361 // Initialize targets first, so that --version shows registered targets.
362 InitializeAllTargets();
363 InitializeAllTargetMCs();
364 InitializeAllAsmPrinters();
365 InitializeAllAsmParsers();
367 // Register the target printer for --version.
368 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
370 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
372 // Load the module to be compiled...
374 std::auto_ptr<Module> M;
376 M.reset(ParseIRFile(InputFilename, Err, Context));
378 Err.print(argv[0], errs());
381 Module &mod = *M.get();
383 // If we are supposed to override the target triple, do so now.
384 if (!TargetTriple.empty())
385 mod.setTargetTriple(Triple::normalize(TargetTriple));
387 Triple TheTriple(mod.getTargetTriple());
388 if (TheTriple.getTriple().empty())
389 TheTriple.setTriple(sys::getDefaultTargetTriple());
391 // Allocate target machine. First, check whether the user has explicitly
392 // specified an architecture to compile for. If so we have to look it up by
393 // name, because it might be a backend that has no mapping to a target triple.
394 const Target *TheTarget = 0;
395 if (!MArch.empty()) {
396 for (TargetRegistry::iterator it = TargetRegistry::begin(),
397 ie = TargetRegistry::end(); it != ie; ++it) {
398 if (MArch == it->getName()) {
405 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
409 // Adjust the triple to match (if known), otherwise stick with the
410 // module/host triple.
411 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
412 if (Type != Triple::UnknownArch)
413 TheTriple.setArch(Type);
416 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
417 if (TheTarget == 0) {
418 errs() << argv[0] << ": error auto-selecting target for module '"
419 << Err << "'. Please use the -march option to explicitly "
420 << "pick a target.\n";
425 // Package up features to be passed to target/subtarget
426 std::string FeaturesStr;
428 SubtargetFeatures Features;
429 for (unsigned i = 0; i != MAttrs.size(); ++i)
430 Features.AddFeature(MAttrs[i]);
431 FeaturesStr = Features.getString();
434 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
437 errs() << argv[0] << ": invalid optimization level.\n";
440 case '0': OLvl = CodeGenOpt::None; break;
441 case '1': OLvl = CodeGenOpt::Less; break;
442 case '2': OLvl = CodeGenOpt::Default; break;
443 case '3': OLvl = CodeGenOpt::Aggressive; break;
446 TargetOptions Options;
447 Options.LessPreciseFPMADOption = EnableFPMAD;
448 Options.PrintMachineCode = PrintCode;
449 Options.NoFramePointerElim = DisableFPElim;
450 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
451 Options.NoExcessFPPrecision = DisableExcessPrecision;
452 Options.UnsafeFPMath = EnableUnsafeFPMath;
453 Options.NoInfsFPMath = EnableNoInfsFPMath;
454 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
455 Options.HonorSignDependentRoundingFPMathOption =
456 EnableHonorSignDependentRoundingFPMath;
457 Options.UseSoftFloat = GenerateSoftFloatCalls;
458 if (FloatABIForCalls != FloatABI::Default)
459 Options.FloatABIType = FloatABIForCalls;
460 Options.NoZerosInBSS = DontPlaceZerosInBSS;
461 Options.JITExceptionHandling = EnableJITExceptionHandling;
462 Options.JITEmitDebugInfo = EmitJitDebugInfo;
463 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
464 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
465 Options.StackAlignmentOverride = OverrideStackAlignment;
466 Options.RealignStack = EnableRealignStack;
467 Options.DisableJumpTables = DisableSwitchTables;
468 Options.TrapFuncName = TrapFuncName;
469 Options.EnableSegmentedStacks = SegmentedStacks;
471 std::auto_ptr<TargetMachine>
472 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
473 MCPU, FeaturesStr, Options,
474 RelocModel, CMModel, OLvl));
475 assert(target.get() && "Could not allocate target machine!");
476 TargetMachine &Target = *target.get();
479 Target.setMCUseLoc(false);
482 Target.setMCUseCFI(false);
484 if (EnableDwarfDirectory)
485 Target.setMCUseDwarfDirectory(true);
487 if (GenerateSoftFloatCalls)
488 FloatABIForCalls = FloatABI::Soft;
490 // Disable .loc support for older OS X versions.
491 if (TheTriple.isMacOSX() &&
492 TheTriple.isMacOSXVersionLT(10, 6))
493 Target.setMCUseLoc(false);
495 // Figure out where we are going to send the output...
496 OwningPtr<tool_output_file> Out
497 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
500 // Build up all of the passes that we want to do to the module.
503 // Add the target data from the target machine, if it exists, or the module.
504 if (const TargetData *TD = Target.getTargetData())
505 PM.add(new TargetData(*TD));
507 PM.add(new TargetData(&mod));
509 // Override default to generate verbose assembly.
510 Target.setAsmVerbosityDefault(true);
513 if (FileType != TargetMachine::CGFT_ObjectFile)
515 << ": warning: ignoring -mc-relax-all because filetype != obj";
517 Target.setMCRelaxAll(true);
521 formatted_raw_ostream FOS(Out->os());
523 // Ask the target to add backend passes as necessary.
524 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
525 errs() << argv[0] << ": target does not support generation of this"
530 // Before executing passes, print the final values of the LLVM options.
531 cl::PrintOptionValues();