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"),
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 DisableFPElim("disable-fp-elim",
150 cl::desc("Disable frame pointer elimination optimization"),
154 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
155 cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
159 EnableUnsafeFPMath("enable-unsafe-fp-math",
160 cl::desc("Enable optimizations that may decrease FP precision"),
164 EnableNoInfsFPMath("enable-no-infs-fp-math",
165 cl::desc("Enable FP math optimizations that assume no +-Infs"),
169 EnableNoNaNsFPMath("enable-no-nans-fp-math",
170 cl::desc("Enable FP math optimizations that assume no NaNs"),
174 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
176 cl::desc("Force codegen to assume rounding mode can change dynamically"),
180 GenerateSoftFloatCalls("soft-float",
181 cl::desc("Generate software floating point library calls"),
184 static cl::opt<llvm::FloatABI::ABIType>
185 FloatABIForCalls("float-abi",
186 cl::desc("Choose float ABI type"),
187 cl::init(FloatABI::Default),
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)"),
197 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
198 FuseFPOps("fuse-fp-ops",
199 cl::desc("Enable aggresive formation of fused FP ops"),
200 cl::init(FPOpFusion::Standard),
202 clEnumValN(FPOpFusion::Fast, "fast",
203 "Fuse FP ops whenever profitable"),
204 clEnumValN(FPOpFusion::Standard, "standard",
205 "Only fuse 'blessed' FP ops."),
206 clEnumValN(FPOpFusion::Strict, "strict",
207 "Only fuse FP ops when the result won't be effected."),
211 DontPlaceZerosInBSS("nozero-initialized-in-bss",
212 cl::desc("Don't place zero-initialized symbols into bss section"),
216 EnableGuaranteedTailCallOpt("tailcallopt",
217 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
221 DisableTailCalls("disable-tail-calls",
222 cl::desc("Never emit tail calls"),
225 static cl::opt<unsigned>
226 OverrideStackAlignment("stack-alignment",
227 cl::desc("Override default stack alignment"),
231 EnableRealignStack("realign-stack",
232 cl::desc("Realign stack if needed"),
236 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
237 cl::desc("Do not generate jump tables."),
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"),
246 EnablePIE("enable-pie",
247 cl::desc("Assume the creation of a position independent executable."),
251 SegmentedStacks("segmented-stacks",
252 cl::desc("Use segmented stacks if possible."),
256 UseInitArray("use-init-array",
257 cl::desc("Use .init_array instead of .ctors."),
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();
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/
272 outputFilename = IFN;
274 return outputFilename;
277 static tool_output_file *GetOutputStream(const char *TargetName,
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 = "-";
285 OutputFilename = GetFileNameRoot(InputFilename);
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";
295 OutputFilename += ".s";
297 OutputFilename += ".s";
299 case TargetMachine::CGFT_ObjectFile:
300 if (OS == Triple::Win32)
301 OutputFilename += ".obj";
303 OutputFilename += ".o";
305 case TargetMachine::CGFT_Null:
306 OutputFilename += ".null";
312 // Decide if we need "binary" output.
315 case TargetMachine::CGFT_AssemblyFile:
317 case TargetMachine::CGFT_ObjectFile:
318 case TargetMachine::CGFT_Null:
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,
329 if (!error.empty()) {
330 errs() << error << '\n';
338 // main - Entry point for the llc compiler.
340 int main(int argc, char **argv) {
341 sys::PrintStackTraceOnErrorSignal();
342 PrettyStackTraceProgram X(argc, argv);
344 // Enable debug stream buffering.
345 EnableDebugBuffering = true;
347 LLVMContext &Context = getGlobalContext();
348 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
350 // Initialize targets first, so that --version shows registered targets.
351 InitializeAllTargets();
352 InitializeAllTargetMCs();
353 InitializeAllAsmPrinters();
354 InitializeAllAsmParsers();
356 // Register the target printer for --version.
357 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
359 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
361 // Load the module to be compiled...
363 std::auto_ptr<Module> M;
365 M.reset(ParseIRFile(InputFilename, Err, Context));
367 Err.print(argv[0], errs());
370 Module &mod = *M.get();
372 // If we are supposed to override the target triple, do so now.
373 if (!TargetTriple.empty())
374 mod.setTargetTriple(Triple::normalize(TargetTriple));
376 // Figure out the target triple.
377 Triple TheTriple(mod.getTargetTriple());
378 if (TheTriple.getTriple().empty())
379 TheTriple.setTriple(sys::getDefaultTargetTriple());
381 // Get the target specific parser.
383 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
386 errs() << argv[0] << ": " << Error;
390 // Package up features to be passed to target/subtarget
391 std::string FeaturesStr;
393 SubtargetFeatures Features;
394 for (unsigned i = 0; i != MAttrs.size(); ++i)
395 Features.AddFeature(MAttrs[i]);
396 FeaturesStr = Features.getString();
399 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
402 errs() << argv[0] << ": invalid optimization level.\n";
405 case '0': OLvl = CodeGenOpt::None; break;
406 case '1': OLvl = CodeGenOpt::Less; break;
407 case '2': OLvl = CodeGenOpt::Default; break;
408 case '3': OLvl = CodeGenOpt::Aggressive; break;
411 TargetOptions Options;
412 Options.LessPreciseFPMADOption = EnableFPMAD;
413 Options.NoFramePointerElim = DisableFPElim;
414 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
415 Options.AllowFPOpFusion = FuseFPOps;
416 Options.UnsafeFPMath = EnableUnsafeFPMath;
417 Options.NoInfsFPMath = EnableNoInfsFPMath;
418 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
419 Options.HonorSignDependentRoundingFPMathOption =
420 EnableHonorSignDependentRoundingFPMath;
421 Options.UseSoftFloat = GenerateSoftFloatCalls;
422 if (FloatABIForCalls != FloatABI::Default)
423 Options.FloatABIType = FloatABIForCalls;
424 Options.NoZerosInBSS = DontPlaceZerosInBSS;
425 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
426 Options.DisableTailCalls = DisableTailCalls;
427 Options.StackAlignmentOverride = OverrideStackAlignment;
428 Options.RealignStack = EnableRealignStack;
429 Options.DisableJumpTables = DisableSwitchTables;
430 Options.TrapFuncName = TrapFuncName;
431 Options.PositionIndependentExecutable = EnablePIE;
432 Options.EnableSegmentedStacks = SegmentedStacks;
433 Options.UseInitArray = UseInitArray;
435 std::auto_ptr<TargetMachine>
436 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
437 MCPU, FeaturesStr, Options,
438 RelocModel, CMModel, OLvl));
439 assert(target.get() && "Could not allocate target machine!");
440 TargetMachine &Target = *target.get();
443 Target.setMCUseLoc(false);
446 Target.setMCUseCFI(false);
448 if (EnableDwarfDirectory)
449 Target.setMCUseDwarfDirectory(true);
451 if (GenerateSoftFloatCalls)
452 FloatABIForCalls = FloatABI::Soft;
454 // Disable .loc support for older OS X versions.
455 if (TheTriple.isMacOSX() &&
456 TheTriple.isMacOSXVersionLT(10, 6))
457 Target.setMCUseLoc(false);
459 // Figure out where we are going to send the output...
460 OwningPtr<tool_output_file> Out
461 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
464 // Build up all of the passes that we want to do to the module.
467 // Add the target data from the target machine, if it exists, or the module.
468 if (const TargetData *TD = Target.getTargetData())
469 PM.add(new TargetData(*TD));
471 PM.add(new TargetData(&mod));
473 // Override default to generate verbose assembly.
474 Target.setAsmVerbosityDefault(true);
477 if (FileType != TargetMachine::CGFT_ObjectFile)
479 << ": warning: ignoring -mc-relax-all because filetype != obj";
481 Target.setMCRelaxAll(true);
485 formatted_raw_ostream FOS(Out->os());
487 // Ask the target to add backend passes as necessary.
488 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
489 errs() << argv[0] << ": target does not support generation of this"
494 // Before executing passes, print the final values of the LLVM options.
495 cl::PrintOptionValues();