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/Analysis/Verifier.h"
22 #include "llvm/Support/IRReader.h"
23 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
24 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
25 #include "llvm/Config/config.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/System/Host.h"
33 #include "llvm/System/Signals.h"
34 #include "llvm/Target/SubtargetFeature.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Target/TargetSelect.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,..."));
80 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
82 cl::opt<TargetMachine::CodeGenFileType>
83 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
84 cl::desc("Choose a file type (not all types are supported by all targets):"),
86 clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
87 "Emit an assembly ('.s') file"),
88 clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
89 "Emit a native object ('.o') file [experimental]"),
90 clEnumValN(TargetMachine::CGFT_Null, "null",
91 "Emit nothing, for performance testing"),
94 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
95 cl::desc("Do not verify input module"));
99 DisableRedZone("disable-red-zone",
100 cl::desc("Do not emit code that uses the red zone."),
104 NoImplicitFloats("no-implicit-float",
105 cl::desc("Don't generate implicit floating point instructions (x86-only)"),
108 // GetFileNameRoot - Helper function to get the basename of a filename.
109 static inline std::string
110 GetFileNameRoot(const std::string &InputFilename) {
111 std::string IFN = InputFilename;
112 std::string outputFilename;
113 int Len = IFN.length();
116 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
117 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
118 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
120 outputFilename = IFN;
122 return outputFilename;
125 static formatted_raw_ostream *GetOutputStream(const char *TargetName,
127 const char *ProgName) {
128 if (OutputFilename != "") {
129 if (OutputFilename == "-")
130 return new formatted_raw_ostream(outs(),
131 formatted_raw_ostream::PRESERVE_STREAM);
133 // Make sure that the Out file gets unlinked from the disk if we get a
135 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
138 raw_fd_ostream *FDOut =
139 new raw_fd_ostream(OutputFilename.c_str(), error,
140 raw_fd_ostream::F_Binary);
141 if (!error.empty()) {
142 errs() << error << '\n';
146 formatted_raw_ostream *Out =
147 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
152 if (InputFilename == "-") {
153 OutputFilename = "-";
154 return new formatted_raw_ostream(outs(),
155 formatted_raw_ostream::PRESERVE_STREAM);
158 OutputFilename = GetFileNameRoot(InputFilename);
162 default: assert(0 && "Unknown file type");
163 case TargetMachine::CGFT_AssemblyFile:
164 if (TargetName[0] == 'c') {
165 if (TargetName[1] == 0)
166 OutputFilename += ".cbe.c";
167 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
168 OutputFilename += ".cpp";
170 OutputFilename += ".s";
172 OutputFilename += ".s";
174 case TargetMachine::CGFT_ObjectFile:
175 if (OS == Triple::Win32)
176 OutputFilename += ".obj";
178 OutputFilename += ".o";
181 case TargetMachine::CGFT_Null:
182 OutputFilename += ".null";
187 // Make sure that the Out file gets unlinked from the disk if we get a
189 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
192 unsigned OpenFlags = 0;
193 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
194 raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
196 if (!error.empty()) {
197 errs() << error << '\n';
202 formatted_raw_ostream *Out =
203 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);
208 // main - Entry point for the llc compiler.
210 int main(int argc, char **argv) {
211 sys::PrintStackTraceOnErrorSignal();
212 PrettyStackTraceProgram X(argc, argv);
214 // Enable debug stream buffering.
215 EnableDebugBuffering = true;
217 LLVMContext &Context = getGlobalContext();
218 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
220 // Initialize targets first, so that --version shows registered targets.
221 InitializeAllTargets();
222 InitializeAllAsmPrinters();
223 InitializeAllAsmParsers();
225 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
227 // Load the module to be compiled...
229 std::auto_ptr<Module> M;
231 M.reset(ParseIRFile(InputFilename, Err, Context));
233 Err.Print(argv[0], errs());
236 Module &mod = *M.get();
238 // If we are supposed to override the target triple, do so now.
239 if (!TargetTriple.empty())
240 mod.setTargetTriple(TargetTriple);
242 Triple TheTriple(mod.getTargetTriple());
243 if (TheTriple.getTriple().empty())
244 TheTriple.setTriple(sys::getHostTriple());
246 // Allocate target machine. First, check whether the user has explicitly
247 // specified an architecture to compile for. If so we have to look it up by
248 // name, because it might be a backend that has no mapping to a target triple.
249 const Target *TheTarget = 0;
250 if (!MArch.empty()) {
251 for (TargetRegistry::iterator it = TargetRegistry::begin(),
252 ie = TargetRegistry::end(); it != ie; ++it) {
253 if (MArch == it->getName()) {
260 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
264 // Adjust the triple to match (if known), otherwise stick with the
265 // module/host triple.
266 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
267 if (Type != Triple::UnknownArch)
268 TheTriple.setArch(Type);
271 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
272 if (TheTarget == 0) {
273 errs() << argv[0] << ": error auto-selecting target for module '"
274 << Err << "'. Please use the -march option to explicitly "
275 << "pick a target.\n";
280 // Package up features to be passed to target/subtarget
281 std::string FeaturesStr;
282 if (MCPU.size() || MAttrs.size()) {
283 SubtargetFeatures Features;
284 Features.setCPU(MCPU);
285 for (unsigned i = 0; i != MAttrs.size(); ++i)
286 Features.AddFeature(MAttrs[i]);
287 FeaturesStr = Features.getString();
290 std::auto_ptr<TargetMachine>
291 target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
292 assert(target.get() && "Could not allocate target machine!");
293 TargetMachine &Target = *target.get();
295 // Figure out where we are going to send the output...
296 formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(),
297 TheTriple.getOS(), argv[0]);
298 if (Out == 0) return 1;
300 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
303 errs() << argv[0] << ": invalid optimization level.\n";
306 case '0': OLvl = CodeGenOpt::None; break;
307 case '1': OLvl = CodeGenOpt::Less; break;
308 case '2': OLvl = CodeGenOpt::Default; break;
309 case '3': OLvl = CodeGenOpt::Aggressive; break;
312 // Request that addPassesToEmitFile run the Verifier after running
313 // passes which modify the IR.
315 bool DisableVerify = false;
317 bool DisableVerify = true;
320 // Build up all of the passes that we want to do to the module.
323 // Add the target data from the target machine, if it exists, or the module.
324 if (const TargetData *TD = Target.getTargetData())
325 PM.add(new TargetData(*TD));
327 PM.add(new TargetData(&mod));
330 PM.add(createVerifierPass());
332 // Override default to generate verbose assembly.
333 Target.setAsmVerbosityDefault(true);
336 if (FileType != TargetMachine::CGFT_ObjectFile)
338 << ": warning: ignoring -mc-relax-all because filetype != obj";
340 Target.setMCRelaxAll(true);
343 // Ask the target to add backend passes as necessary.
344 if (Target.addPassesToEmitFile(PM, *Out, FileType, OLvl,
346 errs() << argv[0] << ": target does not support generation of this"
349 // And the Out file is empty and useless, so remove it now.
350 sys::Path(OutputFilename).eraseFromDisk();
356 // Delete the ostream.