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"));
137 DisableRedZone("disable-red-zone",
138 cl::desc("Do not emit code that uses the red zone."),
141 // GetFileNameRoot - Helper function to get the basename of a filename.
142 static inline std::string
143 GetFileNameRoot(const std::string &InputFilename) {
144 std::string IFN = InputFilename;
145 std::string outputFilename;
146 int Len = IFN.length();
149 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
150 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
151 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
153 outputFilename = IFN;
155 return outputFilename;
158 static tool_output_file *GetOutputStream(const char *TargetName,
160 const char *ProgName) {
161 // If we don't yet have an output filename, make one.
162 if (OutputFilename.empty()) {
163 if (InputFilename == "-")
164 OutputFilename = "-";
166 OutputFilename = GetFileNameRoot(InputFilename);
169 default: assert(0 && "Unknown file type");
170 case TargetMachine::CGFT_AssemblyFile:
171 if (TargetName[0] == 'c') {
172 if (TargetName[1] == 0)
173 OutputFilename += ".cbe.c";
174 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
175 OutputFilename += ".cpp";
177 OutputFilename += ".s";
179 OutputFilename += ".s";
181 case TargetMachine::CGFT_ObjectFile:
182 if (OS == Triple::Win32)
183 OutputFilename += ".obj";
185 OutputFilename += ".o";
187 case TargetMachine::CGFT_Null:
188 OutputFilename += ".null";
194 // Decide if we need "binary" output.
197 default: assert(0 && "Unknown file type");
198 case TargetMachine::CGFT_AssemblyFile:
200 case TargetMachine::CGFT_ObjectFile:
201 case TargetMachine::CGFT_Null:
208 unsigned OpenFlags = 0;
209 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
210 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
212 if (!error.empty()) {
213 errs() << error << '\n';
221 // main - Entry point for the llc compiler.
223 int main(int argc, char **argv) {
224 sys::PrintStackTraceOnErrorSignal();
225 PrettyStackTraceProgram X(argc, argv);
227 // Enable debug stream buffering.
228 EnableDebugBuffering = true;
230 LLVMContext &Context = getGlobalContext();
231 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
233 // Initialize targets first, so that --version shows registered targets.
234 InitializeAllTargets();
235 InitializeAllTargetMCs();
236 InitializeAllAsmPrinters();
237 InitializeAllAsmParsers();
239 // Register the target printer for --version.
240 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
242 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
244 // Load the module to be compiled...
246 std::auto_ptr<Module> M;
248 M.reset(ParseIRFile(InputFilename, Err, Context));
250 Err.Print(argv[0], errs());
253 Module &mod = *M.get();
255 // If we are supposed to override the target triple, do so now.
256 if (!TargetTriple.empty())
257 mod.setTargetTriple(Triple::normalize(TargetTriple));
259 Triple TheTriple(mod.getTargetTriple());
260 if (TheTriple.getTriple().empty())
261 TheTriple.setTriple(sys::getHostTriple());
263 // Allocate target machine. First, check whether the user has explicitly
264 // specified an architecture to compile for. If so we have to look it up by
265 // name, because it might be a backend that has no mapping to a target triple.
266 const Target *TheTarget = 0;
267 if (!MArch.empty()) {
268 for (TargetRegistry::iterator it = TargetRegistry::begin(),
269 ie = TargetRegistry::end(); it != ie; ++it) {
270 if (MArch == it->getName()) {
277 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
281 // Adjust the triple to match (if known), otherwise stick with the
282 // module/host triple.
283 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
284 if (Type != Triple::UnknownArch)
285 TheTriple.setArch(Type);
288 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
289 if (TheTarget == 0) {
290 errs() << argv[0] << ": error auto-selecting target for module '"
291 << Err << "'. Please use the -march option to explicitly "
292 << "pick a target.\n";
297 // Package up features to be passed to target/subtarget
298 std::string FeaturesStr;
300 SubtargetFeatures Features;
301 for (unsigned i = 0; i != MAttrs.size(); ++i)
302 Features.AddFeature(MAttrs[i]);
303 FeaturesStr = Features.getString();
306 std::auto_ptr<TargetMachine>
307 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
309 RelocModel, CMModel));
310 assert(target.get() && "Could not allocate target machine!");
311 TargetMachine &Target = *target.get();
314 Target.setMCUseLoc(false);
317 Target.setMCUseCFI(false);
319 // Disable .loc support for older OS X versions.
320 if (TheTriple.isMacOSX() &&
321 TheTriple.isMacOSXVersionLT(10, 6))
322 Target.setMCUseLoc(false);
324 // Figure out where we are going to send the output...
325 OwningPtr<tool_output_file> Out
326 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
329 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
332 errs() << argv[0] << ": invalid optimization level.\n";
335 case '0': OLvl = CodeGenOpt::None; break;
336 case '1': OLvl = CodeGenOpt::Less; break;
337 case '2': OLvl = CodeGenOpt::Default; break;
338 case '3': OLvl = CodeGenOpt::Aggressive; break;
341 // Build up all of the passes that we want to do to the module.
344 // Add the target data from the target machine, if it exists, or the module.
345 if (const TargetData *TD = Target.getTargetData())
346 PM.add(new TargetData(*TD));
348 PM.add(new TargetData(&mod));
350 // Override default to generate verbose assembly.
351 Target.setAsmVerbosityDefault(true);
354 if (FileType != TargetMachine::CGFT_ObjectFile)
356 << ": warning: ignoring -mc-relax-all because filetype != obj";
358 Target.setMCRelaxAll(true);
362 formatted_raw_ostream FOS(Out->os());
364 // Ask the target to add backend passes as necessary.
365 if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
366 errs() << argv[0] << ": target does not support generation of this"
371 // Before executing passes, print the final values of the LLVM options.
372 cl::PrintOptionValues();