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/CodeGen/MIRParser/MIRParser.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
57 // General options for llc. Other pass-specific options are specified
58 // within the corresponding llc passes, and target-specific options
59 // and back-end code generation options are specified with the target machine.
61 static cl::opt<std::string>
62 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
64 static cl::opt<std::string>
65 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
67 static cl::opt<unsigned>
68 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
70 cl::desc("Repeat compilation N times for timing"));
73 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
74 cl::desc("Disable integrated assembler"));
77 PreserveComments("preserve-as-comments", cl::Hidden,
78 cl::desc("Preserve Comments in outputted assembly"),
81 // Determine optimization level.
84 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
90 static cl::opt<std::string>
91 TargetTriple("mtriple", cl::desc("Override target triple for module"));
93 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
94 cl::desc("Do not verify input module"));
96 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
97 cl::desc("Disable simplify-libcalls"));
99 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
100 cl::desc("Show encoding in .s output"));
102 static cl::opt<bool> EnableDwarfDirectory(
103 "enable-dwarf-directory", cl::Hidden,
104 cl::desc("Use .file directives with an explicit directory."));
106 static cl::opt<bool> AsmVerbose("asm-verbose",
107 cl::desc("Add comments to directives."),
111 CompileTwice("compile-twice", cl::Hidden,
112 cl::desc("Run everything twice, re-using the same pass "
113 "manager and verify the result is the same."),
116 static cl::opt<bool> DiscardValueNames(
117 "discard-value-names",
118 cl::desc("Discard names from Value (other than GlobalValue)."),
119 cl::init(false), cl::Hidden);
122 static ManagedStatic<std::vector<std::string>> RunPassNames;
124 struct RunPassOption {
125 void operator=(const std::string &Val) const {
128 SmallVector<StringRef, 8> PassNames;
129 StringRef(Val).split(PassNames, ',', -1, false);
130 for (auto PassName : PassNames)
131 RunPassNames->push_back(PassName);
136 static RunPassOption RunPassOpt;
138 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
140 cl::desc("Run compiler only for specified passes (comma separated list)"),
141 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
143 static int compileModule(char **, LLVMContext &);
145 static std::unique_ptr<tool_output_file>
146 GetOutputStream(const char *TargetName, Triple::OSType OS,
147 const char *ProgName) {
148 // If we don't yet have an output filename, make one.
149 if (OutputFilename.empty()) {
150 if (InputFilename == "-")
151 OutputFilename = "-";
153 // If InputFilename ends in .bc or .ll, remove it.
154 StringRef IFN = InputFilename;
155 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
156 OutputFilename = IFN.drop_back(3);
157 else if (IFN.endswith(".mir"))
158 OutputFilename = IFN.drop_back(4);
160 OutputFilename = IFN;
163 case TargetMachine::CGFT_AssemblyFile:
164 if (TargetName[0] == 'c') {
165 if (TargetName[1] == 0)
166 OutputFilename += ".cbe.c";
167 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
168 OutputFilename += ".cpp";
170 OutputFilename += ".s";
172 OutputFilename += ".s";
174 case TargetMachine::CGFT_ObjectFile:
175 if (OS == Triple::Win32)
176 OutputFilename += ".obj";
178 OutputFilename += ".o";
180 case TargetMachine::CGFT_Null:
181 OutputFilename += ".null";
187 // Decide if we need "binary" output.
190 case TargetMachine::CGFT_AssemblyFile:
192 case TargetMachine::CGFT_ObjectFile:
193 case TargetMachine::CGFT_Null:
200 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
202 OpenFlags |= sys::fs::F_Text;
203 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
206 errs() << EC.message() << '\n';
213 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
214 bool *HasError = static_cast<bool *>(Context);
215 if (DI.getSeverity() == DS_Error)
218 DiagnosticPrinterRawOStream DP(errs());
219 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
224 // main - Entry point for the llc compiler.
226 int main(int argc, char **argv) {
227 sys::PrintStackTraceOnErrorSignal(argv[0]);
228 PrettyStackTraceProgram X(argc, argv);
230 // Enable debug stream buffering.
231 EnableDebugBuffering = true;
234 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
236 // Initialize targets first, so that --version shows registered targets.
237 InitializeAllTargets();
238 InitializeAllTargetMCs();
239 InitializeAllAsmPrinters();
240 InitializeAllAsmParsers();
242 // Initialize codegen and IR passes used by llc so that the -print-after,
243 // -print-before, and -stop-after options work.
244 PassRegistry *Registry = PassRegistry::getPassRegistry();
245 initializeCore(*Registry);
246 initializeCodeGen(*Registry);
247 initializeLoopStrengthReducePass(*Registry);
248 initializeLowerIntrinsicsPass(*Registry);
249 initializeUnreachableBlockElimLegacyPassPass(*Registry);
251 // Register the target printer for --version.
252 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
254 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
256 Context.setDiscardValueNames(DiscardValueNames);
258 // Set a diagnostic handler that doesn't exit on the first error
259 bool HasError = false;
260 Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
262 // Compile the module TimeCompilations times to give better compile time
264 for (unsigned I = TimeCompilations; I; --I)
265 if (int RetVal = compileModule(argv, Context))
270 static bool addPass(PassManagerBase &PM, const char *argv0,
271 StringRef PassName, TargetPassConfig &TPC) {
272 if (PassName == "none")
275 const PassRegistry *PR = PassRegistry::getPassRegistry();
276 const PassInfo *PI = PR->getPassInfo(PassName);
278 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
283 if (PI->getTargetMachineCtor())
284 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>());
285 else if (PI->getNormalCtor())
286 P = PI->getNormalCtor()();
288 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
291 std::string Banner = std::string("After ") + std::string(P->getPassName());
293 TPC.printAndVerify(Banner);
298 static int compileModule(char **argv, LLVMContext &Context) {
299 // Load the module to be compiled...
301 std::unique_ptr<Module> M;
302 std::unique_ptr<MIRParser> MIR;
305 bool SkipModule = MCPU == "help" ||
306 (!MAttrs.empty() && MAttrs.front() == "help");
308 // If user just wants to list available options, skip module loading
310 if (StringRef(InputFilename).endswith_lower(".mir")) {
311 MIR = createMIRParserFromFile(InputFilename, Err, Context);
313 M = MIR->parseLLVMModule();
315 M = parseIRFile(InputFilename, Err, Context);
317 Err.print(argv[0], errs());
321 // Verify module immediately to catch problems before doInitialization() is
322 // called on any passes.
323 if (!NoVerify && verifyModule(*M, &errs())) {
324 errs() << argv[0] << ": " << InputFilename
325 << ": error: input module is broken!\n";
329 // If we are supposed to override the target triple, do so now.
330 if (!TargetTriple.empty())
331 M->setTargetTriple(Triple::normalize(TargetTriple));
332 TheTriple = Triple(M->getTargetTriple());
334 TheTriple = Triple(Triple::normalize(TargetTriple));
337 if (TheTriple.getTriple().empty())
338 TheTriple.setTriple(sys::getDefaultTargetTriple());
340 // Get the target specific parser.
342 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
345 errs() << argv[0] << ": " << Error;
349 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
351 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
354 errs() << argv[0] << ": invalid optimization level.\n";
357 case '0': OLvl = CodeGenOpt::None; break;
358 case '1': OLvl = CodeGenOpt::Less; break;
359 case '2': OLvl = CodeGenOpt::Default; break;
360 case '3': OLvl = CodeGenOpt::Aggressive; break;
363 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
364 Options.DisableIntegratedAS = NoIntegratedAssembler;
365 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
366 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
367 Options.MCOptions.AsmVerbose = AsmVerbose;
368 Options.MCOptions.PreserveAsmComments = PreserveComments;
370 std::unique_ptr<TargetMachine> Target(
371 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
372 Options, getRelocModel(), CMModel, OLvl));
374 assert(Target && "Could not allocate target machine!");
376 // If we don't have a module then just exit now. We do this down
377 // here since the CPU/Feature help is underneath the target machine
382 assert(M && "Should have exited if we didn't have a module!");
383 if (FloatABIForCalls != FloatABI::Default)
384 Options.FloatABIType = FloatABIForCalls;
386 // Figure out where we are going to send the output.
387 std::unique_ptr<tool_output_file> Out =
388 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
391 // Build up all of the passes that we want to do to the module.
392 legacy::PassManager PM;
394 // Add an appropriate TargetLibraryInfo pass for the module's triple.
395 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
397 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
398 if (DisableSimplifyLibCalls)
399 TLII.disableAllFunctions();
400 PM.add(new TargetLibraryInfoWrapperPass(TLII));
402 // Add the target data from the target machine, if it exists, or the module.
403 M->setDataLayout(Target->createDataLayout());
405 // Override function attributes based on CPUStr, FeaturesStr, and command line
407 setFunctionAttributes(CPUStr, FeaturesStr, *M);
409 if (RelaxAll.getNumOccurrences() > 0 &&
410 FileType != TargetMachine::CGFT_ObjectFile)
412 << ": warning: ignoring -mc-relax-all because filetype != obj";
415 raw_pwrite_stream *OS = &Out->os();
417 // Manually do the buffering rather than using buffer_ostream,
418 // so we can memcmp the contents in CompileTwice mode
419 SmallVector<char, 0> Buffer;
420 std::unique_ptr<raw_svector_ostream> BOS;
421 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
422 !Out->os().supportsSeeking()) ||
424 BOS = make_unique<raw_svector_ostream>(Buffer);
428 AnalysisID StartBeforeID = nullptr;
429 AnalysisID StartAfterID = nullptr;
430 AnalysisID StopAfterID = nullptr;
431 const PassRegistry *PR = PassRegistry::getPassRegistry();
432 if (!RunPassNames->empty()) {
433 if (!StartAfter.empty() || !StopAfter.empty()) {
434 errs() << argv[0] << ": start-after and/or stop-after passes are "
435 "redundant when run-pass is specified.\n";
439 errs() << argv[0] << ": run-pass needs a .mir input.\n";
442 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
443 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
445 LLVMTM.addMachineModuleInfo(PM);
446 LLVMTM.addMachineFunctionAnalysis(PM, MIR.get());
447 TPC.printAndVerify("");
449 for (const std::string &RunPassName : *RunPassNames) {
450 if (addPass(PM, argv[0], RunPassName, TPC))
453 PM.add(createPrintMIRPass(*OS));
455 if (!StartAfter.empty()) {
456 const PassInfo *PI = PR->getPassInfo(StartAfter);
458 errs() << argv[0] << ": start-after pass is not registered.\n";
461 StartAfterID = PI->getTypeInfo();
463 if (!StopAfter.empty()) {
464 const PassInfo *PI = PR->getPassInfo(StopAfter);
466 errs() << argv[0] << ": stop-after pass is not registered.\n";
469 StopAfterID = PI->getTypeInfo();
472 // Ask the target to add backend passes as necessary.
473 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
474 StartBeforeID, StartAfterID, StopAfterID,
476 errs() << argv[0] << ": target does not support generation of this"
482 // Before executing passes, print the final values of the LLVM options.
483 cl::PrintOptionValues();
485 // If requested, run the pass manager over the same module again,
486 // to catch any bugs due to persistent state in the passes. Note that
487 // opt has the same functionality, so it may be worth abstracting this out
489 SmallVector<char, 0> CompileTwiceBuffer;
491 std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
493 CompileTwiceBuffer = Buffer;
499 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
503 // Compare the two outputs and make sure they're the same
505 if (Buffer.size() != CompileTwiceBuffer.size() ||
506 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
509 << "Running the pass manager twice changed the output.\n"
510 "Writing the result of the second run to the specified output\n"
511 "To generate the one-run comparison binary, just run without\n"
512 "the compile-twice option\n";