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<std::string> SplitDwarfFile(
96 "Specify the name of the .dwo file to encode in the DWARF output"));
98 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
99 cl::desc("Do not verify input module"));
101 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
102 cl::desc("Disable simplify-libcalls"));
104 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
105 cl::desc("Show encoding in .s output"));
107 static cl::opt<bool> EnableDwarfDirectory(
108 "enable-dwarf-directory", cl::Hidden,
109 cl::desc("Use .file directives with an explicit directory."));
111 static cl::opt<bool> AsmVerbose("asm-verbose",
112 cl::desc("Add comments to directives."),
116 CompileTwice("compile-twice", cl::Hidden,
117 cl::desc("Run everything twice, re-using the same pass "
118 "manager and verify the result is the same."),
121 static cl::opt<bool> DiscardValueNames(
122 "discard-value-names",
123 cl::desc("Discard names from Value (other than GlobalValue)."),
124 cl::init(false), cl::Hidden);
126 static cl::opt<std::string> StopBefore("stop-before",
127 cl::desc("Stop compilation before a specific pass"),
128 cl::value_desc("pass-name"), cl::init(""));
130 static cl::opt<std::string> StopAfter("stop-after",
131 cl::desc("Stop compilation after a specific pass"),
132 cl::value_desc("pass-name"), cl::init(""));
134 static cl::opt<std::string> StartBefore("start-before",
135 cl::desc("Resume compilation before a specific pass"),
136 cl::value_desc("pass-name"), cl::init(""));
138 static cl::opt<std::string> StartAfter("start-after",
139 cl::desc("Resume compilation after a specific pass"),
140 cl::value_desc("pass-name"), cl::init(""));
142 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
144 static cl::opt<bool> PassRemarksWithHotness(
145 "pass-remarks-with-hotness",
146 cl::desc("With PGO, include profile count in optimization remarks"),
149 static cl::opt<std::string>
150 RemarksFilename("pass-remarks-output",
151 cl::desc("YAML output filename for pass remarks"),
152 cl::value_desc("filename"));
155 static ManagedStatic<std::vector<std::string>> RunPassNames;
157 struct RunPassOption {
158 void operator=(const std::string &Val) const {
161 SmallVector<StringRef, 8> PassNames;
162 StringRef(Val).split(PassNames, ',', -1, false);
163 for (auto PassName : PassNames)
164 RunPassNames->push_back(PassName);
169 static RunPassOption RunPassOpt;
171 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
173 cl::desc("Run compiler only for specified passes (comma separated list)"),
174 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
176 static int compileModule(char **, LLVMContext &);
178 static std::unique_ptr<tool_output_file>
179 GetOutputStream(const char *TargetName, Triple::OSType OS,
180 const char *ProgName) {
181 // If we don't yet have an output filename, make one.
182 if (OutputFilename.empty()) {
183 if (InputFilename == "-")
184 OutputFilename = "-";
186 // If InputFilename ends in .bc or .ll, remove it.
187 StringRef IFN = InputFilename;
188 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
189 OutputFilename = IFN.drop_back(3);
190 else if (IFN.endswith(".mir"))
191 OutputFilename = IFN.drop_back(4);
193 OutputFilename = IFN;
196 case TargetMachine::CGFT_AssemblyFile:
197 if (TargetName[0] == 'c') {
198 if (TargetName[1] == 0)
199 OutputFilename += ".cbe.c";
200 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
201 OutputFilename += ".cpp";
203 OutputFilename += ".s";
205 OutputFilename += ".s";
207 case TargetMachine::CGFT_ObjectFile:
208 if (OS == Triple::Win32)
209 OutputFilename += ".obj";
211 OutputFilename += ".o";
213 case TargetMachine::CGFT_Null:
214 OutputFilename += ".null";
220 // Decide if we need "binary" output.
223 case TargetMachine::CGFT_AssemblyFile:
225 case TargetMachine::CGFT_ObjectFile:
226 case TargetMachine::CGFT_Null:
233 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
235 OpenFlags |= sys::fs::F_Text;
236 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
239 errs() << EC.message() << '\n';
246 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
247 bool *HasError = static_cast<bool *>(Context);
248 if (DI.getSeverity() == DS_Error)
251 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
252 if (!Remark->isEnabled())
255 DiagnosticPrinterRawOStream DP(errs());
256 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
261 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
262 unsigned LocCookie) {
263 bool *HasError = static_cast<bool *>(Context);
264 if (SMD.getKind() == SourceMgr::DK_Error)
267 SMD.print(nullptr, errs());
269 // For testing purposes, we print the LocCookie here.
271 errs() << "note: !srcloc = " << LocCookie << "\n";
274 // main - Entry point for the llc compiler.
276 int main(int argc, char **argv) {
277 sys::PrintStackTraceOnErrorSignal(argv[0]);
278 PrettyStackTraceProgram X(argc, argv);
280 // Enable debug stream buffering.
281 EnableDebugBuffering = true;
284 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
286 // Initialize targets first, so that --version shows registered targets.
287 InitializeAllTargets();
288 InitializeAllTargetMCs();
289 InitializeAllAsmPrinters();
290 InitializeAllAsmParsers();
292 // Initialize codegen and IR passes used by llc so that the -print-after,
293 // -print-before, and -stop-after options work.
294 PassRegistry *Registry = PassRegistry::getPassRegistry();
295 initializeCore(*Registry);
296 initializeCodeGen(*Registry);
297 initializeLoopStrengthReducePass(*Registry);
298 initializeLowerIntrinsicsPass(*Registry);
299 initializeCountingFunctionInserterPass(*Registry);
300 initializeUnreachableBlockElimLegacyPassPass(*Registry);
301 initializeConstantHoistingLegacyPassPass(*Registry);
302 initializeScalarOpts(*Registry);
303 initializeVectorization(*Registry);
304 initializeScalarizeMaskedMemIntrinPass(*Registry);
305 initializeExpandReductionsPass(*Registry);
307 // Register the target printer for --version.
308 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
310 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
312 Context.setDiscardValueNames(DiscardValueNames);
314 // Set a diagnostic handler that doesn't exit on the first error
315 bool HasError = false;
316 Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
317 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
319 if (PassRemarksWithHotness)
320 Context.setDiagnosticHotnessRequested(true);
322 std::unique_ptr<tool_output_file> YamlFile;
323 if (RemarksFilename != "") {
325 YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
328 errs() << EC.message() << '\n';
331 Context.setDiagnosticsOutputFile(
332 llvm::make_unique<yaml::Output>(YamlFile->os()));
335 // Compile the module TimeCompilations times to give better compile time
337 for (unsigned I = TimeCompilations; I; --I)
338 if (int RetVal = compileModule(argv, Context))
346 static bool addPass(PassManagerBase &PM, const char *argv0,
347 StringRef PassName, TargetPassConfig &TPC) {
348 if (PassName == "none")
351 const PassRegistry *PR = PassRegistry::getPassRegistry();
352 const PassInfo *PI = PR->getPassInfo(PassName);
354 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
359 if (PI->getTargetMachineCtor())
360 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>());
361 else if (PI->getNormalCtor())
362 P = PI->getNormalCtor()();
364 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
367 std::string Banner = std::string("After ") + std::string(P->getPassName());
369 TPC.printAndVerify(Banner);
374 static AnalysisID getPassID(const char *argv0, const char *OptionName,
375 StringRef PassName) {
376 if (PassName.empty())
379 const PassRegistry &PR = *PassRegistry::getPassRegistry();
380 const PassInfo *PI = PR.getPassInfo(PassName);
382 errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
385 return PI->getTypeInfo();
388 static int compileModule(char **argv, LLVMContext &Context) {
389 // Load the module to be compiled...
391 std::unique_ptr<Module> M;
392 std::unique_ptr<MIRParser> MIR;
395 bool SkipModule = MCPU == "help" ||
396 (!MAttrs.empty() && MAttrs.front() == "help");
398 // If user just wants to list available options, skip module loading
400 if (StringRef(InputFilename).endswith_lower(".mir")) {
401 MIR = createMIRParserFromFile(InputFilename, Err, Context);
403 M = MIR->parseLLVMModule();
405 M = parseIRFile(InputFilename, Err, Context);
407 Err.print(argv[0], errs());
411 // Verify module immediately to catch problems before doInitialization() is
412 // called on any passes.
413 if (!NoVerify && verifyModule(*M, &errs())) {
414 errs() << argv[0] << ": " << InputFilename
415 << ": error: input module is broken!\n";
419 // If we are supposed to override the target triple, do so now.
420 if (!TargetTriple.empty())
421 M->setTargetTriple(Triple::normalize(TargetTriple));
422 TheTriple = Triple(M->getTargetTriple());
424 TheTriple = Triple(Triple::normalize(TargetTriple));
427 if (TheTriple.getTriple().empty())
428 TheTriple.setTriple(sys::getDefaultTargetTriple());
430 // Get the target specific parser.
432 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
435 errs() << argv[0] << ": " << Error;
439 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
441 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
444 errs() << argv[0] << ": invalid optimization level.\n";
447 case '0': OLvl = CodeGenOpt::None; break;
448 case '1': OLvl = CodeGenOpt::Less; break;
449 case '2': OLvl = CodeGenOpt::Default; break;
450 case '3': OLvl = CodeGenOpt::Aggressive; break;
453 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
454 Options.DisableIntegratedAS = NoIntegratedAssembler;
455 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
456 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
457 Options.MCOptions.AsmVerbose = AsmVerbose;
458 Options.MCOptions.PreserveAsmComments = PreserveComments;
459 Options.MCOptions.IASSearchPaths = IncludeDirs;
460 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
462 std::unique_ptr<TargetMachine> Target(
463 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
464 Options, getRelocModel(), CMModel, OLvl));
466 assert(Target && "Could not allocate target machine!");
468 // If we don't have a module then just exit now. We do this down
469 // here since the CPU/Feature help is underneath the target machine
474 assert(M && "Should have exited if we didn't have a module!");
475 if (FloatABIForCalls != FloatABI::Default)
476 Options.FloatABIType = FloatABIForCalls;
478 // Figure out where we are going to send the output.
479 std::unique_ptr<tool_output_file> Out =
480 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
483 // Build up all of the passes that we want to do to the module.
484 legacy::PassManager PM;
486 // Add an appropriate TargetLibraryInfo pass for the module's triple.
487 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
489 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
490 if (DisableSimplifyLibCalls)
491 TLII.disableAllFunctions();
492 PM.add(new TargetLibraryInfoWrapperPass(TLII));
494 // Add the target data from the target machine, if it exists, or the module.
495 M->setDataLayout(Target->createDataLayout());
497 // Override function attributes based on CPUStr, FeaturesStr, and command line
499 setFunctionAttributes(CPUStr, FeaturesStr, *M);
501 if (RelaxAll.getNumOccurrences() > 0 &&
502 FileType != TargetMachine::CGFT_ObjectFile)
504 << ": warning: ignoring -mc-relax-all because filetype != obj";
507 raw_pwrite_stream *OS = &Out->os();
509 // Manually do the buffering rather than using buffer_ostream,
510 // so we can memcmp the contents in CompileTwice mode
511 SmallVector<char, 0> Buffer;
512 std::unique_ptr<raw_svector_ostream> BOS;
513 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
514 !Out->os().supportsSeeking()) ||
516 BOS = make_unique<raw_svector_ostream>(Buffer);
520 if (!RunPassNames->empty()) {
521 if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
522 !StopBefore.empty()) {
523 errs() << argv[0] << ": start-after and/or stop-after passes are "
524 "redundant when run-pass is specified.\n";
528 errs() << argv[0] << ": run-pass needs a .mir input.\n";
531 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
532 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
534 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
535 MMI->setMachineFunctionInitializer(MIR.get());
537 TPC.printAndVerify("");
539 for (const std::string &RunPassName : *RunPassNames) {
540 if (addPass(PM, argv[0], RunPassName, TPC))
543 PM.add(createPrintMIRPass(*OS));
545 const char *argv0 = argv[0];
546 AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
547 AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
548 AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
549 AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
551 if (StartBeforeID && StartAfterID) {
552 errs() << argv[0] << ": -start-before and -start-after specified!\n";
555 if (StopBeforeID && StopAfterID) {
556 errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
560 // Ask the target to add backend passes as necessary.
561 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
562 StartBeforeID, StartAfterID, StopBeforeID,
563 StopAfterID, MIR.get())) {
564 errs() << argv[0] << ": target does not support generation of this"
570 // Before executing passes, print the final values of the LLVM options.
571 cl::PrintOptionValues();
573 // If requested, run the pass manager over the same module again,
574 // to catch any bugs due to persistent state in the passes. Note that
575 // opt has the same functionality, so it may be worth abstracting this out
577 SmallVector<char, 0> CompileTwiceBuffer;
579 std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
581 CompileTwiceBuffer = Buffer;
587 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
591 // Compare the two outputs and make sure they're the same
593 if (Buffer.size() != CompileTwiceBuffer.size() ||
594 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
597 << "Running the pass manager twice changed the output.\n"
598 "Writing the result of the second run to the specified output\n"
599 "To generate the one-run comparison binary, just run without\n"
600 "the compile-twice option\n";