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/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"
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.
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
52 // Determine optimization level.
55 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
61 static cl::opt<std::string>
62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
64 static cl::opt<std::string>
65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
67 static cl::opt<std::string>
69 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70 cl::value_desc("cpu-name"),
73 static cl::list<std::string>
76 cl::desc("Target specific attributes (-mattr=help for details)"),
77 cl::value_desc("a1,+a2,-a3,..."));
79 static cl::opt<Reloc::Model>
80 RelocModel("relocation-model",
81 cl::desc("Choose relocation model"),
82 cl::init(Reloc::Default),
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"),
94 static cl::opt<llvm::CodeModel::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",
102 clEnumValN(CodeModel::Kernel, "kernel",
103 "Kernel code model"),
104 clEnumValN(CodeModel::Medium, "medium",
105 "Medium code model"),
106 clEnumValN(CodeModel::Large, "large",
111 RelaxAll("mc-relax-all",
112 cl::desc("When used with filetype=obj, "
113 "relax all fixups in the emitted object file"));
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):"),
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"),
127 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
128 cl::desc("Do not verify input module"));
130 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
131 cl::desc("Do not use .loc entries"));
133 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
134 cl::desc("Do not use .cfi_* directives"));
136 cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
137 cl::desc("Use .file directives with an explicit directory."));
140 DisableRedZone("disable-red-zone",
141 cl::desc("Do not emit code that uses the red zone."),
145 EnableFPMAD("enable-fp-mad",
146 cl::desc("Enable less precise MAD instructions to be generated"),
150 PrintCode("print-machineinstrs",
151 cl::desc("Print generated machine code"),
155 DisableFPElim("disable-fp-elim",
156 cl::desc("Disable frame pointer elimination optimization"),
160 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
161 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
165 DisableExcessPrecision("disable-excess-fp-precision",
166 cl::desc("Disable optimizations that may increase FP precision"),
170 EnableUnsafeFPMath("enable-unsafe-fp-math",
171 cl::desc("Enable optimizations that may decrease FP precision"),
175 EnableNoInfsFPMath("enable-no-infs-fp-math",
176 cl::desc("Enable FP math optimizations that assume no +-Infs"),
180 EnableNoNaNsFPMath("enable-no-nans-fp-math",
181 cl::desc("Enable FP math optimizations that assume no NaNs"),
185 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
187 cl::desc("Force codegen to assume rounding mode can change dynamically"),
191 GenerateSoftFloatCalls("soft-float",
192 cl::desc("Generate software floating point library calls"),
195 static cl::opt<llvm::FloatABI::ABIType>
196 FloatABIForCalls("float-abi",
197 cl::desc("Choose float ABI type"),
198 cl::init(FloatABI::Default),
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)"),
209 DontPlaceZerosInBSS("nozero-initialized-in-bss",
210 cl::desc("Don't place zero-initialized symbols into bss section"),
214 EnableJITExceptionHandling("jit-enable-eh",
215 cl::desc("Emit exception handling information"),
218 // In debug builds, make this default to true.
220 #define EMIT_DEBUG false
222 #define EMIT_DEBUG true
225 EmitJitDebugInfo("jit-emit-debug",
226 cl::desc("Emit debug information to debugger"),
227 cl::init(EMIT_DEBUG));
231 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
233 cl::desc("Emit debug info objfiles to disk"),
237 EnableGuaranteedTailCallOpt("tailcallopt",
238 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
241 static cl::opt<unsigned>
242 OverrideStackAlignment("stack-alignment",
243 cl::desc("Override default stack alignment"),
247 EnableRealignStack("realign-stack",
248 cl::desc("Realign stack if needed"),
252 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
253 cl::desc("Do not generate jump tables."),
257 EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
258 cl::desc("Use strong PHI elimination."),
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"),
267 SegmentedStacks("segmented-stacks",
268 cl::desc("Use segmented stacks if possible."),
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();
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/
284 outputFilename = IFN;
286 return outputFilename;
289 static tool_output_file *GetOutputStream(const char *TargetName,
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 = "-";
297 OutputFilename = GetFileNameRoot(InputFilename);
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";
308 OutputFilename += ".s";
310 OutputFilename += ".s";
312 case TargetMachine::CGFT_ObjectFile:
313 if (OS == Triple::Win32)
314 OutputFilename += ".obj";
316 OutputFilename += ".o";
318 case TargetMachine::CGFT_Null:
319 OutputFilename += ".null";
325 // Decide if we need "binary" output.
328 default: assert(0 && "Unknown file type");
329 case TargetMachine::CGFT_AssemblyFile:
331 case TargetMachine::CGFT_ObjectFile:
332 case TargetMachine::CGFT_Null:
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,
343 if (!error.empty()) {
344 errs() << error << '\n';
352 // main - Entry point for the llc compiler.
354 int main(int argc, char **argv) {
355 sys::PrintStackTraceOnErrorSignal();
356 PrettyStackTraceProgram X(argc, argv);
358 // Enable debug stream buffering.
359 EnableDebugBuffering = true;
361 LLVMContext &Context = getGlobalContext();
362 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
364 // Initialize targets first, so that --version shows registered targets.
365 InitializeAllTargets();
366 InitializeAllTargetMCs();
367 InitializeAllAsmPrinters();
368 InitializeAllAsmParsers();
370 // Register the target printer for --version.
371 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
373 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
375 // Load the module to be compiled...
377 std::auto_ptr<Module> M;
379 M.reset(ParseIRFile(InputFilename, Err, Context));
381 Err.print(argv[0], errs());
384 Module &mod = *M.get();
386 // If we are supposed to override the target triple, do so now.
387 if (!TargetTriple.empty())
388 mod.setTargetTriple(Triple::normalize(TargetTriple));
390 Triple TheTriple(mod.getTargetTriple());
391 if (TheTriple.getTriple().empty())
392 TheTriple.setTriple(sys::getDefaultTargetTriple());
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()) {
408 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
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);
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";
428 // Package up features to be passed to target/subtarget
429 std::string FeaturesStr;
431 SubtargetFeatures Features;
432 for (unsigned i = 0; i != MAttrs.size(); ++i)
433 Features.AddFeature(MAttrs[i]);
434 FeaturesStr = Features.getString();
437 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
440 errs() << argv[0] << ": invalid optimization level.\n";
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;
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;
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();
482 Target.setMCUseLoc(false);
485 Target.setMCUseCFI(false);
487 if (EnableDwarfDirectory)
488 Target.setMCUseDwarfDirectory(true);
490 if (GenerateSoftFloatCalls)
491 FloatABIForCalls = FloatABI::Soft;
493 // Disable .loc support for older OS X versions.
494 if (TheTriple.isMacOSX() &&
495 TheTriple.isMacOSXVersionLT(10, 6))
496 Target.setMCUseLoc(false);
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]));
503 // Build up all of the passes that we want to do to the module.
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));
510 PM.add(new TargetData(&mod));
512 // Override default to generate verbose assembly.
513 Target.setAsmVerbosityDefault(true);
516 if (FileType != TargetMachine::CGFT_ObjectFile)
518 << ": warning: ignoring -mc-relax-all because filetype != obj";
520 Target.setMCRelaxAll(true);
524 formatted_raw_ostream FOS(Out->os());
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"
533 // Before executing passes, print the final values of the LLVM options.
534 cl::PrintOptionValues();