1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
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/Target/TargetData.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Target/TargetSelect.h"
39 #include <memory>
40 using namespace llvm;
41
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.
45 //
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52 // Determine optimization level.
53 static cl::opt<char>
54 OptLevel("O",
55 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
56 "(default = '-O2')"),
57 cl::Prefix,
58 cl::ZeroOrMore,
59 cl::init(' '));
60
61 static cl::opt<std::string>
62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
63
64 static cl::opt<std::string>
65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
66
67 static cl::opt<std::string>
68 MCPU("mcpu",
69 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70 cl::value_desc("cpu-name"),
71 cl::init(""));
72
73 static cl::list<std::string>
74 MAttrs("mattr",
75 cl::CommaSeparated,
76 cl::desc("Target specific attributes (-mattr=help for details)"),
77 cl::value_desc("a1,+a2,-a3,..."));
78
79 static cl::opt<Reloc::Model>
80 RelocModel("relocation-model",
81 cl::desc("Choose relocation model"),
82 cl::init(Reloc::Default),
83 cl::values(
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"),
92 clEnumValEnd));
93
94 static cl::opt<bool>
95 RelaxAll("mc-relax-all",
96 cl::desc("When used with filetype=obj, "
97 "relax all fixups in the emitted object file"));
98
99 cl::opt<TargetMachine::CodeGenFileType>
100 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
101 cl::desc("Choose a file type (not all types are supported by all targets):"),
102 cl::values(
103 clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
104 "Emit an assembly ('.s') file"),
105 clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
106 "Emit a native object ('.o') file [experimental]"),
107 clEnumValN(TargetMachine::CGFT_Null, "null",
108 "Emit nothing, for performance testing"),
109 clEnumValEnd));
110
111 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
112 cl::desc("Do not verify input module"));
113
114 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
115 cl::desc("Do not use .loc entries"));
116
117 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
118 cl::desc("Do not use .cfi_* directives"));
119
120 static cl::opt<bool>
121 DisableRedZone("disable-red-zone",
122 cl::desc("Do not emit code that uses the red zone."),
123 cl::init(false));
124
125 // GetFileNameRoot - Helper function to get the basename of a filename.
126 static inline std::string
GetFileNameRoot(const std::string & InputFilename)127 GetFileNameRoot(const std::string &InputFilename) {
128 std::string IFN = InputFilename;
129 std::string outputFilename;
130 int Len = IFN.length();
131 if ((Len > 2) &&
132 IFN[Len-3] == '.' &&
133 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
134 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
135 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
136 } else {
137 outputFilename = IFN;
138 }
139 return outputFilename;
140 }
141
GetOutputStream(const char * TargetName,Triple::OSType OS,const char * ProgName)142 static tool_output_file *GetOutputStream(const char *TargetName,
143 Triple::OSType OS,
144 const char *ProgName) {
145 // If we don't yet have an output filename, make one.
146 if (OutputFilename.empty()) {
147 if (InputFilename == "-")
148 OutputFilename = "-";
149 else {
150 OutputFilename = GetFileNameRoot(InputFilename);
151
152 switch (FileType) {
153 default: assert(0 && "Unknown file type");
154 case TargetMachine::CGFT_AssemblyFile:
155 if (TargetName[0] == 'c') {
156 if (TargetName[1] == 0)
157 OutputFilename += ".cbe.c";
158 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
159 OutputFilename += ".cpp";
160 else
161 OutputFilename += ".s";
162 } else
163 OutputFilename += ".s";
164 break;
165 case TargetMachine::CGFT_ObjectFile:
166 if (OS == Triple::Win32)
167 OutputFilename += ".obj";
168 else
169 OutputFilename += ".o";
170 break;
171 case TargetMachine::CGFT_Null:
172 OutputFilename += ".null";
173 break;
174 }
175 }
176 }
177
178 // Decide if we need "binary" output.
179 bool Binary = false;
180 switch (FileType) {
181 default: assert(0 && "Unknown file type");
182 case TargetMachine::CGFT_AssemblyFile:
183 break;
184 case TargetMachine::CGFT_ObjectFile:
185 case TargetMachine::CGFT_Null:
186 Binary = true;
187 break;
188 }
189
190 // Open the file.
191 std::string error;
192 unsigned OpenFlags = 0;
193 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
194 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
195 OpenFlags);
196 if (!error.empty()) {
197 errs() << error << '\n';
198 delete FDOut;
199 return 0;
200 }
201
202 return FDOut;
203 }
204
205 // main - Entry point for the llc compiler.
206 //
main(int argc,char ** argv)207 int main(int argc, char **argv) {
208 sys::PrintStackTraceOnErrorSignal();
209 PrettyStackTraceProgram X(argc, argv);
210
211 // Enable debug stream buffering.
212 EnableDebugBuffering = true;
213
214 LLVMContext &Context = getGlobalContext();
215 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
216
217 // Initialize targets first, so that --version shows registered targets.
218 InitializeAllTargets();
219 InitializeAllMCAsmInfos();
220 InitializeAllMCCodeGenInfos();
221 InitializeAllMCSubtargetInfos();
222 InitializeAllAsmPrinters();
223 InitializeAllAsmParsers();
224
225 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
226
227 // Load the module to be compiled...
228 SMDiagnostic Err;
229 std::auto_ptr<Module> M;
230
231 M.reset(ParseIRFile(InputFilename, Err, Context));
232 if (M.get() == 0) {
233 Err.Print(argv[0], errs());
234 return 1;
235 }
236 Module &mod = *M.get();
237
238 // If we are supposed to override the target triple, do so now.
239 if (!TargetTriple.empty())
240 mod.setTargetTriple(Triple::normalize(TargetTriple));
241
242 Triple TheTriple(mod.getTargetTriple());
243 if (TheTriple.getTriple().empty())
244 TheTriple.setTriple(sys::getHostTriple());
245
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()) {
254 TheTarget = &*it;
255 break;
256 }
257 }
258
259 if (!TheTarget) {
260 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
261 return 1;
262 }
263
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);
269 } else {
270 std::string Err;
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";
276 return 1;
277 }
278 }
279
280 // Package up features to be passed to target/subtarget
281 std::string FeaturesStr;
282 if (MAttrs.size()) {
283 SubtargetFeatures Features;
284 for (unsigned i = 0; i != MAttrs.size(); ++i)
285 Features.AddFeature(MAttrs[i]);
286 FeaturesStr = Features.getString();
287 }
288
289 std::auto_ptr<TargetMachine>
290 target(TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU,
291 FeaturesStr, RelocModel));
292 assert(target.get() && "Could not allocate target machine!");
293 TargetMachine &Target = *target.get();
294
295 if (DisableDotLoc)
296 Target.setMCUseLoc(false);
297
298 if (DisableCFI)
299 Target.setMCUseCFI(false);
300
301 // Disable .loc support for older OS X versions.
302 if (TheTriple.isMacOSX() &&
303 TheTriple.isMacOSXVersionLT(10, 6))
304 Target.setMCUseLoc(false);
305
306 // Figure out where we are going to send the output...
307 OwningPtr<tool_output_file> Out
308 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
309 if (!Out) return 1;
310
311 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
312 switch (OptLevel) {
313 default:
314 errs() << argv[0] << ": invalid optimization level.\n";
315 return 1;
316 case ' ': break;
317 case '0': OLvl = CodeGenOpt::None; break;
318 case '1': OLvl = CodeGenOpt::Less; break;
319 case '2': OLvl = CodeGenOpt::Default; break;
320 case '3': OLvl = CodeGenOpt::Aggressive; break;
321 }
322
323 // Build up all of the passes that we want to do to the module.
324 PassManager PM;
325
326 // Add the target data from the target machine, if it exists, or the module.
327 if (const TargetData *TD = Target.getTargetData())
328 PM.add(new TargetData(*TD));
329 else
330 PM.add(new TargetData(&mod));
331
332 // Override default to generate verbose assembly.
333 Target.setAsmVerbosityDefault(true);
334
335 if (RelaxAll) {
336 if (FileType != TargetMachine::CGFT_ObjectFile)
337 errs() << argv[0]
338 << ": warning: ignoring -mc-relax-all because filetype != obj";
339 else
340 Target.setMCRelaxAll(true);
341 }
342
343 {
344 formatted_raw_ostream FOS(Out->os());
345
346 // Ask the target to add backend passes as necessary.
347 if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
348 errs() << argv[0] << ": target does not support generation of this"
349 << " file type!\n";
350 return 1;
351 }
352
353 // Before executing passes, print the final values of the LLVM options.
354 cl::PrintOptionValues();
355
356 PM.run(mod);
357 }
358
359 // Declare success.
360 Out->keep();
361
362 return 0;
363 }
364