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/Triple.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Pass.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/PluginLoader.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Target/TargetLibraryInfo.h"
43 #include "llvm/Target/TargetMachine.h"
47 // General options for llc. Other pass-specific options are specified
48 // within the corresponding llc passes, and target-specific options
49 // and back-end code generation options are specified with the target machine.
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
57 static cl::opt<unsigned>
58 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
60 cl::desc("Repeat compilation N times for timing"));
63 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
64 cl::desc("Disable integrated assembler"));
66 // Determine optimization level.
69 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
75 static cl::opt<std::string>
76 TargetTriple("mtriple", cl::desc("Override target triple for module"));
78 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
79 cl::desc("Do not verify input module"));
81 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
82 cl::desc("Disable simplify-libcalls"));
84 static int compileModule(char**, LLVMContext&);
86 // GetFileNameRoot - Helper function to get the basename of a filename.
87 static inline std::string
88 GetFileNameRoot(const std::string &InputFilename) {
89 std::string IFN = InputFilename;
90 std::string outputFilename;
91 int Len = IFN.length();
94 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
95 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
96 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
100 return outputFilename;
103 static tool_output_file *GetOutputStream(const char *TargetName,
105 const char *ProgName) {
106 // If we don't yet have an output filename, make one.
107 if (OutputFilename.empty()) {
108 if (InputFilename == "-")
109 OutputFilename = "-";
111 OutputFilename = GetFileNameRoot(InputFilename);
114 case TargetMachine::CGFT_AssemblyFile:
115 if (TargetName[0] == 'c') {
116 if (TargetName[1] == 0)
117 OutputFilename += ".cbe.c";
118 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
119 OutputFilename += ".cpp";
121 OutputFilename += ".s";
123 OutputFilename += ".s";
125 case TargetMachine::CGFT_ObjectFile:
126 if (OS == Triple::Win32)
127 OutputFilename += ".obj";
129 OutputFilename += ".o";
131 case TargetMachine::CGFT_Null:
132 OutputFilename += ".null";
138 // Decide if we need "binary" output.
141 case TargetMachine::CGFT_AssemblyFile:
143 case TargetMachine::CGFT_ObjectFile:
144 case TargetMachine::CGFT_Null:
151 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
153 OpenFlags |= sys::fs::F_Text;
154 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
156 if (!error.empty()) {
157 errs() << error << '\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;
209 Module *mod = nullptr;
212 bool SkipModule = MCPU == "help" ||
213 (!MAttrs.empty() && MAttrs.front() == "help");
215 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
216 // this will set the CPU to an empty string which tells the target to
217 // pick a basic default.
218 if (MCPU == "native")
219 MCPU = sys::getHostCPUName();
221 // If user just wants to list available options, skip module loading
223 M.reset(ParseIRFile(InputFilename, Err, Context));
225 if (mod == nullptr) {
226 Err.print(argv[0], errs());
230 // If we are supposed to override the target triple, do so now.
231 if (!TargetTriple.empty())
232 mod->setTargetTriple(Triple::normalize(TargetTriple));
233 TheTriple = Triple(mod->getTargetTriple());
235 TheTriple = Triple(Triple::normalize(TargetTriple));
238 if (TheTriple.getTriple().empty())
239 TheTriple.setTriple(sys::getDefaultTargetTriple());
241 // Get the target specific parser.
243 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
246 errs() << argv[0] << ": " << Error;
250 // Package up features to be passed to target/subtarget
251 std::string FeaturesStr;
253 SubtargetFeatures Features;
254 for (unsigned i = 0; i != MAttrs.size(); ++i)
255 Features.AddFeature(MAttrs[i]);
256 FeaturesStr = Features.getString();
259 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
262 errs() << argv[0] << ": invalid optimization level.\n";
265 case '0': OLvl = CodeGenOpt::None; break;
266 case '1': OLvl = CodeGenOpt::Less; break;
267 case '2': OLvl = CodeGenOpt::Default; break;
268 case '3': OLvl = CodeGenOpt::Aggressive; break;
271 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
272 Options.DisableIntegratedAS = NoIntegratedAssembler;
274 // Override default to generate verbose assembly unless we've seen the flag.
275 if (AsmVerbose.getNumOccurrences() == 0)
276 Options.MCOptions.AsmVerbose = true;
278 std::unique_ptr<TargetMachine> target(
279 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
280 Options, RelocModel, CMModel, OLvl));
281 assert(target.get() && "Could not allocate target machine!");
283 // If we don't have a module then just exit now. We do this down
284 // here since the CPU/Feature help is underneath the target machine
289 assert(mod && "Should have exited if we didn't have a module!");
290 TargetMachine &Target = *target.get();
292 if (GenerateSoftFloatCalls)
293 FloatABIForCalls = FloatABI::Soft;
295 // Figure out where we are going to send the output.
296 std::unique_ptr<tool_output_file> Out(
297 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
300 // Build up all of the passes that we want to do to the module.
303 // Add an appropriate TargetLibraryInfo pass for the module's triple.
304 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
305 if (DisableSimplifyLibCalls)
306 TLI->disableAllFunctions();
309 // Add the target data from the target machine, if it exists, or the module.
310 if (const DataLayout *DL = Target.getDataLayout())
311 mod->setDataLayout(DL);
312 PM.add(new DataLayoutPass(mod));
314 if (RelaxAll.getNumOccurrences() > 0 &&
315 FileType != TargetMachine::CGFT_ObjectFile)
317 << ": warning: ignoring -mc-relax-all because filetype != obj";
320 formatted_raw_ostream FOS(Out->os());
322 AnalysisID StartAfterID = nullptr;
323 AnalysisID StopAfterID = nullptr;
324 const PassRegistry *PR = PassRegistry::getPassRegistry();
325 if (!StartAfter.empty()) {
326 const PassInfo *PI = PR->getPassInfo(StartAfter);
328 errs() << argv[0] << ": start-after pass is not registered.\n";
331 StartAfterID = PI->getTypeInfo();
333 if (!StopAfter.empty()) {
334 const PassInfo *PI = PR->getPassInfo(StopAfter);
336 errs() << argv[0] << ": stop-after pass is not registered.\n";
339 StopAfterID = PI->getTypeInfo();
342 // Ask the target to add backend passes as necessary.
343 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
344 StartAfterID, StopAfterID)) {
345 errs() << argv[0] << ": target does not support generation of this"
350 // Before executing passes, print the final values of the LLVM options.
351 cl::PrintOptionValues();