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 //===----------------------------------------------------------------------===//
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"
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.
54 static cl::opt<std::string>
55 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
57 static cl::opt<std::string>
58 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
60 static cl::opt<unsigned>
61 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
63 cl::desc("Repeat compilation N times for timing"));
66 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
67 cl::desc("Disable integrated assembler"));
69 // Determine optimization level.
72 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
78 static cl::opt<std::string>
79 TargetTriple("mtriple", cl::desc("Override target triple for module"));
81 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
82 cl::desc("Do not verify input module"));
84 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
85 cl::desc("Disable simplify-libcalls"));
87 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
88 cl::desc("Show encoding in .s output"));
90 static cl::opt<bool> EnableDwarfDirectory(
91 "enable-dwarf-directory", cl::Hidden,
92 cl::desc("Use .file directives with an explicit directory."));
94 static cl::opt<bool> AsmVerbose("asm-verbose",
95 cl::desc("Add comments to directives."),
98 static int compileModule(char **, LLVMContext &);
100 static std::unique_ptr<tool_output_file>
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 = "-";
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);
113 OutputFilename = IFN;
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";
123 OutputFilename += ".s";
125 OutputFilename += ".s";
127 case TargetMachine::CGFT_ObjectFile:
128 if (OS == Triple::Win32)
129 OutputFilename += ".obj";
131 OutputFilename += ".o";
133 case TargetMachine::CGFT_Null:
134 OutputFilename += ".null";
140 // Decide if we need "binary" output.
143 case TargetMachine::CGFT_AssemblyFile:
145 case TargetMachine::CGFT_ObjectFile:
146 case TargetMachine::CGFT_Null:
153 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
155 OpenFlags |= sys::fs::F_Text;
156 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
159 errs() << EC.message() << '\n';
166 // main - Entry point for the llc compiler.
168 int main(int argc, char **argv) {
169 sys::PrintStackTraceOnErrorSignal();
170 PrettyStackTraceProgram X(argc, argv);
172 // Enable debug stream buffering.
173 EnableDebugBuffering = true;
175 LLVMContext &Context = getGlobalContext();
176 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
178 // Initialize targets first, so that --version shows registered targets.
179 InitializeAllTargets();
180 InitializeAllTargetMCs();
181 InitializeAllAsmPrinters();
182 InitializeAllAsmParsers();
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);
193 // Register the target printer for --version.
194 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
196 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
198 // Compile the module TimeCompilations times to give better compile time
200 for (unsigned I = TimeCompilations; I; --I)
201 if (int RetVal = compileModule(argv, Context))
206 static int compileModule(char **argv, LLVMContext &Context) {
207 // Load the module to be compiled...
209 std::unique_ptr<Module> M;
212 bool SkipModule = MCPU == "help" ||
213 (!MAttrs.empty() && MAttrs.front() == "help");
215 // If user just wants to list available options, skip module loading
217 M = parseIRFile(InputFilename, Err, Context);
219 Err.print(argv[0], errs());
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";
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());
236 TheTriple = Triple(Triple::normalize(TargetTriple));
239 if (TheTriple.getTriple().empty())
240 TheTriple.setTriple(sys::getDefaultTargetTriple());
242 // Get the target specific parser.
244 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
247 errs() << argv[0] << ": " << Error;
251 // Package up features to be passed to target/subtarget
252 std::string FeaturesStr;
253 if (!MAttrs.empty() || MCPU == "native") {
254 SubtargetFeatures Features;
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);
267 for (unsigned i = 0; i != MAttrs.size(); ++i)
268 Features.AddFeature(MAttrs[i]);
269 FeaturesStr = Features.getString();
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();
278 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
281 errs() << argv[0] << ": invalid optimization level.\n";
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;
290 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
291 Options.DisableIntegratedAS = NoIntegratedAssembler;
292 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
293 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
294 Options.MCOptions.AsmVerbose = AsmVerbose;
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!");
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
307 assert(M && "Should have exited if we didn't have a module!");
309 if (GenerateSoftFloatCalls)
310 FloatABIForCalls = FloatABI::Soft;
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]);
317 // Build up all of the passes that we want to do to the module.
318 legacy::PassManager PM;
320 // Add an appropriate TargetLibraryInfo pass for the module's triple.
321 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
323 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
324 if (DisableSimplifyLibCalls)
325 TLII.disableAllFunctions();
326 PM.add(new TargetLibraryInfoWrapperPass(TLII));
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);
332 if (RelaxAll.getNumOccurrences() > 0 &&
333 FileType != TargetMachine::CGFT_ObjectFile)
335 << ": warning: ignoring -mc-relax-all because filetype != obj";
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);
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);
352 errs() << argv[0] << ": start-after pass is not registered.\n";
355 StartAfterID = PI->getTypeInfo();
357 if (!StopAfter.empty()) {
358 const PassInfo *PI = PR->getPassInfo(StopAfter);
360 errs() << argv[0] << ": stop-after pass is not registered.\n";
363 StopAfterID = PI->getTypeInfo();
366 // Ask the target to add backend passes as necessary.
367 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, StartAfterID,
369 errs() << argv[0] << ": target does not support generation of this"
374 // Before executing passes, print the final values of the LLVM options.
375 cl::PrintOptionValues();