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
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/IRPrintingPasses.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/LegacyPassManager.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/IRReader/IRReader.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/PluginLoader.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetSubtargetInfo.h"
47 #include <memory>
48 using namespace llvm;
49
50 // General options for llc. Other pass-specific options are specified
51 // within the corresponding llc passes, and target-specific options
52 // and back-end code generation options are specified with the target machine.
53 //
54 static cl::opt<std::string>
55 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
56
57 static cl::opt<std::string>
58 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
59
60 static cl::opt<unsigned>
61 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
62 cl::value_desc("N"),
63 cl::desc("Repeat compilation N times for timing"));
64
65 static cl::opt<bool>
66 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
67 cl::desc("Disable integrated assembler"));
68
69 // Determine optimization level.
70 static cl::opt<char>
71 OptLevel("O",
72 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
73 "(default = '-O2')"),
74 cl::Prefix,
75 cl::ZeroOrMore,
76 cl::init(' '));
77
78 static cl::opt<std::string>
79 TargetTriple("mtriple", cl::desc("Override target triple for module"));
80
81 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
82 cl::desc("Do not verify input module"));
83
84 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
85 cl::desc("Disable simplify-libcalls"));
86
87 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
88 cl::desc("Show encoding in .s output"));
89
90 static cl::opt<bool> EnableDwarfDirectory(
91 "enable-dwarf-directory", cl::Hidden,
92 cl::desc("Use .file directives with an explicit directory."));
93
94 static cl::opt<bool> AsmVerbose("asm-verbose",
95 cl::desc("Add comments to directives."),
96 cl::init(true));
97
98 static int compileModule(char **, LLVMContext &);
99
100 static std::unique_ptr<tool_output_file>
GetOutputStream(const char * TargetName,Triple::OSType OS,const char * ProgName)101 GetOutputStream(const char *TargetName, Triple::OSType OS,
102 const char *ProgName) {
103 // If we don't yet have an output filename, make one.
104 if (OutputFilename.empty()) {
105 if (InputFilename == "-")
106 OutputFilename = "-";
107 else {
108 // If InputFilename ends in .bc or .ll, remove it.
109 StringRef IFN = InputFilename;
110 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
111 OutputFilename = IFN.drop_back(3);
112 else
113 OutputFilename = IFN;
114
115 switch (FileType) {
116 case TargetMachine::CGFT_AssemblyFile:
117 if (TargetName[0] == 'c') {
118 if (TargetName[1] == 0)
119 OutputFilename += ".cbe.c";
120 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
121 OutputFilename += ".cpp";
122 else
123 OutputFilename += ".s";
124 } else
125 OutputFilename += ".s";
126 break;
127 case TargetMachine::CGFT_ObjectFile:
128 if (OS == Triple::Win32)
129 OutputFilename += ".obj";
130 else
131 OutputFilename += ".o";
132 break;
133 case TargetMachine::CGFT_Null:
134 OutputFilename += ".null";
135 break;
136 }
137 }
138 }
139
140 // Decide if we need "binary" output.
141 bool Binary = false;
142 switch (FileType) {
143 case TargetMachine::CGFT_AssemblyFile:
144 break;
145 case TargetMachine::CGFT_ObjectFile:
146 case TargetMachine::CGFT_Null:
147 Binary = true;
148 break;
149 }
150
151 // Open the file.
152 std::error_code EC;
153 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
154 if (!Binary)
155 OpenFlags |= sys::fs::F_Text;
156 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
157 OpenFlags);
158 if (EC) {
159 errs() << EC.message() << '\n';
160 return nullptr;
161 }
162
163 return FDOut;
164 }
165
166 // main - Entry point for the llc compiler.
167 //
main(int argc,char ** argv)168 int main(int argc, char **argv) {
169 sys::PrintStackTraceOnErrorSignal();
170 PrettyStackTraceProgram X(argc, argv);
171
172 // Enable debug stream buffering.
173 EnableDebugBuffering = true;
174
175 LLVMContext &Context = getGlobalContext();
176 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
177
178 // Initialize targets first, so that --version shows registered targets.
179 InitializeAllTargets();
180 InitializeAllTargetMCs();
181 InitializeAllAsmPrinters();
182 InitializeAllAsmParsers();
183
184 // Initialize codegen and IR passes used by llc so that the -print-after,
185 // -print-before, and -stop-after options work.
186 PassRegistry *Registry = PassRegistry::getPassRegistry();
187 initializeCore(*Registry);
188 initializeCodeGen(*Registry);
189 initializeLoopStrengthReducePass(*Registry);
190 initializeLowerIntrinsicsPass(*Registry);
191 initializeUnreachableBlockElimPass(*Registry);
192
193 // Register the target printer for --version.
194 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
195
196 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
197
198 // Compile the module TimeCompilations times to give better compile time
199 // metrics.
200 for (unsigned I = TimeCompilations; I; --I)
201 if (int RetVal = compileModule(argv, Context))
202 return RetVal;
203 return 0;
204 }
205
compileModule(char ** argv,LLVMContext & Context)206 static int compileModule(char **argv, LLVMContext &Context) {
207 // Load the module to be compiled...
208 SMDiagnostic Err;
209 std::unique_ptr<Module> M;
210 Triple TheTriple;
211
212 bool SkipModule = MCPU == "help" ||
213 (!MAttrs.empty() && MAttrs.front() == "help");
214
215 // If user just wants to list available options, skip module loading
216 if (!SkipModule) {
217 M = parseIRFile(InputFilename, Err, Context);
218 if (!M) {
219 Err.print(argv[0], errs());
220 return 1;
221 }
222
223 // Verify module immediately to catch problems before doInitialization() is
224 // called on any passes.
225 if (!NoVerify && verifyModule(*M, &errs())) {
226 errs() << argv[0] << ": " << InputFilename
227 << ": error: input module is broken!\n";
228 return 1;
229 }
230
231 // If we are supposed to override the target triple, do so now.
232 if (!TargetTriple.empty())
233 M->setTargetTriple(Triple::normalize(TargetTriple));
234 TheTriple = Triple(M->getTargetTriple());
235 } else {
236 TheTriple = Triple(Triple::normalize(TargetTriple));
237 }
238
239 if (TheTriple.getTriple().empty())
240 TheTriple.setTriple(sys::getDefaultTargetTriple());
241
242 // Get the target specific parser.
243 std::string Error;
244 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
245 Error);
246 if (!TheTarget) {
247 errs() << argv[0] << ": " << Error;
248 return 1;
249 }
250
251 // Package up features to be passed to target/subtarget
252 std::string FeaturesStr;
253 if (!MAttrs.empty() || MCPU == "native") {
254 SubtargetFeatures Features;
255
256 // If user asked for the 'native' CPU, we need to autodetect features.
257 // This is necessary for x86 where the CPU might not support all the
258 // features the autodetected CPU name lists in the target. For example,
259 // not all Sandybridge processors support AVX.
260 if (MCPU == "native") {
261 StringMap<bool> HostFeatures;
262 if (sys::getHostCPUFeatures(HostFeatures))
263 for (auto &F : HostFeatures)
264 Features.AddFeature(F.first(), F.second);
265 }
266
267 for (unsigned i = 0; i != MAttrs.size(); ++i)
268 Features.AddFeature(MAttrs[i]);
269 FeaturesStr = Features.getString();
270 }
271
272 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
273 // this will set the CPU to an empty string which tells the target to
274 // pick a basic default.
275 if (MCPU == "native")
276 MCPU = sys::getHostCPUName();
277
278 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
279 switch (OptLevel) {
280 default:
281 errs() << argv[0] << ": invalid optimization level.\n";
282 return 1;
283 case ' ': break;
284 case '0': OLvl = CodeGenOpt::None; break;
285 case '1': OLvl = CodeGenOpt::Less; break;
286 case '2': OLvl = CodeGenOpt::Default; break;
287 case '3': OLvl = CodeGenOpt::Aggressive; break;
288 }
289
290 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
291 Options.DisableIntegratedAS = NoIntegratedAssembler;
292 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
293 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
294 Options.MCOptions.AsmVerbose = AsmVerbose;
295
296 std::unique_ptr<TargetMachine> Target(
297 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
298 Options, RelocModel, CMModel, OLvl));
299 assert(Target && "Could not allocate target machine!");
300
301 // If we don't have a module then just exit now. We do this down
302 // here since the CPU/Feature help is underneath the target machine
303 // creation.
304 if (SkipModule)
305 return 0;
306
307 assert(M && "Should have exited if we didn't have a module!");
308
309 if (GenerateSoftFloatCalls)
310 FloatABIForCalls = FloatABI::Soft;
311
312 // Figure out where we are going to send the output.
313 std::unique_ptr<tool_output_file> Out =
314 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
315 if (!Out) return 1;
316
317 // Build up all of the passes that we want to do to the module.
318 legacy::PassManager PM;
319
320 // Add an appropriate TargetLibraryInfo pass for the module's triple.
321 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
322
323 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
324 if (DisableSimplifyLibCalls)
325 TLII.disableAllFunctions();
326 PM.add(new TargetLibraryInfoWrapperPass(TLII));
327
328 // Add the target data from the target machine, if it exists, or the module.
329 if (const DataLayout *DL = Target->getDataLayout())
330 M->setDataLayout(*DL);
331
332 if (RelaxAll.getNumOccurrences() > 0 &&
333 FileType != TargetMachine::CGFT_ObjectFile)
334 errs() << argv[0]
335 << ": warning: ignoring -mc-relax-all because filetype != obj";
336
337 {
338 raw_pwrite_stream *OS = &Out->os();
339 std::unique_ptr<buffer_ostream> BOS;
340 if (FileType != TargetMachine::CGFT_AssemblyFile &&
341 !Out->os().supportsSeeking()) {
342 BOS = make_unique<buffer_ostream>(*OS);
343 OS = BOS.get();
344 }
345
346 AnalysisID StartAfterID = nullptr;
347 AnalysisID StopAfterID = nullptr;
348 const PassRegistry *PR = PassRegistry::getPassRegistry();
349 if (!StartAfter.empty()) {
350 const PassInfo *PI = PR->getPassInfo(StartAfter);
351 if (!PI) {
352 errs() << argv[0] << ": start-after pass is not registered.\n";
353 return 1;
354 }
355 StartAfterID = PI->getTypeInfo();
356 }
357 if (!StopAfter.empty()) {
358 const PassInfo *PI = PR->getPassInfo(StopAfter);
359 if (!PI) {
360 errs() << argv[0] << ": stop-after pass is not registered.\n";
361 return 1;
362 }
363 StopAfterID = PI->getTypeInfo();
364 }
365
366 // Ask the target to add backend passes as necessary.
367 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, StartAfterID,
368 StopAfterID)) {
369 errs() << argv[0] << ": target does not support generation of this"
370 << " file type!\n";
371 return 1;
372 }
373
374 // Before executing passes, print the final values of the LLVM options.
375 cl::PrintOptionValues();
376
377 PM.run(*M);
378 }
379
380 // Declare success.
381 Out->keep();
382
383 return 0;
384 }
385