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 // Initialize debugging passes.
308 initializeScavengerTestPass(*Registry);
310 // Register the target printer for --version.
311 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
313 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
315 Context.setDiscardValueNames(DiscardValueNames);
317 // Set a diagnostic handler that doesn't exit on the first error
318 bool HasError = false;
319 Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
320 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
322 if (PassRemarksWithHotness)
323 Context.setDiagnosticHotnessRequested(true);
325 std::unique_ptr<tool_output_file> YamlFile;
326 if (RemarksFilename != "") {
328 YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
331 errs() << EC.message() << '\n';
334 Context.setDiagnosticsOutputFile(
335 llvm::make_unique<yaml::Output>(YamlFile->os()));
338 // Compile the module TimeCompilations times to give better compile time
340 for (unsigned I = TimeCompilations; I; --I)
341 if (int RetVal = compileModule(argv, Context))
349 static bool addPass(PassManagerBase &PM, const char *argv0,
350 StringRef PassName, TargetPassConfig &TPC) {
351 if (PassName == "none")
354 const PassRegistry *PR = PassRegistry::getPassRegistry();
355 const PassInfo *PI = PR->getPassInfo(PassName);
357 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
362 if (PI->getNormalCtor())
363 P = PI->getNormalCtor()();
365 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
368 std::string Banner = std::string("After ") + std::string(P->getPassName());
370 TPC.printAndVerify(Banner);
375 static AnalysisID getPassID(const char *argv0, const char *OptionName,
376 StringRef PassName) {
377 if (PassName.empty())
380 const PassRegistry &PR = *PassRegistry::getPassRegistry();
381 const PassInfo *PI = PR.getPassInfo(PassName);
383 errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
386 return PI->getTypeInfo();
389 static int compileModule(char **argv, LLVMContext &Context) {
390 // Load the module to be compiled...
392 std::unique_ptr<Module> M;
393 std::unique_ptr<MIRParser> MIR;
396 bool SkipModule = MCPU == "help" ||
397 (!MAttrs.empty() && MAttrs.front() == "help");
399 // If user just wants to list available options, skip module loading
401 if (StringRef(InputFilename).endswith_lower(".mir")) {
402 MIR = createMIRParserFromFile(InputFilename, Err, Context);
404 M = MIR->parseLLVMModule();
406 M = parseIRFile(InputFilename, Err, Context);
408 Err.print(argv[0], errs());
412 // Verify module immediately to catch problems before doInitialization() is
413 // called on any passes.
414 if (!NoVerify && verifyModule(*M, &errs())) {
415 errs() << argv[0] << ": " << InputFilename
416 << ": error: input module is broken!\n";
420 // If we are supposed to override the target triple, do so now.
421 if (!TargetTriple.empty())
422 M->setTargetTriple(Triple::normalize(TargetTriple));
423 TheTriple = Triple(M->getTargetTriple());
425 TheTriple = Triple(Triple::normalize(TargetTriple));
428 if (TheTriple.getTriple().empty())
429 TheTriple.setTriple(sys::getDefaultTargetTriple());
431 // Get the target specific parser.
433 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
436 errs() << argv[0] << ": " << Error;
440 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
442 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
445 errs() << argv[0] << ": invalid optimization level.\n";
448 case '0': OLvl = CodeGenOpt::None; break;
449 case '1': OLvl = CodeGenOpt::Less; break;
450 case '2': OLvl = CodeGenOpt::Default; break;
451 case '3': OLvl = CodeGenOpt::Aggressive; break;
454 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
455 Options.DisableIntegratedAS = NoIntegratedAssembler;
456 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
457 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
458 Options.MCOptions.AsmVerbose = AsmVerbose;
459 Options.MCOptions.PreserveAsmComments = PreserveComments;
460 Options.MCOptions.IASSearchPaths = IncludeDirs;
461 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
463 std::unique_ptr<TargetMachine> Target(
464 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
465 Options, getRelocModel(), CMModel, OLvl));
467 assert(Target && "Could not allocate target machine!");
469 // If we don't have a module then just exit now. We do this down
470 // here since the CPU/Feature help is underneath the target machine
475 assert(M && "Should have exited if we didn't have a module!");
476 if (FloatABIForCalls != FloatABI::Default)
477 Options.FloatABIType = FloatABIForCalls;
479 // Figure out where we are going to send the output.
480 std::unique_ptr<tool_output_file> Out =
481 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
484 // Build up all of the passes that we want to do to the module.
485 legacy::PassManager PM;
487 // Add an appropriate TargetLibraryInfo pass for the module's triple.
488 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
490 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
491 if (DisableSimplifyLibCalls)
492 TLII.disableAllFunctions();
493 PM.add(new TargetLibraryInfoWrapperPass(TLII));
495 // Add the target data from the target machine, if it exists, or the module.
496 M->setDataLayout(Target->createDataLayout());
498 // Override function attributes based on CPUStr, FeaturesStr, and command line
500 setFunctionAttributes(CPUStr, FeaturesStr, *M);
502 if (RelaxAll.getNumOccurrences() > 0 &&
503 FileType != TargetMachine::CGFT_ObjectFile)
505 << ": warning: ignoring -mc-relax-all because filetype != obj";
508 raw_pwrite_stream *OS = &Out->os();
510 // Manually do the buffering rather than using buffer_ostream,
511 // so we can memcmp the contents in CompileTwice mode
512 SmallVector<char, 0> Buffer;
513 std::unique_ptr<raw_svector_ostream> BOS;
514 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
515 !Out->os().supportsSeeking()) ||
517 BOS = make_unique<raw_svector_ostream>(Buffer);
521 if (!RunPassNames->empty()) {
522 if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
523 !StopBefore.empty()) {
524 errs() << argv[0] << ": start-after and/or stop-after passes are "
525 "redundant when run-pass is specified.\n";
529 errs() << argv[0] << ": run-pass needs a .mir input.\n";
532 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
533 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
535 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
536 MMI->setMachineFunctionInitializer(MIR.get());
538 TPC.printAndVerify("");
540 for (const std::string &RunPassName : *RunPassNames) {
541 if (addPass(PM, argv[0], RunPassName, TPC))
544 PM.add(createPrintMIRPass(*OS));
546 const char *argv0 = argv[0];
547 AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
548 AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
549 AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
550 AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
552 if (StartBeforeID && StartAfterID) {
553 errs() << argv[0] << ": -start-before and -start-after specified!\n";
556 if (StopBeforeID && StopAfterID) {
557 errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
561 // Ask the target to add backend passes as necessary.
562 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
563 StartBeforeID, StartAfterID, StopBeforeID,
564 StopAfterID, MIR.get())) {
565 errs() << argv[0] << ": target does not support generation of this"
571 // Before executing passes, print the final values of the LLVM options.
572 cl::PrintOptionValues();
574 // If requested, run the pass manager over the same module again,
575 // to catch any bugs due to persistent state in the passes. Note that
576 // opt has the same functionality, so it may be worth abstracting this out
578 SmallVector<char, 0> CompileTwiceBuffer;
580 std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
582 CompileTwiceBuffer = Buffer;
588 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
592 // Compare the two outputs and make sure they're the same
594 if (Buffer.size() != CompileTwiceBuffer.size() ||
595 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
598 << "Running the pass manager twice changed the output.\n"
599 "Writing the result of the second run to the specified output\n"
600 "To generate the one-run comparison binary, just run without\n"
601 "the compile-twice option\n";