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);
121 static cl::opt<std::string> StopBefore("stop-before",
122 cl::desc("Stop compilation before a specific pass"),
123 cl::value_desc("pass-name"), cl::init(""));
125 static cl::opt<std::string> StopAfter("stop-after",
126 cl::desc("Stop compilation after a specific pass"),
127 cl::value_desc("pass-name"), cl::init(""));
129 static cl::opt<std::string> StartBefore("start-before",
130 cl::desc("Resume compilation before a specific pass"),
131 cl::value_desc("pass-name"), cl::init(""));
133 static cl::opt<std::string> StartAfter("start-after",
134 cl::desc("Resume compilation after a specific pass"),
135 cl::value_desc("pass-name"), cl::init(""));
137 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
140 static ManagedStatic<std::vector<std::string>> RunPassNames;
142 struct RunPassOption {
143 void operator=(const std::string &Val) const {
146 SmallVector<StringRef, 8> PassNames;
147 StringRef(Val).split(PassNames, ',', -1, false);
148 for (auto PassName : PassNames)
149 RunPassNames->push_back(PassName);
154 static RunPassOption RunPassOpt;
156 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
158 cl::desc("Run compiler only for specified passes (comma separated list)"),
159 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
161 static int compileModule(char **, LLVMContext &);
163 static std::unique_ptr<tool_output_file>
164 GetOutputStream(const char *TargetName, Triple::OSType OS,
165 const char *ProgName) {
166 // If we don't yet have an output filename, make one.
167 if (OutputFilename.empty()) {
168 if (InputFilename == "-")
169 OutputFilename = "-";
171 // If InputFilename ends in .bc or .ll, remove it.
172 StringRef IFN = InputFilename;
173 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
174 OutputFilename = IFN.drop_back(3);
175 else if (IFN.endswith(".mir"))
176 OutputFilename = IFN.drop_back(4);
178 OutputFilename = IFN;
181 case TargetMachine::CGFT_AssemblyFile:
182 if (TargetName[0] == 'c') {
183 if (TargetName[1] == 0)
184 OutputFilename += ".cbe.c";
185 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
186 OutputFilename += ".cpp";
188 OutputFilename += ".s";
190 OutputFilename += ".s";
192 case TargetMachine::CGFT_ObjectFile:
193 if (OS == Triple::Win32)
194 OutputFilename += ".obj";
196 OutputFilename += ".o";
198 case TargetMachine::CGFT_Null:
199 OutputFilename += ".null";
205 // Decide if we need "binary" output.
208 case TargetMachine::CGFT_AssemblyFile:
210 case TargetMachine::CGFT_ObjectFile:
211 case TargetMachine::CGFT_Null:
218 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
220 OpenFlags |= sys::fs::F_Text;
221 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
224 errs() << EC.message() << '\n';
231 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
232 bool *HasError = static_cast<bool *>(Context);
233 if (DI.getSeverity() == DS_Error)
236 DiagnosticPrinterRawOStream DP(errs());
237 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
242 // main - Entry point for the llc compiler.
244 int main(int argc, char **argv) {
245 sys::PrintStackTraceOnErrorSignal(argv[0]);
246 PrettyStackTraceProgram X(argc, argv);
248 // Enable debug stream buffering.
249 EnableDebugBuffering = true;
252 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
254 // Initialize targets first, so that --version shows registered targets.
255 InitializeAllTargets();
256 InitializeAllTargetMCs();
257 InitializeAllAsmPrinters();
258 InitializeAllAsmParsers();
260 // Initialize codegen and IR passes used by llc so that the -print-after,
261 // -print-before, and -stop-after options work.
262 PassRegistry *Registry = PassRegistry::getPassRegistry();
263 initializeCore(*Registry);
264 initializeCodeGen(*Registry);
265 initializeLoopStrengthReducePass(*Registry);
266 initializeLowerIntrinsicsPass(*Registry);
267 initializeCountingFunctionInserterPass(*Registry);
268 initializeUnreachableBlockElimLegacyPassPass(*Registry);
269 initializeConstantHoistingLegacyPassPass(*Registry);
271 // Register the target printer for --version.
272 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
274 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
276 Context.setDiscardValueNames(DiscardValueNames);
278 // Set a diagnostic handler that doesn't exit on the first error
279 bool HasError = false;
280 Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
282 // Compile the module TimeCompilations times to give better compile time
284 for (unsigned I = TimeCompilations; I; --I)
285 if (int RetVal = compileModule(argv, Context))
290 static bool addPass(PassManagerBase &PM, const char *argv0,
291 StringRef PassName, TargetPassConfig &TPC) {
292 if (PassName == "none")
295 const PassRegistry *PR = PassRegistry::getPassRegistry();
296 const PassInfo *PI = PR->getPassInfo(PassName);
298 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
303 if (PI->getTargetMachineCtor())
304 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>());
305 else if (PI->getNormalCtor())
306 P = PI->getNormalCtor()();
308 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
311 std::string Banner = std::string("After ") + std::string(P->getPassName());
313 TPC.printAndVerify(Banner);
318 static AnalysisID getPassID(const char *argv0, const char *OptionName,
319 StringRef PassName) {
320 if (PassName.empty())
323 const PassRegistry &PR = *PassRegistry::getPassRegistry();
324 const PassInfo *PI = PR.getPassInfo(PassName);
326 errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
329 return PI->getTypeInfo();
332 static int compileModule(char **argv, LLVMContext &Context) {
333 // Load the module to be compiled...
335 std::unique_ptr<Module> M;
336 std::unique_ptr<MIRParser> MIR;
339 bool SkipModule = MCPU == "help" ||
340 (!MAttrs.empty() && MAttrs.front() == "help");
342 // If user just wants to list available options, skip module loading
344 if (StringRef(InputFilename).endswith_lower(".mir")) {
345 MIR = createMIRParserFromFile(InputFilename, Err, Context);
347 M = MIR->parseLLVMModule();
349 M = parseIRFile(InputFilename, Err, Context);
351 Err.print(argv[0], errs());
355 // Verify module immediately to catch problems before doInitialization() is
356 // called on any passes.
357 if (!NoVerify && verifyModule(*M, &errs())) {
358 errs() << argv[0] << ": " << InputFilename
359 << ": error: input module is broken!\n";
363 // If we are supposed to override the target triple, do so now.
364 if (!TargetTriple.empty())
365 M->setTargetTriple(Triple::normalize(TargetTriple));
366 TheTriple = Triple(M->getTargetTriple());
368 TheTriple = Triple(Triple::normalize(TargetTriple));
371 if (TheTriple.getTriple().empty())
372 TheTriple.setTriple(sys::getDefaultTargetTriple());
374 // Get the target specific parser.
376 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
379 errs() << argv[0] << ": " << Error;
383 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
385 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
388 errs() << argv[0] << ": invalid optimization level.\n";
391 case '0': OLvl = CodeGenOpt::None; break;
392 case '1': OLvl = CodeGenOpt::Less; break;
393 case '2': OLvl = CodeGenOpt::Default; break;
394 case '3': OLvl = CodeGenOpt::Aggressive; break;
397 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
398 Options.DisableIntegratedAS = NoIntegratedAssembler;
399 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
400 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
401 Options.MCOptions.AsmVerbose = AsmVerbose;
402 Options.MCOptions.PreserveAsmComments = PreserveComments;
403 Options.MCOptions.IASSearchPaths = IncludeDirs;
405 std::unique_ptr<TargetMachine> Target(
406 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
407 Options, getRelocModel(), CMModel, OLvl));
409 assert(Target && "Could not allocate target machine!");
411 // If we don't have a module then just exit now. We do this down
412 // here since the CPU/Feature help is underneath the target machine
417 assert(M && "Should have exited if we didn't have a module!");
418 if (FloatABIForCalls != FloatABI::Default)
419 Options.FloatABIType = FloatABIForCalls;
421 // Figure out where we are going to send the output.
422 std::unique_ptr<tool_output_file> Out =
423 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
426 // Build up all of the passes that we want to do to the module.
427 legacy::PassManager PM;
429 // Add an appropriate TargetLibraryInfo pass for the module's triple.
430 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
432 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
433 if (DisableSimplifyLibCalls)
434 TLII.disableAllFunctions();
435 PM.add(new TargetLibraryInfoWrapperPass(TLII));
437 // Add the target data from the target machine, if it exists, or the module.
438 M->setDataLayout(Target->createDataLayout());
440 // Override function attributes based on CPUStr, FeaturesStr, and command line
442 setFunctionAttributes(CPUStr, FeaturesStr, *M);
444 if (RelaxAll.getNumOccurrences() > 0 &&
445 FileType != TargetMachine::CGFT_ObjectFile)
447 << ": warning: ignoring -mc-relax-all because filetype != obj";
450 raw_pwrite_stream *OS = &Out->os();
452 // Manually do the buffering rather than using buffer_ostream,
453 // so we can memcmp the contents in CompileTwice mode
454 SmallVector<char, 0> Buffer;
455 std::unique_ptr<raw_svector_ostream> BOS;
456 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
457 !Out->os().supportsSeeking()) ||
459 BOS = make_unique<raw_svector_ostream>(Buffer);
463 if (!RunPassNames->empty()) {
464 if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
465 !StopBefore.empty()) {
466 errs() << argv[0] << ": start-after and/or stop-after passes are "
467 "redundant when run-pass is specified.\n";
471 errs() << argv[0] << ": run-pass needs a .mir input.\n";
474 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
475 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
477 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
478 MMI->setMachineFunctionInitializer(MIR.get());
480 TPC.printAndVerify("");
482 for (const std::string &RunPassName : *RunPassNames) {
483 if (addPass(PM, argv[0], RunPassName, TPC))
486 PM.add(createPrintMIRPass(*OS));
488 const char *argv0 = argv[0];
489 AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
490 AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
491 AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
492 AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
494 if (StartBeforeID && StartAfterID) {
495 errs() << argv[0] << ": -start-before and -start-after specified!\n";
498 if (StopBeforeID && StopAfterID) {
499 errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
503 // Ask the target to add backend passes as necessary.
504 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
505 StartBeforeID, StartAfterID, StopBeforeID,
506 StopAfterID, MIR.get())) {
507 errs() << argv[0] << ": target does not support generation of this"
513 // Before executing passes, print the final values of the LLVM options.
514 cl::PrintOptionValues();
516 // If requested, run the pass manager over the same module again,
517 // to catch any bugs due to persistent state in the passes. Note that
518 // opt has the same functionality, so it may be worth abstracting this out
520 SmallVector<char, 0> CompileTwiceBuffer;
522 std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
524 CompileTwiceBuffer = Buffer;
530 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
534 // Compare the two outputs and make sure they're the same
536 if (Buffer.size() != CompileTwiceBuffer.size() ||
537 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
540 << "Running the pass manager twice changed the output.\n"
541 "Writing the result of the second run to the specified output\n"
542 "To generate the one-run comparison binary, just run without\n"
543 "the compile-twice option\n";