]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llc/llc.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304659, 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   // Initialize debugging passes.
308   initializeScavengerTestPass(*Registry);
309
310   // Register the target printer for --version.
311   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
312
313   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
314
315   Context.setDiscardValueNames(DiscardValueNames);
316
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);
321
322   if (PassRemarksWithHotness)
323     Context.setDiagnosticHotnessRequested(true);
324
325   std::unique_ptr<tool_output_file> YamlFile;
326   if (RemarksFilename != "") {
327     std::error_code EC;
328     YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
329                                                    sys::fs::F_None);
330     if (EC) {
331       errs() << EC.message() << '\n';
332       return 1;
333     }
334     Context.setDiagnosticsOutputFile(
335         llvm::make_unique<yaml::Output>(YamlFile->os()));
336   }
337
338   // Compile the module TimeCompilations times to give better compile time
339   // metrics.
340   for (unsigned I = TimeCompilations; I; --I)
341     if (int RetVal = compileModule(argv, Context))
342       return RetVal;
343
344   if (YamlFile)
345     YamlFile->keep();
346   return 0;
347 }
348
349 static bool addPass(PassManagerBase &PM, const char *argv0,
350                     StringRef PassName, TargetPassConfig &TPC) {
351   if (PassName == "none")
352     return false;
353
354   const PassRegistry *PR = PassRegistry::getPassRegistry();
355   const PassInfo *PI = PR->getPassInfo(PassName);
356   if (!PI) {
357     errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
358     return true;
359   }
360
361   Pass *P;
362   if (PI->getNormalCtor())
363     P = PI->getNormalCtor()();
364   else {
365     errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
366     return true;
367   }
368   std::string Banner = std::string("After ") + std::string(P->getPassName());
369   PM.add(P);
370   TPC.printAndVerify(Banner);
371
372   return false;
373 }
374
375 static AnalysisID getPassID(const char *argv0, const char *OptionName,
376                             StringRef PassName) {
377   if (PassName.empty())
378     return nullptr;
379
380   const PassRegistry &PR = *PassRegistry::getPassRegistry();
381   const PassInfo *PI = PR.getPassInfo(PassName);
382   if (!PI) {
383     errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
384     exit(1);
385   }
386   return PI->getTypeInfo();
387 }
388
389 static int compileModule(char **argv, LLVMContext &Context) {
390   // Load the module to be compiled...
391   SMDiagnostic Err;
392   std::unique_ptr<Module> M;
393   std::unique_ptr<MIRParser> MIR;
394   Triple TheTriple;
395
396   bool SkipModule = MCPU == "help" ||
397                     (!MAttrs.empty() && MAttrs.front() == "help");
398
399   // If user just wants to list available options, skip module loading
400   if (!SkipModule) {
401     if (StringRef(InputFilename).endswith_lower(".mir")) {
402       MIR = createMIRParserFromFile(InputFilename, Err, Context);
403       if (MIR)
404         M = MIR->parseLLVMModule();
405     } else
406       M = parseIRFile(InputFilename, Err, Context);
407     if (!M) {
408       Err.print(argv[0], errs());
409       return 1;
410     }
411
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";
417       return 1;
418     }
419
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());
424   } else {
425     TheTriple = Triple(Triple::normalize(TargetTriple));
426   }
427
428   if (TheTriple.getTriple().empty())
429     TheTriple.setTriple(sys::getDefaultTargetTriple());
430
431   // Get the target specific parser.
432   std::string Error;
433   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
434                                                          Error);
435   if (!TheTarget) {
436     errs() << argv[0] << ": " << Error;
437     return 1;
438   }
439
440   std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
441
442   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
443   switch (OptLevel) {
444   default:
445     errs() << argv[0] << ": invalid optimization level.\n";
446     return 1;
447   case ' ': break;
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;
452   }
453
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;
462
463   std::unique_ptr<TargetMachine> Target(
464       TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
465                                      Options, getRelocModel(), CMModel, OLvl));
466
467   assert(Target && "Could not allocate target machine!");
468
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
471   // creation.
472   if (SkipModule)
473     return 0;
474
475   assert(M && "Should have exited if we didn't have a module!");
476   if (FloatABIForCalls != FloatABI::Default)
477     Options.FloatABIType = FloatABIForCalls;
478
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]);
482   if (!Out) return 1;
483
484   // Build up all of the passes that we want to do to the module.
485   legacy::PassManager PM;
486
487   // Add an appropriate TargetLibraryInfo pass for the module's triple.
488   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
489
490   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
491   if (DisableSimplifyLibCalls)
492     TLII.disableAllFunctions();
493   PM.add(new TargetLibraryInfoWrapperPass(TLII));
494
495   // Add the target data from the target machine, if it exists, or the module.
496   M->setDataLayout(Target->createDataLayout());
497
498   // Override function attributes based on CPUStr, FeaturesStr, and command line
499   // flags.
500   setFunctionAttributes(CPUStr, FeaturesStr, *M);
501
502   if (RelaxAll.getNumOccurrences() > 0 &&
503       FileType != TargetMachine::CGFT_ObjectFile)
504     errs() << argv[0]
505              << ": warning: ignoring -mc-relax-all because filetype != obj";
506
507   {
508     raw_pwrite_stream *OS = &Out->os();
509
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()) ||
516         CompileTwice) {
517       BOS = make_unique<raw_svector_ostream>(Buffer);
518       OS = BOS.get();
519     }
520
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";
526         return 1;
527       }
528       if (!MIR) {
529         errs() << argv[0] << ": run-pass needs a .mir input.\n";
530         return 1;
531       }
532       LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
533       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
534       PM.add(&TPC);
535       MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
536       MMI->setMachineFunctionInitializer(MIR.get());
537       PM.add(MMI);
538       TPC.printAndVerify("");
539
540       for (const std::string &RunPassName : *RunPassNames) {
541         if (addPass(PM, argv[0], RunPassName, TPC))
542           return 1;
543       }
544       PM.add(createPrintMIRPass(*OS));
545     } else {
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);
551
552       if (StartBeforeID && StartAfterID) {
553         errs() << argv[0] << ": -start-before and -start-after specified!\n";
554         return 1;
555       }
556       if (StopBeforeID && StopAfterID) {
557         errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
558         return 1;
559       }
560
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"
566                << " file type!\n";
567         return 1;
568       }
569     }
570
571     // Before executing passes, print the final values of the LLVM options.
572     cl::PrintOptionValues();
573
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
577     // in the future.
578     SmallVector<char, 0> CompileTwiceBuffer;
579     if (CompileTwice) {
580       std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
581       PM.run(*M2);
582       CompileTwiceBuffer = Buffer;
583       Buffer.clear();
584     }
585
586     PM.run(*M);
587
588     auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
589     if (HasError)
590       return 1;
591
592     // Compare the two outputs and make sure they're the same
593     if (CompileTwice) {
594       if (Buffer.size() != CompileTwiceBuffer.size() ||
595           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
596            0)) {
597         errs()
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";
602         Out->os() << Buffer;
603         Out->keep();
604         return 1;
605       }
606     }
607
608     if (BOS) {
609       Out->os() << Buffer;
610     }
611   }
612
613   // Declare success.
614   Out->keep();
615
616   return 0;
617 }