]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llc/llc.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303197, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16
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"
54 #include <memory>
55 using namespace llvm;
56
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.
60 //
61 static cl::opt<std::string>
62 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
63
64 static cl::opt<std::string>
65 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
66
67 static cl::opt<unsigned>
68 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
69                  cl::value_desc("N"),
70                  cl::desc("Repeat compilation N times for timing"));
71
72 static cl::opt<bool>
73 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
74                       cl::desc("Disable integrated assembler"));
75
76 static cl::opt<bool>
77     PreserveComments("preserve-as-comments", cl::Hidden,
78                      cl::desc("Preserve Comments in outputted assembly"),
79                      cl::init(true));
80
81 // Determine optimization level.
82 static cl::opt<char>
83 OptLevel("O",
84          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
85                   "(default = '-O2')"),
86          cl::Prefix,
87          cl::ZeroOrMore,
88          cl::init(' '));
89
90 static cl::opt<std::string>
91 TargetTriple("mtriple", cl::desc("Override target triple for module"));
92
93 static cl::opt<std::string> SplitDwarfFile(
94     "split-dwarf-file",
95     cl::desc(
96         "Specify the name of the .dwo file to encode in the DWARF output"));
97
98 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
99                               cl::desc("Do not verify input module"));
100
101 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
102                                              cl::desc("Disable simplify-libcalls"));
103
104 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
105                                     cl::desc("Show encoding in .s output"));
106
107 static cl::opt<bool> EnableDwarfDirectory(
108     "enable-dwarf-directory", cl::Hidden,
109     cl::desc("Use .file directives with an explicit directory."));
110
111 static cl::opt<bool> AsmVerbose("asm-verbose",
112                                 cl::desc("Add comments to directives."),
113                                 cl::init(true));
114
115 static cl::opt<bool>
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."),
119                  cl::init(false));
120
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);
125
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(""));
129
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(""));
133
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(""));
137
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(""));
141
142 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
143
144 static cl::opt<bool> PassRemarksWithHotness(
145     "pass-remarks-with-hotness",
146     cl::desc("With PGO, include profile count in optimization remarks"),
147     cl::Hidden);
148
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"));
153
154 namespace {
155 static ManagedStatic<std::vector<std::string>> RunPassNames;
156
157 struct RunPassOption {
158   void operator=(const std::string &Val) const {
159     if (Val.empty())
160       return;
161     SmallVector<StringRef, 8> PassNames;
162     StringRef(Val).split(PassNames, ',', -1, false);
163     for (auto PassName : PassNames)
164       RunPassNames->push_back(PassName);
165   }
166 };
167 }
168
169 static RunPassOption RunPassOpt;
170
171 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
172     "run-pass",
173     cl::desc("Run compiler only for specified passes (comma separated list)"),
174     cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
175
176 static int compileModule(char **, LLVMContext &);
177
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 = "-";
185     else {
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);
192       else
193         OutputFilename = IFN;
194
195       switch (FileType) {
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";
202           else
203             OutputFilename += ".s";
204         } else
205           OutputFilename += ".s";
206         break;
207       case TargetMachine::CGFT_ObjectFile:
208         if (OS == Triple::Win32)
209           OutputFilename += ".obj";
210         else
211           OutputFilename += ".o";
212         break;
213       case TargetMachine::CGFT_Null:
214         OutputFilename += ".null";
215         break;
216       }
217     }
218   }
219
220   // Decide if we need "binary" output.
221   bool Binary = false;
222   switch (FileType) {
223   case TargetMachine::CGFT_AssemblyFile:
224     break;
225   case TargetMachine::CGFT_ObjectFile:
226   case TargetMachine::CGFT_Null:
227     Binary = true;
228     break;
229   }
230
231   // Open the file.
232   std::error_code EC;
233   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
234   if (!Binary)
235     OpenFlags |= sys::fs::F_Text;
236   auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
237                                                    OpenFlags);
238   if (EC) {
239     errs() << EC.message() << '\n';
240     return nullptr;
241   }
242
243   return FDOut;
244 }
245
246 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
247   bool *HasError = static_cast<bool *>(Context);
248   if (DI.getSeverity() == DS_Error)
249     *HasError = true;
250
251   if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
252     if (!Remark->isEnabled())
253       return;
254
255   DiagnosticPrinterRawOStream DP(errs());
256   errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
257   DI.print(DP);
258   errs() << "\n";
259 }
260
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)
265     *HasError = true;
266
267   SMD.print(nullptr, errs());
268
269   // For testing purposes, we print the LocCookie here.
270   if (LocCookie)
271     errs() << "note: !srcloc = " << LocCookie << "\n";
272 }
273
274 // main - Entry point for the llc compiler.
275 //
276 int main(int argc, char **argv) {
277   sys::PrintStackTraceOnErrorSignal(argv[0]);
278   PrettyStackTraceProgram X(argc, argv);
279
280   // Enable debug stream buffering.
281   EnableDebugBuffering = true;
282
283   LLVMContext Context;
284   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
285
286   // Initialize targets first, so that --version shows registered targets.
287   InitializeAllTargets();
288   InitializeAllTargetMCs();
289   InitializeAllAsmPrinters();
290   InitializeAllAsmParsers();
291
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);
306
307   // Register the target printer for --version.
308   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
309
310   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
311
312   Context.setDiscardValueNames(DiscardValueNames);
313
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);
318
319   if (PassRemarksWithHotness)
320     Context.setDiagnosticHotnessRequested(true);
321
322   std::unique_ptr<tool_output_file> YamlFile;
323   if (RemarksFilename != "") {
324     std::error_code EC;
325     YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
326                                                    sys::fs::F_None);
327     if (EC) {
328       errs() << EC.message() << '\n';
329       return 1;
330     }
331     Context.setDiagnosticsOutputFile(
332         llvm::make_unique<yaml::Output>(YamlFile->os()));
333   }
334
335   // Compile the module TimeCompilations times to give better compile time
336   // metrics.
337   for (unsigned I = TimeCompilations; I; --I)
338     if (int RetVal = compileModule(argv, Context))
339       return RetVal;
340
341   if (YamlFile)
342     YamlFile->keep();
343   return 0;
344 }
345
346 static bool addPass(PassManagerBase &PM, const char *argv0,
347                     StringRef PassName, TargetPassConfig &TPC) {
348   if (PassName == "none")
349     return false;
350
351   const PassRegistry *PR = PassRegistry::getPassRegistry();
352   const PassInfo *PI = PR->getPassInfo(PassName);
353   if (!PI) {
354     errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
355     return true;
356   }
357
358   Pass *P;
359   if (PI->getTargetMachineCtor())
360     P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>());
361   else if (PI->getNormalCtor())
362     P = PI->getNormalCtor()();
363   else {
364     errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
365     return true;
366   }
367   std::string Banner = std::string("After ") + std::string(P->getPassName());
368   PM.add(P);
369   TPC.printAndVerify(Banner);
370
371   return false;
372 }
373
374 static AnalysisID getPassID(const char *argv0, const char *OptionName,
375                             StringRef PassName) {
376   if (PassName.empty())
377     return nullptr;
378
379   const PassRegistry &PR = *PassRegistry::getPassRegistry();
380   const PassInfo *PI = PR.getPassInfo(PassName);
381   if (!PI) {
382     errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
383     exit(1);
384   }
385   return PI->getTypeInfo();
386 }
387
388 static int compileModule(char **argv, LLVMContext &Context) {
389   // Load the module to be compiled...
390   SMDiagnostic Err;
391   std::unique_ptr<Module> M;
392   std::unique_ptr<MIRParser> MIR;
393   Triple TheTriple;
394
395   bool SkipModule = MCPU == "help" ||
396                     (!MAttrs.empty() && MAttrs.front() == "help");
397
398   // If user just wants to list available options, skip module loading
399   if (!SkipModule) {
400     if (StringRef(InputFilename).endswith_lower(".mir")) {
401       MIR = createMIRParserFromFile(InputFilename, Err, Context);
402       if (MIR)
403         M = MIR->parseLLVMModule();
404     } else
405       M = parseIRFile(InputFilename, Err, Context);
406     if (!M) {
407       Err.print(argv[0], errs());
408       return 1;
409     }
410
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";
416       return 1;
417     }
418
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());
423   } else {
424     TheTriple = Triple(Triple::normalize(TargetTriple));
425   }
426
427   if (TheTriple.getTriple().empty())
428     TheTriple.setTriple(sys::getDefaultTargetTriple());
429
430   // Get the target specific parser.
431   std::string Error;
432   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
433                                                          Error);
434   if (!TheTarget) {
435     errs() << argv[0] << ": " << Error;
436     return 1;
437   }
438
439   std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
440
441   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
442   switch (OptLevel) {
443   default:
444     errs() << argv[0] << ": invalid optimization level.\n";
445     return 1;
446   case ' ': break;
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;
451   }
452
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;
461
462   std::unique_ptr<TargetMachine> Target(
463       TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
464                                      Options, getRelocModel(), CMModel, OLvl));
465
466   assert(Target && "Could not allocate target machine!");
467
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
470   // creation.
471   if (SkipModule)
472     return 0;
473
474   assert(M && "Should have exited if we didn't have a module!");
475   if (FloatABIForCalls != FloatABI::Default)
476     Options.FloatABIType = FloatABIForCalls;
477
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]);
481   if (!Out) return 1;
482
483   // Build up all of the passes that we want to do to the module.
484   legacy::PassManager PM;
485
486   // Add an appropriate TargetLibraryInfo pass for the module's triple.
487   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
488
489   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
490   if (DisableSimplifyLibCalls)
491     TLII.disableAllFunctions();
492   PM.add(new TargetLibraryInfoWrapperPass(TLII));
493
494   // Add the target data from the target machine, if it exists, or the module.
495   M->setDataLayout(Target->createDataLayout());
496
497   // Override function attributes based on CPUStr, FeaturesStr, and command line
498   // flags.
499   setFunctionAttributes(CPUStr, FeaturesStr, *M);
500
501   if (RelaxAll.getNumOccurrences() > 0 &&
502       FileType != TargetMachine::CGFT_ObjectFile)
503     errs() << argv[0]
504              << ": warning: ignoring -mc-relax-all because filetype != obj";
505
506   {
507     raw_pwrite_stream *OS = &Out->os();
508
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()) ||
515         CompileTwice) {
516       BOS = make_unique<raw_svector_ostream>(Buffer);
517       OS = BOS.get();
518     }
519
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";
525         return 1;
526       }
527       if (!MIR) {
528         errs() << argv[0] << ": run-pass needs a .mir input.\n";
529         return 1;
530       }
531       LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
532       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
533       PM.add(&TPC);
534       MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
535       MMI->setMachineFunctionInitializer(MIR.get());
536       PM.add(MMI);
537       TPC.printAndVerify("");
538
539       for (const std::string &RunPassName : *RunPassNames) {
540         if (addPass(PM, argv[0], RunPassName, TPC))
541           return 1;
542       }
543       PM.add(createPrintMIRPass(*OS));
544     } else {
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);
550
551       if (StartBeforeID && StartAfterID) {
552         errs() << argv[0] << ": -start-before and -start-after specified!\n";
553         return 1;
554       }
555       if (StopBeforeID && StopAfterID) {
556         errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
557         return 1;
558       }
559
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"
565                << " file type!\n";
566         return 1;
567       }
568     }
569
570     // Before executing passes, print the final values of the LLVM options.
571     cl::PrintOptionValues();
572
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
576     // in the future.
577     SmallVector<char, 0> CompileTwiceBuffer;
578     if (CompileTwice) {
579       std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
580       PM.run(*M2);
581       CompileTwiceBuffer = Buffer;
582       Buffer.clear();
583     }
584
585     PM.run(*M);
586
587     auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
588     if (HasError)
589       return 1;
590
591     // Compare the two outputs and make sure they're the same
592     if (CompileTwice) {
593       if (Buffer.size() != CompileTwiceBuffer.size() ||
594           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
595            0)) {
596         errs()
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";
601         Out->os() << Buffer;
602         Out->keep();
603         return 1;
604       }
605     }
606
607     if (BOS) {
608       Out->os() << Buffer;
609     }
610   }
611
612   // Declare success.
613   Out->keep();
614
615   return 0;
616 }