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/IRReader/IRReader.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/PluginLoader.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/ToolOutputFile.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
49 // General options for llc. Other pass-specific options are specified
50 // within the corresponding llc passes, and target-specific options
51 // and back-end code generation options are specified with the target machine.
53 static cl::opt<std::string>
54 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
56 static cl::opt<std::string>
57 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
59 static cl::opt<unsigned>
60 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
62 cl::desc("Repeat compilation N times for timing"));
65 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
66 cl::desc("Disable integrated assembler"));
68 // Determine optimization level.
71 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
77 static cl::opt<std::string>
78 TargetTriple("mtriple", cl::desc("Override target triple for module"));
80 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
81 cl::desc("Do not verify input module"));
83 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
84 cl::desc("Disable simplify-libcalls"));
86 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
87 cl::desc("Show encoding in .s output"));
89 static cl::opt<bool> EnableDwarfDirectory(
90 "enable-dwarf-directory", cl::Hidden,
91 cl::desc("Use .file directives with an explicit directory."));
93 static cl::opt<bool> AsmVerbose("asm-verbose",
94 cl::desc("Add comments to directives."),
97 static int compileModule(char **, LLVMContext &);
99 static std::unique_ptr<tool_output_file>
100 GetOutputStream(const char *TargetName, Triple::OSType OS,
101 const char *ProgName) {
102 // If we don't yet have an output filename, make one.
103 if (OutputFilename.empty()) {
104 if (InputFilename == "-")
105 OutputFilename = "-";
107 // If InputFilename ends in .bc or .ll, remove it.
108 StringRef IFN = InputFilename;
109 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
110 OutputFilename = IFN.drop_back(3);
112 OutputFilename = IFN;
115 case TargetMachine::CGFT_AssemblyFile:
116 if (TargetName[0] == 'c') {
117 if (TargetName[1] == 0)
118 OutputFilename += ".cbe.c";
119 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
120 OutputFilename += ".cpp";
122 OutputFilename += ".s";
124 OutputFilename += ".s";
126 case TargetMachine::CGFT_ObjectFile:
127 if (OS == Triple::Win32)
128 OutputFilename += ".obj";
130 OutputFilename += ".o";
132 case TargetMachine::CGFT_Null:
133 OutputFilename += ".null";
139 // Decide if we need "binary" output.
142 case TargetMachine::CGFT_AssemblyFile:
144 case TargetMachine::CGFT_ObjectFile:
145 case TargetMachine::CGFT_Null:
152 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
154 OpenFlags |= sys::fs::F_Text;
155 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
158 errs() << EC.message() << '\n';
165 // main - Entry point for the llc compiler.
167 int main(int argc, char **argv) {
168 sys::PrintStackTraceOnErrorSignal();
169 PrettyStackTraceProgram X(argc, argv);
171 // Enable debug stream buffering.
172 EnableDebugBuffering = true;
174 LLVMContext &Context = getGlobalContext();
175 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
177 // Initialize targets first, so that --version shows registered targets.
178 InitializeAllTargets();
179 InitializeAllTargetMCs();
180 InitializeAllAsmPrinters();
181 InitializeAllAsmParsers();
183 // Initialize codegen and IR passes used by llc so that the -print-after,
184 // -print-before, and -stop-after options work.
185 PassRegistry *Registry = PassRegistry::getPassRegistry();
186 initializeCore(*Registry);
187 initializeCodeGen(*Registry);
188 initializeLoopStrengthReducePass(*Registry);
189 initializeLowerIntrinsicsPass(*Registry);
190 initializeUnreachableBlockElimPass(*Registry);
192 // Register the target printer for --version.
193 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
195 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
197 // Compile the module TimeCompilations times to give better compile time
199 for (unsigned I = TimeCompilations; I; --I)
200 if (int RetVal = compileModule(argv, Context))
205 static int compileModule(char **argv, LLVMContext &Context) {
206 // Load the module to be compiled...
208 std::unique_ptr<Module> M;
211 bool SkipModule = MCPU == "help" ||
212 (!MAttrs.empty() && MAttrs.front() == "help");
214 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
215 // this will set the CPU to an empty string which tells the target to
216 // pick a basic default.
217 if (MCPU == "native")
218 MCPU = sys::getHostCPUName();
220 // If user just wants to list available options, skip module loading
222 M = parseIRFile(InputFilename, Err, Context);
224 Err.print(argv[0], errs());
228 // If we are supposed to override the target triple, do so now.
229 if (!TargetTriple.empty())
230 M->setTargetTriple(Triple::normalize(TargetTriple));
231 TheTriple = Triple(M->getTargetTriple());
233 TheTriple = Triple(Triple::normalize(TargetTriple));
236 if (TheTriple.getTriple().empty())
237 TheTriple.setTriple(sys::getDefaultTargetTriple());
239 // Get the target specific parser.
241 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
244 errs() << argv[0] << ": " << Error;
248 // Package up features to be passed to target/subtarget
249 std::string FeaturesStr;
251 SubtargetFeatures Features;
252 for (unsigned i = 0; i != MAttrs.size(); ++i)
253 Features.AddFeature(MAttrs[i]);
254 FeaturesStr = Features.getString();
257 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
260 errs() << argv[0] << ": invalid optimization level.\n";
263 case '0': OLvl = CodeGenOpt::None; break;
264 case '1': OLvl = CodeGenOpt::Less; break;
265 case '2': OLvl = CodeGenOpt::Default; break;
266 case '3': OLvl = CodeGenOpt::Aggressive; break;
269 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
270 Options.DisableIntegratedAS = NoIntegratedAssembler;
271 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
272 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
273 Options.MCOptions.AsmVerbose = AsmVerbose;
275 std::unique_ptr<TargetMachine> Target(
276 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
277 Options, RelocModel, CMModel, OLvl));
278 assert(Target && "Could not allocate target machine!");
280 // If we don't have a module then just exit now. We do this down
281 // here since the CPU/Feature help is underneath the target machine
286 assert(M && "Should have exited if we didn't have a module!");
288 if (GenerateSoftFloatCalls)
289 FloatABIForCalls = FloatABI::Soft;
291 // Figure out where we are going to send the output.
292 std::unique_ptr<tool_output_file> Out =
293 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
296 // Build up all of the passes that we want to do to the module.
297 legacy::PassManager PM;
299 // Add an appropriate TargetLibraryInfo pass for the module's triple.
300 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
302 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
303 if (DisableSimplifyLibCalls)
304 TLII.disableAllFunctions();
305 PM.add(new TargetLibraryInfoWrapperPass(TLII));
307 // Add the target data from the target machine, if it exists, or the module.
308 if (const DataLayout *DL = Target->getDataLayout())
309 M->setDataLayout(*DL);
311 if (RelaxAll.getNumOccurrences() > 0 &&
312 FileType != TargetMachine::CGFT_ObjectFile)
314 << ": warning: ignoring -mc-relax-all because filetype != obj";
317 formatted_raw_ostream FOS(Out->os());
319 AnalysisID StartAfterID = nullptr;
320 AnalysisID StopAfterID = nullptr;
321 const PassRegistry *PR = PassRegistry::getPassRegistry();
322 if (!StartAfter.empty()) {
323 const PassInfo *PI = PR->getPassInfo(StartAfter);
325 errs() << argv[0] << ": start-after pass is not registered.\n";
328 StartAfterID = PI->getTypeInfo();
330 if (!StopAfter.empty()) {
331 const PassInfo *PI = PR->getPassInfo(StopAfter);
333 errs() << argv[0] << ": stop-after pass is not registered.\n";
336 StopAfterID = PI->getTypeInfo();
339 // Ask the target to add backend passes as necessary.
340 if (Target->addPassesToEmitFile(PM, FOS, FileType, NoVerify,
341 StartAfterID, StopAfterID)) {
342 errs() << argv[0] << ": target does not support generation of this"
347 // Before executing passes, print the final values of the LLVM options.
348 cl::PrintOptionValues();