LLVM  10.0.0
AsmPrinter.cpp
Go to the documentation of this file.
1 //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AsmPrinter class.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "CodeViewDebug.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "WasmException.h"
18 #include "WinCFGuard.h"
19 #include "WinException.h"
20 #include "llvm/ADT/APFloat.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
35 #include "llvm/BinaryFormat/COFF.h"
37 #include "llvm/BinaryFormat/ELF.h"
59 #include "llvm/CodeGen/StackMaps.h"
65 #include "llvm/IR/BasicBlock.h"
66 #include "llvm/IR/Comdat.h"
67 #include "llvm/IR/Constant.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GlobalAlias.h"
74 #include "llvm/IR/GlobalIFunc.h"
76 #include "llvm/IR/GlobalObject.h"
77 #include "llvm/IR/GlobalValue.h"
78 #include "llvm/IR/GlobalVariable.h"
79 #include "llvm/IR/Instruction.h"
80 #include "llvm/IR/Mangler.h"
81 #include "llvm/IR/Metadata.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/Operator.h"
84 #include "llvm/IR/RemarkStreamer.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCAsmInfo.h"
88 #include "llvm/MC/MCContext.h"
89 #include "llvm/MC/MCDirectives.h"
90 #include "llvm/MC/MCDwarf.h"
91 #include "llvm/MC/MCExpr.h"
92 #include "llvm/MC/MCInst.h"
93 #include "llvm/MC/MCSection.h"
94 #include "llvm/MC/MCSectionCOFF.h"
95 #include "llvm/MC/MCSectionELF.h"
96 #include "llvm/MC/MCSectionMachO.h"
97 #include "llvm/MC/MCSectionXCOFF.h"
98 #include "llvm/MC/MCStreamer.h"
100 #include "llvm/MC/MCSymbol.h"
101 #include "llvm/MC/MCSymbolELF.h"
102 #include "llvm/MC/MCSymbolXCOFF.h"
103 #include "llvm/MC/MCTargetOptions.h"
104 #include "llvm/MC/MCValue.h"
105 #include "llvm/MC/SectionKind.h"
106 #include "llvm/Pass.h"
107 #include "llvm/Remarks/Remark.h"
110 #include "llvm/Support/Casting.h"
112 #include "llvm/Support/Compiler.h"
114 #include "llvm/Support/Format.h"
115 #include "llvm/Support/MathExtras.h"
116 #include "llvm/Support/Path.h"
118 #include "llvm/Support/Timer.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <cinttypes>
126 #include <cstdint>
127 #include <iterator>
128 #include <limits>
129 #include <memory>
130 #include <string>
131 #include <utility>
132 #include <vector>
133 
134 using namespace llvm;
135 
136 #define DEBUG_TYPE "asm-printer"
137 
138 static const char *const DWARFGroupName = "dwarf";
139 static const char *const DWARFGroupDescription = "DWARF Emission";
140 static const char *const DbgTimerName = "emit";
141 static const char *const DbgTimerDescription = "Debug Info Emission";
142 static const char *const EHTimerName = "write_exception";
143 static const char *const EHTimerDescription = "DWARF Exception Writer";
144 static const char *const CFGuardName = "Control Flow Guard";
145 static const char *const CFGuardDescription = "Control Flow Guard";
146 static const char *const CodeViewLineTablesGroupName = "linetables";
147 static const char *const CodeViewLineTablesGroupDescription =
148  "CodeView Line Tables";
149 
150 STATISTIC(EmittedInsts, "Number of machine instrs printed");
151 
152 char AsmPrinter::ID = 0;
153 
155 
156 static gcp_map_type &getGCMap(void *&P) {
157  if (!P)
158  P = new gcp_map_type();
159  return *(gcp_map_type*)P;
160 }
161 
162 /// getGVAlignment - Return the alignment to use for the specified global
163 /// value. This rounds up to the preferred alignment if possible and legal.
165  Align InAlign) {
166  Align Alignment;
167  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
168  Alignment = Align(DL.getPreferredAlignment(GVar));
169 
170  // If InAlign is specified, round it to it.
171  if (InAlign > Alignment)
172  Alignment = InAlign;
173 
174  // If the GV has a specified alignment, take it into account.
175  const MaybeAlign GVAlign(GV->getAlignment());
176  if (!GVAlign)
177  return Alignment;
178 
179  assert(GVAlign && "GVAlign must be set");
180 
181  // If the GVAlign is larger than NumBits, or if we are required to obey
182  // NumBits because the GV has an assigned section, obey it.
183  if (*GVAlign > Alignment || GV->hasSection())
184  Alignment = *GVAlign;
185  return Alignment;
186 }
187 
188 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
189  : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
190  OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
191  VerboseAsm = OutStreamer->isVerboseAsm();
192 }
193 
195  assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
196 
197  if (GCMetadataPrinters) {
198  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
199 
200  delete &GCMap;
201  GCMetadataPrinters = nullptr;
202  }
203 }
204 
206  return TM.isPositionIndependent();
207 }
208 
209 /// getFunctionNumber - Return a unique ID for the current function.
211  return MF->getFunctionNumber();
212 }
213 
215  return *TM.getObjFileLowering();
216 }
217 
219  return MMI->getModule()->getDataLayout();
220 }
221 
222 // Do not use the cached DataLayout because some client use it without a Module
223 // (dsymutil, llvm-dwarfdump).
224 unsigned AsmPrinter::getPointerSize() const {
225  return TM.getPointerSize(0); // FIXME: Default address space
226 }
227 
229  assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
230  return MF->getSubtarget<MCSubtargetInfo>();
231 }
232 
235 }
236 
238  assert(DD && "Dwarf debug file is not defined.");
239  assert(OutStreamer->hasRawTextSupport() && "Expected assembly output mode.");
240  (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
241 }
242 
243 /// getCurrentSection() - Return the current section we are emitting to.
245  return OutStreamer->getCurrentSectionOnly();
246 }
247 
249  AU.setPreservesAll();
256 }
257 
259  auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
260  MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
261 
262  // Initialize TargetLoweringObjectFile.
264  .Initialize(OutContext, TM);
265 
267  .getModuleMetadata(M);
268 
269  OutStreamer->InitSections(false);
270 
271  // Emit the version-min deployment target directive if needed.
272  //
273  // FIXME: If we end up with a collection of these sorts of Darwin-specific
274  // or ELF-specific things, it may make sense to have a platform helper class
275  // that will work with the target helper class. For now keep it here, as the
276  // alternative is duplicated code in each of the target asm printers that
277  // use the directive, where it would need the same conditionalization
278  // anyway.
279  const Triple &Target = TM.getTargetTriple();
280  OutStreamer->EmitVersionForTarget(Target, M.getSDKVersion());
281 
282  // Allow the target to emit any magic that it wants at the start of the file.
284 
285  // Very minimal debug info. It is ignored if we emit actual debug info. If we
286  // don't, this at least helps the user find where a global came from.
288  // .file "foo.c"
289  OutStreamer->EmitFileDirective(
291  }
292 
293  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
294  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
295  for (auto &I : *MI)
296  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
297  MP->beginAssembly(M, *MI, *this);
298 
299  // Emit module-level inline asm if it exists.
300  if (!M.getModuleInlineAsm().empty()) {
301  // We're at the module level. Construct MCSubtarget from the default CPU
302  // and target triple.
303  std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
306  OutStreamer->AddComment("Start of file scope inline assembly");
307  OutStreamer->AddBlankLine();
308  EmitInlineAsm(M.getModuleInlineAsm()+"\n",
310  OutStreamer->AddComment("End of file scope inline assembly");
311  OutStreamer->AddBlankLine();
312  }
313 
315  bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
316  if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
317  Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
318  DbgTimerName, DbgTimerDescription,
319  CodeViewLineTablesGroupName,
320  CodeViewLineTablesGroupDescription);
321  }
322  if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
323  DD = new DwarfDebug(this, &M);
324  DD->beginModule();
325  Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
326  DbgTimerDescription, DWARFGroupName,
327  DWARFGroupDescription);
328  }
329  }
330 
331  switch (MAI->getExceptionHandlingType()) {
335  isCFIMoveForDebugging = true;
337  break;
338  for (auto &F: M.getFunctionList()) {
339  // If the module contains any function with unwind data,
340  // .eh_frame has to be emitted.
341  // Ignore functions that won't get emitted.
342  if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) {
343  isCFIMoveForDebugging = false;
344  break;
345  }
346  }
347  break;
348  default:
349  isCFIMoveForDebugging = false;
350  break;
351  }
352 
353  EHStreamer *ES = nullptr;
354  switch (MAI->getExceptionHandlingType()) {
356  break;
359  ES = new DwarfCFIException(this);
360  break;
362  ES = new ARMException(this);
363  break;
365  switch (MAI->getWinEHEncodingType()) {
366  default: llvm_unreachable("unsupported unwinding information encoding");
368  break;
371  ES = new WinException(this);
372  break;
373  }
374  break;
376  ES = new WasmException(this);
377  break;
378  }
379  if (ES)
380  Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
381  EHTimerDescription, DWARFGroupName,
382  DWARFGroupDescription);
383 
384  // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
385  if (mdconst::extract_or_null<ConstantInt>(
386  MMI->getModule()->getModuleFlag("cfguard")))
387  Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
388  CFGuardDescription, DWARFGroupName,
389  DWARFGroupDescription);
390  return false;
391 }
392 
393 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
395  return false;
396 
397  return GV->canBeOmittedFromSymbolTable();
398 }
399 
400 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
402  switch (Linkage) {
408  if (MAI->hasWeakDefDirective()) {
409  // .globl _foo
410  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
411 
412  if (!canBeHidden(GV, *MAI))
413  // .weak_definition _foo
414  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
415  else
416  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
417  } else if (MAI->hasLinkOnceDirective()) {
418  // .globl _foo
419  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
420  //NOTE: linkonce is handled by the section the symbol was assigned to.
421  } else {
422  // .weak _foo
423  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
424  }
425  return;
427  // If external, declare as a global symbol: .globl _foo
428  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
429  return;
431  return;
433  if (MAI->hasDotLGloblDirective())
434  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_LGlobal);
435  return;
439  llvm_unreachable("Should never emit this");
440  }
441  llvm_unreachable("Unknown linkage type!");
442 }
443 
445  const GlobalValue *GV) const {
446  TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
447 }
448 
450  return TM.getSymbol(GV);
451 }
452 
453 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
455  bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
456  assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
457  "No emulated TLS variables in the common section");
458 
459  // Never emit TLS variable xyz in emulated TLS model.
460  // The initialization value is in __emutls_t.xyz instead of xyz.
461  if (IsEmuTLSVar)
462  return;
463 
464  if (GV->hasInitializer()) {
465  // Check to see if this is a special global used by LLVM, if so, emit it.
466  if (EmitSpecialLLVMGlobal(GV))
467  return;
468 
469  // Skip the emission of global equivalents. The symbol can be emitted later
470  // on by emitGlobalGOTEquivs in case it turns out to be needed.
471  if (GlobalGOTEquivs.count(getSymbol(GV)))
472  return;
473 
474  if (isVerbose()) {
475  // When printing the control variable __emutls_v.*,
476  // we don't need to print the original TLS variable name.
477  GV->printAsOperand(OutStreamer->GetCommentOS(),
478  /*PrintType=*/false, GV->getParent());
479  OutStreamer->GetCommentOS() << '\n';
480  }
481  }
482 
483  MCSymbol *GVSym = getSymbol(GV);
484  MCSymbol *EmittedSym = GVSym;
485 
486  // getOrCreateEmuTLSControlSym only creates the symbol with name and default
487  // attributes.
488  // GV's or GVSym's attributes will be used for the EmittedSym.
489  EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
490 
491  if (!GV->hasInitializer()) // External globals require no extra code.
492  return;
493 
494  GVSym->redefineIfPossible();
495  if (GVSym->isDefined() || GVSym->isVariable())
496  report_fatal_error("symbol '" + Twine(GVSym->getName()) +
497  "' is already defined");
498 
500  OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
501 
503 
504  const DataLayout &DL = GV->getParent()->getDataLayout();
505  uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
506 
507  // If the alignment is specified, we *must* obey it. Overaligning a global
508  // with a specified alignment is a prompt way to break globals emitted to
509  // sections and expected to be contiguous (e.g. ObjC metadata).
510  const Align Alignment = getGVAlignment(GV, DL);
511 
512  for (const HandlerInfo &HI : Handlers) {
513  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
514  HI.TimerGroupName, HI.TimerGroupDescription,
516  HI.Handler->setSymbolSize(GVSym, Size);
517  }
518 
519  // Handle common symbols
520  if (GVKind.isCommon()) {
521  if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
522  // .comm _foo, 42, 4
523  const bool SupportsAlignment =
525  OutStreamer->EmitCommonSymbol(GVSym, Size,
526  SupportsAlignment ? Alignment.value() : 0);
527  return;
528  }
529 
530  // Determine to which section this global should be emitted.
531  MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
532 
533  // If we have a bss global going to a section that supports the
534  // zerofill directive, do so here.
535  if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
536  TheSection->isVirtualSection()) {
537  if (Size == 0)
538  Size = 1; // zerofill of 0 bytes is undefined.
539  EmitLinkage(GV, GVSym);
540  // .zerofill __DATA, __bss, _foo, 400, 5
541  OutStreamer->EmitZerofill(TheSection, GVSym, Size, Alignment.value());
542  return;
543  }
544 
545  // If this is a BSS local symbol and we are emitting in the BSS
546  // section use .lcomm/.comm directive.
547  if (GVKind.isBSSLocal() &&
548  getObjFileLowering().getBSSSection() == TheSection) {
549  if (Size == 0)
550  Size = 1; // .comm Foo, 0 is undefined, avoid it.
551 
552  // Use .lcomm only if it supports user-specified alignment.
553  // Otherwise, while it would still be correct to use .lcomm in some
554  // cases (e.g. when Align == 1), the external assembler might enfore
555  // some -unknown- default alignment behavior, which could cause
556  // spurious differences between external and integrated assembler.
557  // Prefer to simply fall back to .local / .comm in this case.
559  // .lcomm _foo, 42
560  OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Alignment.value());
561  return;
562  }
563 
564  // .local _foo
565  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
566  // .comm _foo, 42, 4
567  const bool SupportsAlignment =
569  OutStreamer->EmitCommonSymbol(GVSym, Size,
570  SupportsAlignment ? Alignment.value() : 0);
571  return;
572  }
573 
574  // Handle thread local data for mach-o which requires us to output an
575  // additional structure of data and mangle the original symbol so that we
576  // can reference it later.
577  //
578  // TODO: This should become an "emit thread local global" method on TLOF.
579  // All of this macho specific stuff should be sunk down into TLOFMachO and
580  // stuff like "TLSExtraDataSection" should no longer be part of the parent
581  // TLOF class. This will also make it more obvious that stuff like
582  // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
583  // specific code.
584  if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
585  // Emit the .tbss symbol
586  MCSymbol *MangSym =
587  OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
588 
589  if (GVKind.isThreadBSS()) {
590  TheSection = getObjFileLowering().getTLSBSSSection();
591  OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
592  } else if (GVKind.isThreadData()) {
593  OutStreamer->SwitchSection(TheSection);
594 
595  EmitAlignment(Alignment, GV);
596  OutStreamer->EmitLabel(MangSym);
597 
599  GV->getInitializer());
600  }
601 
602  OutStreamer->AddBlankLine();
603 
604  // Emit the variable struct for the runtime.
606 
607  OutStreamer->SwitchSection(TLVSect);
608  // Emit the linkage here.
609  EmitLinkage(GV, GVSym);
610  OutStreamer->EmitLabel(GVSym);
611 
612  // Three pointers in size:
613  // - __tlv_bootstrap - used to make sure support exists
614  // - spare pointer, used when mapped by the runtime
615  // - pointer to mangled symbol above with initializer
616  unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
617  OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
618  PtrSize);
619  OutStreamer->EmitIntValue(0, PtrSize);
620  OutStreamer->EmitSymbolValue(MangSym, PtrSize);
621 
622  OutStreamer->AddBlankLine();
623  return;
624  }
625 
626  MCSymbol *EmittedInitSym = GVSym;
627 
628  OutStreamer->SwitchSection(TheSection);
629 
630  EmitLinkage(GV, EmittedInitSym);
631  EmitAlignment(Alignment, GV);
632 
633  OutStreamer->EmitLabel(EmittedInitSym);
634 
636 
638  // .size foo, 42
639  OutStreamer->emitELFSize(EmittedInitSym,
641 
642  OutStreamer->AddBlankLine();
643 }
644 
645 /// Emit the directive and value for debug thread local expression
646 ///
647 /// \p Value - The value to emit.
648 /// \p Size - The size of the integer (in bytes) to emit.
649 void AsmPrinter::EmitDebugValue(const MCExpr *Value, unsigned Size) const {
650  OutStreamer->EmitValue(Value, Size);
651 }
652 
653 /// EmitFunctionHeader - This method emits the header for the current
654 /// function.
655 void AsmPrinter::EmitFunctionHeader() {
656  const Function &F = MF->getFunction();
657 
658  if (isVerbose())
659  OutStreamer->GetCommentOS()
660  << "-- Begin function "
662 
663  // Print out constants referenced by the function
665 
666  // Print the 'header' of function.
667  OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(&F, TM));
669 
670  if (MAI->needsFunctionDescriptors() &&
673 
675  if (MAI->hasFunctionAlignment())
677 
679  OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
680 
682  OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_Cold);
683 
684  if (isVerbose()) {
685  F.printAsOperand(OutStreamer->GetCommentOS(),
686  /*PrintType=*/false, F.getParent());
687  OutStreamer->GetCommentOS() << '\n';
688  }
689 
690  // Emit the prefix data.
691  if (F.hasPrefixData()) {
692  if (MAI->hasSubsectionsViaSymbols()) {
693  // Preserving prefix data on platforms which use subsections-via-symbols
694  // is a bit tricky. Here we introduce a symbol for the prefix data
695  // and use the .alt_entry attribute to mark the function's real entry point
696  // as an alternative entry point to the prefix-data symbol.
698  OutStreamer->EmitLabel(PrefixSym);
699 
701 
702  // Emit an .alt_entry directive for the actual function symbol.
703  OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
704  } else {
706  }
707  }
708 
709  // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
710  // place prefix data before NOPs.
711  unsigned PatchableFunctionPrefix = 0;
712  unsigned PatchableFunctionEntry = 0;
713  (void)F.getFnAttribute("patchable-function-prefix")
715  .getAsInteger(10, PatchableFunctionPrefix);
716  (void)F.getFnAttribute("patchable-function-entry")
718  .getAsInteger(10, PatchableFunctionEntry);
719  if (PatchableFunctionPrefix) {
723  emitNops(PatchableFunctionPrefix);
724  } else if (PatchableFunctionEntry) {
725  // May be reassigned when emitting the body, to reference the label after
726  // the initial BTI (AArch64) or endbr32/endbr64 (x86).
728  }
729 
730  // Emit the function descriptor. This is a virtual function to allow targets
731  // to emit their specific function descriptor.
734 
735  // Emit the CurrentFnSym. This is a virtual function to allow targets to do
736  // their wild and crazy things as required.
738 
739  // If the function had address-taken blocks that got deleted, then we have
740  // references to the dangling symbols. Emit them at the start of the function
741  // so that we don't get references to undefined symbols.
742  std::vector<MCSymbol*> DeadBlockSyms;
743  MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
744  for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
745  OutStreamer->AddComment("Address taken block that was later removed");
746  OutStreamer->EmitLabel(DeadBlockSyms[i]);
747  }
748 
749  if (CurrentFnBegin) {
750  if (MAI->useAssignmentForEHBegin()) {
752  OutStreamer->EmitLabel(CurPos);
753  OutStreamer->EmitAssignment(CurrentFnBegin,
755  } else {
756  OutStreamer->EmitLabel(CurrentFnBegin);
757  }
758  }
759 
760  // Emit pre-function debug and/or EH information.
761  for (const HandlerInfo &HI : Handlers) {
762  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
763  HI.TimerGroupDescription, TimePassesIsEnabled);
764  HI.Handler->beginFunction(MF);
765  }
766 
767  // Emit the prologue data.
768  if (F.hasPrologueData())
770 }
771 
772 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
773 /// function. This can be overridden by targets as required to do custom stuff.
776 
777  // The function label could have already been emitted if two symbols end up
778  // conflicting due to asm renaming. Detect this and emit an error.
779  if (CurrentFnSym->isVariable())
781  "' is a protected alias");
782  if (CurrentFnSym->isDefined())
784  "' label emitted multiple times to assembly file");
785 
786  return OutStreamer->EmitLabel(CurrentFnSym);
787 }
788 
789 /// emitComments - Pretty-print comments for instructions.
790 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
791  const MachineFunction *MF = MI.getMF();
792  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
793 
794  // Check for spills and reloads
795 
796  // We assume a single instruction only has a spill or reload, not
797  // both.
799  if ((Size = MI.getRestoreSize(TII))) {
800  CommentOS << *Size << "-byte Reload\n";
801  } else if ((Size = MI.getFoldedRestoreSize(TII))) {
802  if (*Size)
803  CommentOS << *Size << "-byte Folded Reload\n";
804  } else if ((Size = MI.getSpillSize(TII))) {
805  CommentOS << *Size << "-byte Spill\n";
806  } else if ((Size = MI.getFoldedSpillSize(TII))) {
807  if (*Size)
808  CommentOS << *Size << "-byte Folded Spill\n";
809  }
810 
811  // Check for spill-induced copies
813  CommentOS << " Reload Reuse\n";
814 }
815 
816 /// emitImplicitDef - This method emits the specified machine instruction
817 /// that is an implicit def.
819  Register RegNo = MI->getOperand(0).getReg();
820 
821  SmallString<128> Str;
822  raw_svector_ostream OS(Str);
823  OS << "implicit-def: "
824  << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
825 
826  OutStreamer->AddComment(OS.str());
827  OutStreamer->AddBlankLine();
828 }
829 
830 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
831  std::string Str;
832  raw_string_ostream OS(Str);
833  OS << "kill:";
834  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
835  const MachineOperand &Op = MI->getOperand(i);
836  assert(Op.isReg() && "KILL instruction must have only register operands");
837  OS << ' ' << (Op.isDef() ? "def " : "killed ")
838  << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
839  }
840  AP.OutStreamer->AddComment(OS.str());
841  AP.OutStreamer->AddBlankLine();
842 }
843 
844 /// emitDebugValueComment - This method handles the target-independent form
845 /// of DBG_VALUE, returning true if it was able to do so. A false return
846 /// means the target will need to handle MI in EmitInstruction.
848  // This code handles only the 4-operand target-independent form.
849  if (MI->getNumOperands() != 4)
850  return false;
851 
852  SmallString<128> Str;
853  raw_svector_ostream OS(Str);
854  OS << "DEBUG_VALUE: ";
855 
856  const DILocalVariable *V = MI->getDebugVariable();
857  if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
858  StringRef Name = SP->getName();
859  if (!Name.empty())
860  OS << Name << ":";
861  }
862  OS << V->getName();
863  OS << " <- ";
864 
865  // The second operand is only an offset if it's an immediate.
866  bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
867  int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0;
868  const DIExpression *Expr = MI->getDebugExpression();
869  if (Expr->getNumElements()) {
870  OS << '[';
871  bool NeedSep = false;
872  for (auto Op : Expr->expr_ops()) {
873  if (NeedSep)
874  OS << ", ";
875  else
876  NeedSep = true;
877  OS << dwarf::OperationEncodingString(Op.getOp());
878  for (unsigned I = 0; I < Op.getNumArgs(); ++I)
879  OS << ' ' << Op.getArg(I);
880  }
881  OS << "] ";
882  }
883 
884  // Register or immediate value. Register 0 means undef.
885  if (MI->getOperand(0).isFPImm()) {
886  APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
887  if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
888  OS << (double)APF.convertToFloat();
889  } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
890  OS << APF.convertToDouble();
891  } else {
892  // There is no good way to print long double. Convert a copy to
893  // double. Ah well, it's only a comment.
894  bool ignored;
896  &ignored);
897  OS << "(long double) " << APF.convertToDouble();
898  }
899  } else if (MI->getOperand(0).isImm()) {
900  OS << MI->getOperand(0).getImm();
901  } else if (MI->getOperand(0).isCImm()) {
902  MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
903  } else if (MI->getOperand(0).isTargetIndex()) {
904  auto Op = MI->getOperand(0);
905  OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
906  return true;
907  } else {
908  unsigned Reg;
909  if (MI->getOperand(0).isReg()) {
910  Reg = MI->getOperand(0).getReg();
911  } else {
912  assert(MI->getOperand(0).isFI() && "Unknown operand type");
914  Offset += TFI->getFrameIndexReference(*AP.MF,
915  MI->getOperand(0).getIndex(), Reg);
916  MemLoc = true;
917  }
918  if (Reg == 0) {
919  // Suppress offset, it is not meaningful here.
920  OS << "undef";
921  // NOTE: Want this comment at start of line, don't emit with AddComment.
922  AP.OutStreamer->emitRawComment(OS.str());
923  return true;
924  }
925  if (MemLoc)
926  OS << '[';
927  OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
928  }
929 
930  if (MemLoc)
931  OS << '+' << Offset << ']';
932 
933  // NOTE: Want this comment at start of line, don't emit with AddComment.
934  AP.OutStreamer->emitRawComment(OS.str());
935  return true;
936 }
937 
938 /// This method handles the target-independent form of DBG_LABEL, returning
939 /// true if it was able to do so. A false return means the target will need
940 /// to handle MI in EmitInstruction.
942  if (MI->getNumOperands() != 1)
943  return false;
944 
945  SmallString<128> Str;
946  raw_svector_ostream OS(Str);
947  OS << "DEBUG_LABEL: ";
948 
949  const DILabel *V = MI->getDebugLabel();
950  if (auto *SP = dyn_cast<DISubprogram>(
952  StringRef Name = SP->getName();
953  if (!Name.empty())
954  OS << Name << ":";
955  }
956  OS << V->getName();
957 
958  // NOTE: Want this comment at start of line, don't emit with AddComment.
959  AP.OutStreamer->emitRawComment(OS.str());
960  return true;
961 }
962 
966  return CFI_M_EH;
967 
969  return CFI_M_Debug;
970 
971  return CFI_M_None;
972 }
973 
976 }
977 
979  ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
980  if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
981  ExceptionHandlingType != ExceptionHandling::ARM)
982  return;
983 
984  if (needsCFIMoves() == CFI_M_None)
985  return;
986 
987  // If there is no "real" instruction following this CFI instruction, skip
988  // emitting it; it would be beyond the end of the function's FDE range.
989  auto *MBB = MI.getParent();
990  auto I = std::next(MI.getIterator());
991  while (I != MBB->end() && I->isTransient())
992  ++I;
993  if (I == MBB->instr_end() &&
994  MBB->getReverseIterator() == MBB->getParent()->rbegin())
995  return;
996 
997  const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
998  unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
999  const MCCFIInstruction &CFI = Instrs[CFIIndex];
1000  emitCFIInstruction(CFI);
1001 }
1002 
1004  // The operands are the MCSymbol and the frame offset of the allocation.
1005  MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1006  int FrameOffset = MI.getOperand(1).getImm();
1007 
1008  // Emit a symbol assignment.
1009  OutStreamer->EmitAssignment(FrameAllocSym,
1010  MCConstantExpr::create(FrameOffset, OutContext));
1011 }
1012 
1015  return;
1016 
1017  MCSection *StackSizeSection =
1019  if (!StackSizeSection)
1020  return;
1021 
1022  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1023  // Don't emit functions with dynamic stack allocations.
1024  if (FrameInfo.hasVarSizedObjects())
1025  return;
1026 
1027  OutStreamer->PushSection();
1028  OutStreamer->SwitchSection(StackSizeSection);
1029 
1030  const MCSymbol *FunctionSymbol = getFunctionBegin();
1031  uint64_t StackSize = FrameInfo.getStackSize();
1032  OutStreamer->EmitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1033  OutStreamer->EmitULEB128IntValue(StackSize);
1034 
1035  OutStreamer->PopSection();
1036 }
1037 
1040  if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI->hasDebugInfo())
1041  return true;
1042 
1043  // We might emit an EH table that uses function begin and end labels even if
1044  // we don't have any landingpads.
1045  if (!MF.getFunction().hasPersonalityFn())
1046  return false;
1047  return !isNoOpWithoutInvoke(
1049 }
1050 
1051 /// EmitFunctionBody - This method emits the body and trailer for a
1052 /// function.
1054  EmitFunctionHeader();
1055 
1056  // Emit target-specific gunk before the function body.
1058 
1059  bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
1060 
1061  if (isVerbose()) {
1062  // Get MachineDominatorTree or compute it on the fly if it's unavailable
1063  MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1064  if (!MDT) {
1065  OwnedMDT = std::make_unique<MachineDominatorTree>();
1066  OwnedMDT->getBase().recalculate(*MF);
1067  MDT = OwnedMDT.get();
1068  }
1069 
1070  // Get MachineLoopInfo or compute it on the fly if it's unavailable
1071  MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1072  if (!MLI) {
1073  OwnedMLI = std::make_unique<MachineLoopInfo>();
1074  OwnedMLI->getBase().analyze(MDT->getBase());
1075  MLI = OwnedMLI.get();
1076  }
1077  }
1078 
1079  // Print out code for the function.
1080  bool HasAnyRealCode = false;
1081  int NumInstsInFunction = 0;
1082  for (auto &MBB : *MF) {
1083  // Print a label for the basic block.
1084  EmitBasicBlockStart(MBB);
1085  for (auto &MI : MBB) {
1086  // Print the assembly for the instruction.
1087  if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1088  !MI.isDebugInstr()) {
1089  HasAnyRealCode = true;
1090  ++NumInstsInFunction;
1091  }
1092 
1093  // If there is a pre-instruction symbol, emit a label for it here.
1094  if (MCSymbol *S = MI.getPreInstrSymbol())
1095  OutStreamer->EmitLabel(S);
1096 
1097  if (ShouldPrintDebugScopes) {
1098  for (const HandlerInfo &HI : Handlers) {
1099  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1100  HI.TimerGroupName, HI.TimerGroupDescription,
1102  HI.Handler->beginInstruction(&MI);
1103  }
1104  }
1105 
1106  if (isVerbose())
1107  emitComments(MI, OutStreamer->GetCommentOS());
1108 
1109  switch (MI.getOpcode()) {
1110  case TargetOpcode::CFI_INSTRUCTION:
1112  break;
1113  case TargetOpcode::LOCAL_ESCAPE:
1114  emitFrameAlloc(MI);
1115  break;
1118  case TargetOpcode::GC_LABEL:
1119  OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
1120  break;
1123  EmitInlineAsm(&MI);
1124  break;
1125  case TargetOpcode::DBG_VALUE:
1126  if (isVerbose()) {
1127  if (!emitDebugValueComment(&MI, *this))
1128  EmitInstruction(&MI);
1129  }
1130  break;
1131  case TargetOpcode::DBG_LABEL:
1132  if (isVerbose()) {
1133  if (!emitDebugLabelComment(&MI, *this))
1134  EmitInstruction(&MI);
1135  }
1136  break;
1137  case TargetOpcode::IMPLICIT_DEF:
1138  if (isVerbose()) emitImplicitDef(&MI);
1139  break;
1140  case TargetOpcode::KILL:
1141  if (isVerbose()) emitKill(&MI, *this);
1142  break;
1143  default:
1144  EmitInstruction(&MI);
1145  break;
1146  }
1147 
1148  // If there is a post-instruction symbol, emit a label for it here.
1149  if (MCSymbol *S = MI.getPostInstrSymbol())
1150  OutStreamer->EmitLabel(S);
1151 
1152  if (ShouldPrintDebugScopes) {
1153  for (const HandlerInfo &HI : Handlers) {
1154  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
1155  HI.TimerGroupName, HI.TimerGroupDescription,
1157  HI.Handler->endInstruction();
1158  }
1159  }
1160  }
1161 
1162  EmitBasicBlockEnd(MBB);
1163  }
1164 
1165  EmittedInsts += NumInstsInFunction;
1166  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
1167  MF->getFunction().getSubprogram(),
1168  &MF->front());
1169  R << ore::NV("NumInstructions", NumInstsInFunction)
1170  << " instructions in function";
1171  ORE->emit(R);
1172 
1173  // If the function is empty and the object file uses .subsections_via_symbols,
1174  // then we need to emit *something* to the function body to prevent the
1175  // labels from collapsing together. Just emit a noop.
1176  // Similarly, don't emit empty functions on Windows either. It can lead to
1177  // duplicate entries (two functions with the same RVA) in the Guard CF Table
1178  // after linking, causing the kernel not to load the binary:
1179  // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1180  // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1181  const Triple &TT = TM.getTargetTriple();
1182  if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1183  (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1184  MCInst Noop;
1185  MF->getSubtarget().getInstrInfo()->getNoop(Noop);
1186 
1187  // Targets can opt-out of emitting the noop here by leaving the opcode
1188  // unspecified.
1189  if (Noop.getOpcode()) {
1190  OutStreamer->AddComment("avoids zero-length function");
1191  emitNops(1);
1192  }
1193  }
1194 
1195  const Function &F = MF->getFunction();
1196  for (const auto &BB : F) {
1197  if (!BB.hasAddressTaken())
1198  continue;
1199  MCSymbol *Sym = GetBlockAddressSymbol(&BB);
1200  if (Sym->isDefined())
1201  continue;
1202  OutStreamer->AddComment("Address of block that was removed by CodeGen");
1203  OutStreamer->EmitLabel(Sym);
1204  }
1205 
1206  // Emit target-specific gunk after the function body.
1208 
1209  if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) ||
1211  // Create a symbol for the end of function.
1212  CurrentFnEnd = createTempSymbol("func_end");
1213  OutStreamer->EmitLabel(CurrentFnEnd);
1214  }
1215 
1216  // If the target wants a .size directive for the size of the function, emit
1217  // it.
1219  // We can get the size as difference between the function label and the
1220  // temp label.
1221  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1222  MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1224  OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1225  }
1226 
1227  for (const HandlerInfo &HI : Handlers) {
1228  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1229  HI.TimerGroupDescription, TimePassesIsEnabled);
1230  HI.Handler->markFunctionEnd();
1231  }
1232 
1233  // Print out jump tables referenced by the function.
1235 
1236  // Emit post-function debug and/or EH information.
1237  for (const HandlerInfo &HI : Handlers) {
1238  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1239  HI.TimerGroupDescription, TimePassesIsEnabled);
1240  HI.Handler->endFunction(MF);
1241  }
1242 
1243  // Emit section containing stack size metadata.
1244  emitStackSizeSection(*MF);
1245 
1247 
1248  if (isVerbose())
1249  OutStreamer->GetCommentOS() << "-- End function\n";
1250 
1251  OutStreamer->AddBlankLine();
1252 }
1253 
1254 /// Compute the number of Global Variables that uses a Constant.
1255 static unsigned getNumGlobalVariableUses(const Constant *C) {
1256  if (!C)
1257  return 0;
1258 
1259  if (isa<GlobalVariable>(C))
1260  return 1;
1261 
1262  unsigned NumUses = 0;
1263  for (auto *CU : C->users())
1264  NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1265 
1266  return NumUses;
1267 }
1268 
1269 /// Only consider global GOT equivalents if at least one user is a
1270 /// cstexpr inside an initializer of another global variables. Also, don't
1271 /// handle cstexpr inside instructions. During global variable emission,
1272 /// candidates are skipped and are emitted later in case at least one cstexpr
1273 /// isn't replaced by a PC relative GOT entry access.
1275  unsigned &NumGOTEquivUsers) {
1276  // Global GOT equivalents are unnamed private globals with a constant
1277  // pointer initializer to another global symbol. They must point to a
1278  // GlobalVariable or Function, i.e., as GlobalValue.
1279  if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1280  !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1281  !isa<GlobalValue>(GV->getOperand(0)))
1282  return false;
1283 
1284  // To be a got equivalent, at least one of its users need to be a constant
1285  // expression used by another global variable.
1286  for (auto *U : GV->users())
1287  NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1288 
1289  return NumGOTEquivUsers > 0;
1290 }
1291 
1292 /// Unnamed constant global variables solely contaning a pointer to
1293 /// another globals variable is equivalent to a GOT table entry; it contains the
1294 /// the address of another symbol. Optimize it and replace accesses to these
1295 /// "GOT equivalents" by using the GOT entry for the final global instead.
1296 /// Compute GOT equivalent candidates among all global variables to avoid
1297 /// emitting them if possible later on, after it use is replaced by a GOT entry
1298 /// access.
1300  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1301  return;
1302 
1303  for (const auto &G : M.globals()) {
1304  unsigned NumGOTEquivUsers = 0;
1305  if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1306  continue;
1307 
1308  const MCSymbol *GOTEquivSym = getSymbol(&G);
1309  GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1310  }
1311 }
1312 
1313 /// Constant expressions using GOT equivalent globals may not be eligible
1314 /// for PC relative GOT entry conversion, in such cases we need to emit such
1315 /// globals we previously omitted in EmitGlobalVariable.
1317  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1318  return;
1319 
1320  SmallVector<const GlobalVariable *, 8> FailedCandidates;
1321  for (auto &I : GlobalGOTEquivs) {
1322  const GlobalVariable *GV = I.second.first;
1323  unsigned Cnt = I.second.second;
1324  if (Cnt)
1325  FailedCandidates.push_back(GV);
1326  }
1327  GlobalGOTEquivs.clear();
1328 
1329  for (auto *GV : FailedCandidates)
1330  EmitGlobalVariable(GV);
1331 }
1332 
1333 void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
1334  const GlobalIndirectSymbol& GIS) {
1335  MCSymbol *Name = getSymbol(&GIS);
1336 
1337  if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
1338  OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1339  else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
1340  OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1341  else
1342  assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage");
1343 
1344  bool IsFunction = GIS.getValueType()->isFunctionTy();
1345 
1346  // Treat bitcasts of functions as functions also. This is important at least
1347  // on WebAssembly where object and function addresses can't alias each other.
1348  if (!IsFunction)
1349  if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol()))
1350  if (CE->getOpcode() == Instruction::BitCast)
1351  IsFunction =
1352  CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1353 
1354  // Set the symbol type to function if the alias has a function type.
1355  // This affects codegen when the aliasee is not a function.
1356  if (IsFunction)
1357  OutStreamer->EmitSymbolAttribute(Name, isa<GlobalIFunc>(GIS)
1360 
1361  EmitVisibility(Name, GIS.getVisibility());
1362 
1363  const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
1364 
1365  if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1366  OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry);
1367 
1368  // Emit the directives as assignments aka .set:
1369  OutStreamer->EmitAssignment(Name, Expr);
1370 
1371  if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1372  // If the aliasee does not correspond to a symbol in the output, i.e. the
1373  // alias is not of an object or the aliased object is private, then set the
1374  // size of the alias symbol from the type of the alias. We don't do this in
1375  // other situations as the alias and aliasee having differing types but same
1376  // size may be intentional.
1377  const GlobalObject *BaseObject = GA->getBaseObject();
1378  if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1379  (!BaseObject || BaseObject->hasPrivateLinkage())) {
1380  const DataLayout &DL = M.getDataLayout();
1381  uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1382  OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1383  }
1384  }
1385 }
1386 
1388  if (!RS.needsSection())
1389  return;
1390 
1391  remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
1392 
1393  Optional<SmallString<128>> Filename;
1394  if (Optional<StringRef> FilenameRef = RS.getFilename()) {
1395  Filename = *FilenameRef;
1396  sys::fs::make_absolute(*Filename);
1397  assert(!Filename->empty() && "The filename can't be empty.");
1398  }
1399 
1400  std::string Buf;
1401  raw_string_ostream OS(Buf);
1402  std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1403  Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename))
1404  : RemarkSerializer.metaSerializer(OS);
1405  MetaSerializer->emit();
1406 
1407  // Switch to the remarks section.
1408  MCSection *RemarksSection =
1410  OutStreamer->SwitchSection(RemarksSection);
1411 
1412  OutStreamer->EmitBinaryData(OS.str());
1413 }
1414 
1416  // Set the MachineFunction to nullptr so that we can catch attempted
1417  // accesses to MF specific features at the module level and so that
1418  // we can conditionalize accesses based on whether or not it is nullptr.
1419  MF = nullptr;
1420 
1421  // Gather all GOT equivalent globals in the module. We really need two
1422  // passes over the globals: one to compute and another to avoid its emission
1423  // in EmitGlobalVariable, otherwise we would not be able to handle cases
1424  // where the got equivalent shows up before its use.
1426 
1427  // Emit global variables.
1428  for (const auto &G : M.globals())
1430 
1431  // Emit remaining GOT equivalent globals.
1433 
1434  // Emit visibility info for declarations
1435  for (const Function &F : M) {
1436  if (!F.isDeclarationForLinker())
1437  continue;
1438  GlobalValue::VisibilityTypes V = F.getVisibility();
1440  continue;
1441 
1442  MCSymbol *Name = getSymbol(&F);
1443  EmitVisibility(Name, V, false);
1444  }
1445 
1446  // Emit the remarks section contents.
1447  // FIXME: Figure out when is the safest time to emit this section. It should
1448  // not come after debug info.
1449  if (RemarkStreamer *RS = M.getContext().getRemarkStreamer())
1450  emitRemarksSection(*RS);
1451 
1453 
1454  TLOF.emitModuleMetadata(*OutStreamer, M);
1455 
1458 
1459  // Output stubs for external and common global variables.
1461  if (!Stubs.empty()) {
1462  OutStreamer->SwitchSection(TLOF.getDataSection());
1463  const DataLayout &DL = M.getDataLayout();
1464 
1466  for (const auto &Stub : Stubs) {
1467  OutStreamer->EmitLabel(Stub.first);
1468  OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1469  DL.getPointerSize());
1470  }
1471  }
1472  }
1473 
1475  MachineModuleInfoCOFF &MMICOFF =
1477 
1478  // Output stubs for external and common global variables.
1480  if (!Stubs.empty()) {
1481  const DataLayout &DL = M.getDataLayout();
1482 
1483  for (const auto &Stub : Stubs) {
1484  SmallString<256> SectionName = StringRef(".rdata$");
1485  SectionName += Stub.first->getName();
1486  OutStreamer->SwitchSection(OutContext.getCOFFSection(
1487  SectionName,
1490  SectionKind::getReadOnly(), Stub.first->getName(),
1493  OutStreamer->EmitSymbolAttribute(Stub.first, MCSA_Global);
1494  OutStreamer->EmitLabel(Stub.first);
1495  OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1496  DL.getPointerSize());
1497  }
1498  }
1499  }
1500 
1501  // Finalize debug and EH information.
1502  for (const HandlerInfo &HI : Handlers) {
1503  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1504  HI.TimerGroupDescription, TimePassesIsEnabled);
1505  HI.Handler->endModule();
1506  }
1507  Handlers.clear();
1508  DD = nullptr;
1509 
1510  // If the target wants to know about weak references, print them all.
1511  if (MAI->getWeakRefDirective()) {
1512  // FIXME: This is not lazy, it would be nice to only print weak references
1513  // to stuff that is actually used. Note that doing so would require targets
1514  // to notice uses in operands (due to constant exprs etc). This should
1515  // happen with the MC stuff eventually.
1516 
1517  // Print out module-level global objects here.
1518  for (const auto &GO : M.global_objects()) {
1519  if (!GO.hasExternalWeakLinkage())
1520  continue;
1521  OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1522  }
1523  }
1524 
1525  // Print aliases in topological order, that is, for each alias a = b,
1526  // b must be printed before a.
1527  // This is because on some targets (e.g. PowerPC) linker expects aliases in
1528  // such an order to generate correct TOC information.
1531  for (const auto &Alias : M.aliases()) {
1532  for (const GlobalAlias *Cur = &Alias; Cur;
1533  Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1534  if (!AliasVisited.insert(Cur).second)
1535  break;
1536  AliasStack.push_back(Cur);
1537  }
1538  for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1539  emitGlobalIndirectSymbol(M, *AncestorAlias);
1540  AliasStack.clear();
1541  }
1542  for (const auto &IFunc : M.ifuncs())
1543  emitGlobalIndirectSymbol(M, IFunc);
1544 
1545  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1546  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1547  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1548  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1549  MP->finishAssembly(M, *MI, *this);
1550 
1551  // Emit llvm.ident metadata in an '.ident' directive.
1552  EmitModuleIdents(M);
1553 
1554  // Emit bytes for llvm.commandline metadata.
1555  EmitModuleCommandLines(M);
1556 
1557  // Emit __morestack address if needed for indirect calls.
1558  if (MMI->usesMorestackAddr()) {
1559  unsigned Align = 1;
1560  MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1562  /*C=*/nullptr, Align);
1563  OutStreamer->SwitchSection(ReadOnlySection);
1564 
1565  MCSymbol *AddrSymbol =
1566  OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1567  OutStreamer->EmitLabel(AddrSymbol);
1568 
1569  unsigned PtrSize = MAI->getCodePointerSize();
1570  OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1571  PtrSize);
1572  }
1573 
1574  // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1575  // split-stack is used.
1577  OutStreamer->SwitchSection(
1578  OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1579  if (MMI->hasNosplitStack())
1580  OutStreamer->SwitchSection(
1581  OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1582  }
1583 
1584  // If we don't have any trampolines, then we don't require stack memory
1585  // to be executable. Some targets have a directive to declare this.
1586  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1587  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1589  OutStreamer->SwitchSection(S);
1590 
1592  // Emit /EXPORT: flags for each exported global as necessary.
1593  const auto &TLOF = getObjFileLowering();
1594  std::string Flags;
1595 
1596  for (const GlobalValue &GV : M.global_values()) {
1597  raw_string_ostream OS(Flags);
1598  TLOF.emitLinkerFlagsForGlobal(OS, &GV);
1599  OS.flush();
1600  if (!Flags.empty()) {
1601  OutStreamer->SwitchSection(TLOF.getDrectveSection());
1602  OutStreamer->EmitBytes(Flags);
1603  }
1604  Flags.clear();
1605  }
1606 
1607  // Emit /INCLUDE: flags for each used global as necessary.
1608  if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1609  assert(LU->hasInitializer() &&
1610  "expected llvm.used to have an initializer");
1611  assert(isa<ArrayType>(LU->getValueType()) &&
1612  "expected llvm.used to be an array type");
1613  if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1614  for (const Value *Op : A->operands()) {
1615  const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1616  // Global symbols with internal or private linkage are not visible to
1617  // the linker, and thus would cause an error when the linker tried to
1618  // preserve the symbol due to the `/include:` directive.
1619  if (GV->hasLocalLinkage())
1620  continue;
1621 
1622  raw_string_ostream OS(Flags);
1623  TLOF.emitLinkerFlagsForUsed(OS, GV);
1624  OS.flush();
1625 
1626  if (!Flags.empty()) {
1627  OutStreamer->SwitchSection(TLOF.getDrectveSection());
1628  OutStreamer->EmitBytes(Flags);
1629  }
1630  Flags.clear();
1631  }
1632  }
1633  }
1634  }
1635 
1636  if (TM.Options.EmitAddrsig) {
1637  // Emit address-significance attributes for all globals.
1638  OutStreamer->EmitAddrsig();
1639  for (const GlobalValue &GV : M.global_values())
1640  if (!GV.use_empty() && !GV.isThreadLocal() &&
1641  !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") &&
1642  !GV.hasAtLeastLocalUnnamedAddr())
1643  OutStreamer->EmitAddrsigSym(getSymbol(&GV));
1644  }
1645 
1646  // Emit symbol partition specifications (ELF only).
1648  unsigned UniqueID = 0;
1649  for (const GlobalValue &GV : M.global_values()) {
1650  if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1651  GV.getVisibility() != GlobalValue::DefaultVisibility)
1652  continue;
1653 
1654  OutStreamer->SwitchSection(OutContext.getELFSection(
1655  ".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, "", ++UniqueID));
1656  OutStreamer->EmitBytes(GV.getPartition());
1657  OutStreamer->EmitZeros(1);
1658  OutStreamer->EmitValue(
1660  MAI->getCodePointerSize());
1661  }
1662  }
1663 
1664  // Allow the target to emit any magic that it wants at the end of the file,
1665  // after everything else has gone out.
1666  EmitEndOfAsmFile(M);
1667 
1668  MMI = nullptr;
1669 
1670  OutStreamer->Finish();
1671  OutStreamer->reset();
1672  OwnedMLI.reset();
1673  OwnedMDT.reset();
1674 
1675  return false;
1676 }
1677 
1679  if (!CurExceptionSym)
1680  CurExceptionSym = createTempSymbol("exception");
1681  return CurExceptionSym;
1682 }
1683 
1685  this->MF = &MF;
1686  const Function &F = MF.getFunction();
1687 
1688  // Get the function symbol.
1689  if (MAI->needsFunctionDescriptors()) {
1690  assert(TM.getTargetTriple().isOSAIX() && "Function descriptor is only"
1691  " supported on AIX.");
1692  assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
1693  " initalized first.");
1694 
1695  // Get the function entry point symbol.
1696  CurrentFnSym =
1698 
1699  MCSectionXCOFF *FnEntryPointSec =
1700  cast<MCSectionXCOFF>(getObjFileLowering().SectionForGlobal(&F, TM));
1701  // Set the containing csect.
1702  cast<MCSymbolXCOFF>(CurrentFnSym)->setContainingCsect(FnEntryPointSec);
1703  } else {
1705  }
1706 
1708  CurrentFnBegin = nullptr;
1709  CurExceptionSym = nullptr;
1710  bool NeedsLocalForSize = MAI->needsLocalForSize();
1711  if (F.hasFnAttribute("patchable-function-entry") ||
1712  needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize ||
1714  CurrentFnBegin = createTempSymbol("func_begin");
1715  if (NeedsLocalForSize)
1716  CurrentFnSymForSize = CurrentFnBegin;
1717  }
1718 
1719  ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
1720  PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1721  MBFI = (PSI && PSI->hasProfileSummary()) ?
1722  // ORE conditionally computes MBFI. If available, use it, otherwise
1723  // request it.
1724  (ORE->getBFI() ? ORE->getBFI() :
1725  &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()) :
1726  nullptr;
1727 }
1728 
1729 namespace {
1730 
1731 // Keep track the alignment, constpool entries per Section.
1732  struct SectionCPs {
1733  MCSection *S;
1734  unsigned Alignment;
1736 
1737  SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1738  };
1739 
1740 } // end anonymous namespace
1741 
1742 /// EmitConstantPool - Print to the current output stream assembly
1743 /// representations of the constants in the constant pool MCP. This is
1744 /// used to print out constants which have been "spilled to memory" by
1745 /// the code generator.
1747  const MachineConstantPool *MCP = MF->getConstantPool();
1748  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1749  if (CP.empty()) return;
1750 
1751  // Calculate sections for constant pool entries. We collect entries to go into
1752  // the same section together to reduce amount of section switch statements.
1753  SmallVector<SectionCPs, 4> CPSections;
1754  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1755  const MachineConstantPoolEntry &CPE = CP[i];
1756  unsigned Align = CPE.getAlignment();
1757 
1758  SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1759 
1760  const Constant *C = nullptr;
1761  if (!CPE.isMachineConstantPoolEntry())
1762  C = CPE.Val.ConstVal;
1763 
1765  Kind, C, Align);
1766 
1767  // The number of sections are small, just do a linear search from the
1768  // last section to the first.
1769  bool Found = false;
1770  unsigned SecIdx = CPSections.size();
1771  while (SecIdx != 0) {
1772  if (CPSections[--SecIdx].S == S) {
1773  Found = true;
1774  break;
1775  }
1776  }
1777  if (!Found) {
1778  SecIdx = CPSections.size();
1779  CPSections.push_back(SectionCPs(S, Align));
1780  }
1781 
1782  if (Align > CPSections[SecIdx].Alignment)
1783  CPSections[SecIdx].Alignment = Align;
1784  CPSections[SecIdx].CPEs.push_back(i);
1785  }
1786 
1787  // Now print stuff into the calculated sections.
1788  const MCSection *CurSection = nullptr;
1789  unsigned Offset = 0;
1790  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1791  for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1792  unsigned CPI = CPSections[i].CPEs[j];
1793  MCSymbol *Sym = GetCPISymbol(CPI);
1794  if (!Sym->isUndefined())
1795  continue;
1796 
1798  cast<MCSymbolXCOFF>(Sym)->setContainingCsect(
1799  cast<MCSectionXCOFF>(CPSections[i].S));
1800  }
1801 
1802  if (CurSection != CPSections[i].S) {
1803  OutStreamer->SwitchSection(CPSections[i].S);
1804  EmitAlignment(Align(CPSections[i].Alignment));
1805  CurSection = CPSections[i].S;
1806  Offset = 0;
1807  }
1808 
1809  MachineConstantPoolEntry CPE = CP[CPI];
1810 
1811  // Emit inter-object padding for alignment.
1812  unsigned AlignMask = CPE.getAlignment() - 1;
1813  unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1814  OutStreamer->EmitZeros(NewOffset - Offset);
1815 
1816  Type *Ty = CPE.getType();
1817  Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1818 
1819  OutStreamer->EmitLabel(Sym);
1820  if (CPE.isMachineConstantPoolEntry())
1822  else
1824  }
1825  }
1826 }
1827 
1828 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1829 /// by the current function to the current output stream.
1831  const DataLayout &DL = MF->getDataLayout();
1832  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1833  if (!MJTI) return;
1834  if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1835  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1836  if (JT.empty()) return;
1837 
1838  // Pick the directive to use to print the jump table entries, and switch to
1839  // the appropriate section.
1840  const Function &F = MF->getFunction();
1842  bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1844  F);
1845  if (JTInDiffSection) {
1846  // Drop it in the readonly section.
1847  MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
1848  OutStreamer->SwitchSection(ReadOnlySection);
1849  }
1850 
1852 
1853  // Jump tables in code sections are marked with a data_region directive
1854  // where that's supported.
1855  if (!JTInDiffSection)
1856  OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1857 
1858  for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1859  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1860 
1861  // If this jump table was deleted, ignore it.
1862  if (JTBBs.empty()) continue;
1863 
1864  // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1865  /// emit a .set directive for each unique entry.
1869  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1871  for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1872  const MachineBasicBlock *MBB = JTBBs[ii];
1873  if (!EmittedSets.insert(MBB).second)
1874  continue;
1875 
1876  // .set LJTSet, LBB32-base
1877  const MCExpr *LHS =
1879  OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1880  MCBinaryExpr::createSub(LHS, Base,
1881  OutContext));
1882  }
1883  }
1884 
1885  // On some targets (e.g. Darwin) we want to emit two consecutive labels
1886  // before each jump table. The first label is never referenced, but tells
1887  // the assembler and linker the extents of the jump table object. The
1888  // second label is actually referenced by the code.
1889  if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1890  // FIXME: This doesn't have to have any specific name, just any randomly
1891  // named and numbered local label started with 'l' would work. Simplify
1892  // GetJTISymbol.
1893  OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1894 
1895  MCSymbol* JTISymbol = GetJTISymbol(JTI);
1897  cast<MCSymbolXCOFF>(JTISymbol)->setContainingCsect(
1898  cast<MCSectionXCOFF>(TLOF.getSectionForJumpTable(F, TM)));
1899  }
1900  OutStreamer->EmitLabel(JTISymbol);
1901 
1902  for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1903  EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1904  }
1905  if (!JTInDiffSection)
1906  OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1907 }
1908 
1909 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1910 /// current stream.
1911 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1912  const MachineBasicBlock *MBB,
1913  unsigned UID) const {
1914  assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1915  const MCExpr *Value = nullptr;
1916  switch (MJTI->getEntryKind()) {
1918  llvm_unreachable("Cannot emit EK_Inline jump table entry");
1921  MJTI, MBB, UID, OutContext);
1922  break;
1924  // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1925  // .word LBB123
1926  Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1927  break;
1929  // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1930  // with a relocation as gp-relative, e.g.:
1931  // .gprel32 LBB123
1932  MCSymbol *MBBSym = MBB->getSymbol();
1933  OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1934  return;
1935  }
1936 
1938  // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1939  // with a relocation as gp-relative, e.g.:
1940  // .gpdword LBB123
1941  MCSymbol *MBBSym = MBB->getSymbol();
1942  OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1943  return;
1944  }
1945 
1947  // Each entry is the address of the block minus the address of the jump
1948  // table. This is used for PIC jump tables where gprel32 is not supported.
1949  // e.g.:
1950  // .word LBB123 - LJTI1_2
1951  // If the .set directive avoids relocations, this is emitted as:
1952  // .set L4_5_set_123, LBB123 - LJTI1_2
1953  // .word L4_5_set_123
1955  Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1956  OutContext);
1957  break;
1958  }
1959  Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1960  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1961  const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1962  Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1963  break;
1964  }
1965  }
1966 
1967  assert(Value && "Unknown entry kind!");
1968 
1969  unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1970  OutStreamer->EmitValue(Value, EntrySize);
1971 }
1972 
1973 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1974 /// special global used by LLVM. If so, emit it and return true, otherwise
1975 /// do nothing and return false.
1977  if (GV->getName() == "llvm.used") {
1978  if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1979  EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1980  return true;
1981  }
1982 
1983  // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1984  if (GV->getSection() == "llvm.metadata" ||
1986  return true;
1987 
1988  if (!GV->hasAppendingLinkage()) return false;
1989 
1990  assert(GV->hasInitializer() && "Not a special LLVM global!");
1991 
1992  if (GV->getName() == "llvm.global_ctors") {
1993  EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1994  /* isCtor */ true);
1995 
1996  return true;
1997  }
1998 
1999  if (GV->getName() == "llvm.global_dtors") {
2000  EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
2001  /* isCtor */ false);
2002 
2003  return true;
2004  }
2005 
2006  report_fatal_error("unknown special variable");
2007 }
2008 
2009 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2010 /// global in the specified llvm.used list.
2011 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
2012  // Should be an array of 'i8*'.
2013  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2014  const GlobalValue *GV =
2016  if (GV)
2017  OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2018  }
2019 }
2020 
2021 namespace {
2022 
2023 struct Structor {
2024  int Priority = 0;
2025  Constant *Func = nullptr;
2026  GlobalValue *ComdatKey = nullptr;
2027 
2028  Structor() = default;
2029 };
2030 
2031 } // end anonymous namespace
2032 
2033 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2034 /// priority.
2035 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
2036  bool isCtor) {
2037  // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is the
2038  // init priority.
2039  if (!isa<ConstantArray>(List)) return;
2040 
2041  // Sanity check the structors list.
2042  const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
2043  if (!InitList) return; // Not an array!
2044  StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
2045  if (!ETy || ETy->getNumElements() != 3 ||
2046  !isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
2047  !isa<PointerType>(ETy->getTypeAtIndex(1U)) ||
2048  !isa<PointerType>(ETy->getTypeAtIndex(2U)))
2049  return; // Not (int, ptr, ptr).
2050 
2051  // Gather the structors in a form that's convenient for sorting by priority.
2052  SmallVector<Structor, 8> Structors;
2053  for (Value *O : InitList->operands()) {
2055  if (!CS) continue; // Malformed.
2056  if (CS->getOperand(1)->isNullValue())
2057  break; // Found a null terminator, skip the rest.
2058  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2059  if (!Priority) continue; // Malformed.
2060  Structors.push_back(Structor());
2061  Structor &S = Structors.back();
2062  S.Priority = Priority->getLimitedValue(65535);
2063  S.Func = CS->getOperand(1);
2064  if (!CS->getOperand(2)->isNullValue())
2065  S.ComdatKey =
2066  dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2067  }
2068 
2069  // Emit the function pointers in the target-specific order
2070  llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2071  return L.Priority < R.Priority;
2072  });
2073  const Align Align = DL.getPointerPrefAlignment();
2074  for (Structor &S : Structors) {
2076  const MCSymbol *KeySym = nullptr;
2077  if (GlobalValue *GV = S.ComdatKey) {
2078  if (GV->isDeclarationForLinker())
2079  // If the associated variable is not defined in this module
2080  // (it might be available_externally, or have been an
2081  // available_externally definition that was dropped by the
2082  // EliminateAvailableExternally pass), some other TU
2083  // will provide its dynamic initializer.
2084  continue;
2085 
2086  KeySym = getSymbol(GV);
2087  }
2088  MCSection *OutputSection =
2089  (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2090  : Obj.getStaticDtorSection(S.Priority, KeySym));
2091  OutStreamer->SwitchSection(OutputSection);
2092  if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2093  EmitAlignment(Align);
2094  EmitXXStructor(DL, S.Func);
2095  }
2096 }
2097 
2098 void AsmPrinter::EmitModuleIdents(Module &M) {
2099  if (!MAI->hasIdentDirective())
2100  return;
2101 
2102  if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2103  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2104  const MDNode *N = NMD->getOperand(i);
2105  assert(N->getNumOperands() == 1 &&
2106  "llvm.ident metadata entry can have only one operand");
2107  const MDString *S = cast<MDString>(N->getOperand(0));
2108  OutStreamer->EmitIdent(S->getString());
2109  }
2110  }
2111 }
2112 
2113 void AsmPrinter::EmitModuleCommandLines(Module &M) {
2115  if (!CommandLine)
2116  return;
2117 
2118  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2119  if (!NMD || !NMD->getNumOperands())
2120  return;
2121 
2122  OutStreamer->PushSection();
2123  OutStreamer->SwitchSection(CommandLine);
2124  OutStreamer->EmitZeros(1);
2125  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2126  const MDNode *N = NMD->getOperand(i);
2127  assert(N->getNumOperands() == 1 &&
2128  "llvm.commandline metadata entry can have only one operand");
2129  const MDString *S = cast<MDString>(N->getOperand(0));
2130  OutStreamer->EmitBytes(S->getString());
2131  OutStreamer->EmitZeros(1);
2132  }
2133  OutStreamer->PopSection();
2134 }
2135 
2136 //===--------------------------------------------------------------------===//
2137 // Emission and print routines
2138 //
2139 
2140 /// Emit a byte directive and value.
2141 ///
2142 void AsmPrinter::emitInt8(int Value) const {
2143  OutStreamer->EmitIntValue(Value, 1);
2144 }
2145 
2146 /// Emit a short directive and value.
2147 void AsmPrinter::emitInt16(int Value) const {
2148  OutStreamer->EmitIntValue(Value, 2);
2149 }
2150 
2151 /// Emit a long directive and value.
2152 void AsmPrinter::emitInt32(int Value) const {
2153  OutStreamer->EmitIntValue(Value, 4);
2154 }
2155 
2156 /// Emit a long long directive and value.
2157 void AsmPrinter::emitInt64(uint64_t Value) const {
2158  OutStreamer->EmitIntValue(Value, 8);
2159 }
2160 
2161 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2162 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2163 /// .set if it avoids relocations.
2165  unsigned Size) const {
2166  OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2167 }
2168 
2169 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2170 /// where the size in bytes of the directive is specified by Size and Label
2171 /// specifies the label. This implicitly uses .set if it is available.
2173  unsigned Size,
2174  bool IsSectionRelative) const {
2175  if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2176  OutStreamer->EmitCOFFSecRel32(Label, Offset);
2177  if (Size > 4)
2178  OutStreamer->EmitZeros(Size - 4);
2179  return;
2180  }
2181 
2182  // Emit Label+Offset (or just Label if Offset is zero)
2183  const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2184  if (Offset)
2185  Expr = MCBinaryExpr::createAdd(
2186  Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
2187 
2188  OutStreamer->EmitValue(Expr, Size);
2189 }
2190 
2191 //===----------------------------------------------------------------------===//
2192 
2193 // EmitAlignment - Emit an alignment directive to the specified power of
2194 // two boundary. If a global value is specified, and if that global has
2195 // an explicit alignment requested, it will override the alignment request
2196 // if required for correctness.
2197 void AsmPrinter::EmitAlignment(Align Alignment, const GlobalObject *GV) const {
2198  if (GV)
2199  Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2200 
2201  if (Alignment == Align::None())
2202  return; // 1-byte aligned: no need to emit alignment.
2203 
2204  if (getCurrentSection()->getKind().isText())
2205  OutStreamer->EmitCodeAlignment(Alignment.value());
2206  else
2207  OutStreamer->EmitValueToAlignment(Alignment.value());
2208 }
2209 
2210 //===----------------------------------------------------------------------===//
2211 // Constant emission.
2212 //===----------------------------------------------------------------------===//
2213 
2215  MCContext &Ctx = OutContext;
2216 
2217  if (CV->isNullValue() || isa<UndefValue>(CV))
2218  return MCConstantExpr::create(0, Ctx);
2219 
2220  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2221  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2222 
2223  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2224  return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2225 
2226  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2228 
2229  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2230  if (!CE) {
2231  llvm_unreachable("Unknown constant value to lower!");
2232  }
2233 
2234  switch (CE->getOpcode()) {
2235  default:
2236  // If the code isn't optimized, there may be outstanding folding
2237  // opportunities. Attempt to fold the expression using DataLayout as a
2238  // last resort before giving up.
2240  if (C != CE)
2241  return lowerConstant(C);
2242 
2243  // Otherwise report the problem to the user.
2244  {
2245  std::string S;
2246  raw_string_ostream OS(S);
2247  OS << "Unsupported expression in static initializer: ";
2248  CE->printAsOperand(OS, /*PrintType=*/false,
2249  !MF ? nullptr : MF->getFunction().getParent());
2250  report_fatal_error(OS.str());
2251  }
2252  case Instruction::GetElementPtr: {
2253  // Generate a symbolic expression for the byte address
2254  APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2255  cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2256 
2257  const MCExpr *Base = lowerConstant(CE->getOperand(0));
2258  if (!OffsetAI)
2259  return Base;
2260 
2261  int64_t Offset = OffsetAI.getSExtValue();
2262  return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2263  Ctx);
2264  }
2265 
2266  case Instruction::Trunc:
2267  // We emit the value and depend on the assembler to truncate the generated
2268  // expression properly. This is important for differences between
2269  // blockaddress labels. Since the two labels are in the same function, it
2270  // is reasonable to treat their delta as a 32-bit value.
2272  case Instruction::BitCast:
2273  return lowerConstant(CE->getOperand(0));
2274 
2275  case Instruction::IntToPtr: {
2276  const DataLayout &DL = getDataLayout();
2277 
2278  // Handle casts to pointers by changing them into casts to the appropriate
2279  // integer type. This promotes constant folding and simplifies this code.
2280  Constant *Op = CE->getOperand(0);
2282  false/*ZExt*/);
2283  return lowerConstant(Op);
2284  }
2285 
2286  case Instruction::PtrToInt: {
2287  const DataLayout &DL = getDataLayout();
2288 
2289  // Support only foldable casts to/from pointers that can be eliminated by
2290  // changing the pointer to the appropriately sized integer type.
2291  Constant *Op = CE->getOperand(0);
2292  Type *Ty = CE->getType();
2293 
2294  const MCExpr *OpExpr = lowerConstant(Op);
2295 
2296  // We can emit the pointer value into this slot if the slot is an
2297  // integer slot equal to the size of the pointer.
2298  //
2299  // If the pointer is larger than the resultant integer, then
2300  // as with Trunc just depend on the assembler to truncate it.
2301  if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType()))
2302  return OpExpr;
2303 
2304  // Otherwise the pointer is smaller than the resultant integer, mask off
2305  // the high bits so we are sure to get a proper truncation if the input is
2306  // a constant expr.
2307  unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2308  const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2309  return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2310  }
2311 
2312  case Instruction::Sub: {
2313  GlobalValue *LHSGV;
2314  APInt LHSOffset;
2315  if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2316  getDataLayout())) {
2317  GlobalValue *RHSGV;
2318  APInt RHSOffset;
2319  if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2320  getDataLayout())) {
2321  const MCExpr *RelocExpr =
2322  getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2323  if (!RelocExpr)
2324  RelocExpr = MCBinaryExpr::createSub(
2325  MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
2326  MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2327  int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2328  if (Addend != 0)
2329  RelocExpr = MCBinaryExpr::createAdd(
2330  RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2331  return RelocExpr;
2332  }
2333  }
2334  }
2335  // else fallthrough
2337 
2338  // The MC library also has a right-shift operator, but it isn't consistently
2339  // signed or unsigned between different targets.
2340  case Instruction::Add:
2341  case Instruction::Mul:
2342  case Instruction::SDiv:
2343  case Instruction::SRem:
2344  case Instruction::Shl:
2345  case Instruction::And:
2346  case Instruction::Or:
2347  case Instruction::Xor: {
2348  const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2349  const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2350  switch (CE->getOpcode()) {
2351  default: llvm_unreachable("Unknown binary operator constant cast expr");
2352  case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2353  case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2354  case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2355  case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2356  case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2357  case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2358  case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2359  case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2360  case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2361  }
2362  }
2363  }
2364 }
2365 
2366 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2367  AsmPrinter &AP,
2368  const Constant *BaseCV = nullptr,
2369  uint64_t Offset = 0);
2370 
2371 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2372 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2373 
2374 /// isRepeatedByteSequence - Determine whether the given value is
2375 /// composed of a repeated sequence of identical bytes and return the
2376 /// byte value. If it is not a repeated sequence, return -1.
2379  assert(!Data.empty() && "Empty aggregates should be CAZ node");
2380  char C = Data[0];
2381  for (unsigned i = 1, e = Data.size(); i != e; ++i)
2382  if (Data[i] != C) return -1;
2383  return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2384 }
2385 
2386 /// isRepeatedByteSequence - Determine whether the given value is
2387 /// composed of a repeated sequence of identical bytes and return the
2388 /// byte value. If it is not a repeated sequence, return -1.
2389 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2390  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2391  uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2392  assert(Size % 8 == 0);
2393 
2394  // Extend the element to take zero padding into account.
2395  APInt Value = CI->getValue().zextOrSelf(Size);
2396  if (!Value.isSplat(8))
2397  return -1;
2398 
2399  return Value.zextOrTrunc(8).getZExtValue();
2400  }
2401  if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2402  // Make sure all array elements are sequences of the same repeated
2403  // byte.
2404  assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2405  Constant *Op0 = CA->getOperand(0);
2406  int Byte = isRepeatedByteSequence(Op0, DL);
2407  if (Byte == -1)
2408  return -1;
2409 
2410  // All array elements must be equal.
2411  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2412  if (CA->getOperand(i) != Op0)
2413  return -1;
2414  return Byte;
2415  }
2416 
2417  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2418  return isRepeatedByteSequence(CDS);
2419 
2420  return -1;
2421 }
2422 
2424  const ConstantDataSequential *CDS,
2425  AsmPrinter &AP) {
2426  // See if we can aggregate this into a .fill, if so, emit it as such.
2427  int Value = isRepeatedByteSequence(CDS, DL);
2428  if (Value != -1) {
2429  uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2430  // Don't emit a 1-byte object as a .fill.
2431  if (Bytes > 1)
2432  return AP.OutStreamer->emitFill(Bytes, Value);
2433  }
2434 
2435  // If this can be emitted with .ascii/.asciz, emit it as such.
2436  if (CDS->isString())
2437  return AP.OutStreamer->EmitBytes(CDS->getAsString());
2438 
2439  // Otherwise, emit the values in successive locations.
2440  unsigned ElementByteSize = CDS->getElementByteSize();
2441  if (isa<IntegerType>(CDS->getElementType())) {
2442  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2443  if (AP.isVerbose())
2444  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2445  CDS->getElementAsInteger(i));
2446  AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
2447  ElementByteSize);
2448  }
2449  } else {
2450  Type *ET = CDS->getElementType();
2451  for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2453  }
2454 
2455  unsigned Size = DL.getTypeAllocSize(CDS->getType());
2456  unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
2457  CDS->getNumElements();
2458  assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
2459  if (unsigned Padding = Size - EmittedSize)
2460  AP.OutStreamer->EmitZeros(Padding);
2461 }
2462 
2463 static void emitGlobalConstantArray(const DataLayout &DL,
2464  const ConstantArray *CA, AsmPrinter &AP,
2465  const Constant *BaseCV, uint64_t Offset) {
2466  // See if we can aggregate some values. Make sure it can be
2467  // represented as a series of bytes of the constant value.
2468  int Value = isRepeatedByteSequence(CA, DL);
2469 
2470  if (Value != -1) {
2471  uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2472  AP.OutStreamer->emitFill(Bytes, Value);
2473  }
2474  else {
2475  for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2476  emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2477  Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2478  }
2479  }
2480 }
2481 
2482 static void emitGlobalConstantVector(const DataLayout &DL,
2483  const ConstantVector *CV, AsmPrinter &AP) {
2484  for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2485  emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2486 
2487  unsigned Size = DL.getTypeAllocSize(CV->getType());
2488  unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2489  CV->getType()->getNumElements();
2490  if (unsigned Padding = Size - EmittedSize)
2491  AP.OutStreamer->EmitZeros(Padding);
2492 }
2493 
2494 static void emitGlobalConstantStruct(const DataLayout &DL,
2495  const ConstantStruct *CS, AsmPrinter &AP,
2496  const Constant *BaseCV, uint64_t Offset) {
2497  // Print the fields in successive locations. Pad to align if needed!
2498  unsigned Size = DL.getTypeAllocSize(CS->getType());
2499  const StructLayout *Layout = DL.getStructLayout(CS->getType());
2500  uint64_t SizeSoFar = 0;
2501  for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2502  const Constant *Field = CS->getOperand(i);
2503 
2504  // Print the actual field value.
2505  emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2506 
2507  // Check if padding is needed and insert one or more 0s.
2508  uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2509  uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2510  - Layout->getElementOffset(i)) - FieldSize;
2511  SizeSoFar += FieldSize + PadSize;
2512 
2513  // Insert padding - this may include padding to increase the size of the
2514  // current field up to the ABI size (if the struct is not packed) as well
2515  // as padding to ensure that the next field starts at the right offset.
2516  AP.OutStreamer->EmitZeros(PadSize);
2517  }
2518  assert(SizeSoFar == Layout->getSizeInBytes() &&
2519  "Layout of constant struct may be incorrect!");
2520 }
2521 
2522 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2523  assert(ET && "Unknown float type");
2524  APInt API = APF.bitcastToAPInt();
2525 
2526  // First print a comment with what we think the original floating-point value
2527  // should have been.
2528  if (AP.isVerbose()) {
2530  APF.toString(StrVal);
2531  ET->print(AP.OutStreamer->GetCommentOS());
2532  AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2533  }
2534 
2535  // Now iterate through the APInt chunks, emitting them in endian-correct
2536  // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2537  // floats).
2538  unsigned NumBytes = API.getBitWidth() / 8;
2539  unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2540  const uint64_t *p = API.getRawData();
2541 
2542  // PPC's long double has odd notions of endianness compared to how LLVM
2543  // handles it: p[0] goes first for *big* endian on PPC.
2544  if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2545  int Chunk = API.getNumWords() - 1;
2546 
2547  if (TrailingBytes)
2548  AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2549 
2550  for (; Chunk >= 0; --Chunk)
2551  AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2552  } else {
2553  unsigned Chunk;
2554  for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2555  AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2556 
2557  if (TrailingBytes)
2558  AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2559  }
2560 
2561  // Emit the tail padding for the long double.
2562  const DataLayout &DL = AP.getDataLayout();
2563  AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2564 }
2565 
2566 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2567  emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2568 }
2569 
2571  const DataLayout &DL = AP.getDataLayout();
2572  unsigned BitWidth = CI->getBitWidth();
2573 
2574  // Copy the value as we may massage the layout for constants whose bit width
2575  // is not a multiple of 64-bits.
2576  APInt Realigned(CI->getValue());
2577  uint64_t ExtraBits = 0;
2578  unsigned ExtraBitsSize = BitWidth & 63;
2579 
2580  if (ExtraBitsSize) {
2581  // The bit width of the data is not a multiple of 64-bits.
2582  // The extra bits are expected to be at the end of the chunk of the memory.
2583  // Little endian:
2584  // * Nothing to be done, just record the extra bits to emit.
2585  // Big endian:
2586  // * Record the extra bits to emit.
2587  // * Realign the raw data to emit the chunks of 64-bits.
2588  if (DL.isBigEndian()) {
2589  // Basically the structure of the raw data is a chunk of 64-bits cells:
2590  // 0 1 BitWidth / 64
2591  // [chunk1][chunk2] ... [chunkN].
2592  // The most significant chunk is chunkN and it should be emitted first.
2593  // However, due to the alignment issue chunkN contains useless bits.
2594  // Realign the chunks so that they contain only useless information:
2595  // ExtraBits 0 1 (BitWidth / 64) - 1
2596  // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2597  ExtraBits = Realigned.getRawData()[0] &
2598  (((uint64_t)-1) >> (64 - ExtraBitsSize));
2599  Realigned.lshrInPlace(ExtraBitsSize);
2600  } else
2601  ExtraBits = Realigned.getRawData()[BitWidth / 64];
2602  }
2603 
2604  // We don't expect assemblers to support integer data directives
2605  // for more than 64 bits, so we emit the data in at most 64-bit
2606  // quantities at a time.
2607  const uint64_t *RawData = Realigned.getRawData();
2608  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2609  uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2610  AP.OutStreamer->EmitIntValue(Val, 8);
2611  }
2612 
2613  if (ExtraBitsSize) {
2614  // Emit the extra bits after the 64-bits chunks.
2615 
2616  // Emit a directive that fills the expected size.
2617  uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2618  Size -= (BitWidth / 64) * 8;
2619  assert(Size && Size * 8 >= ExtraBitsSize &&
2620  (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2621  == ExtraBits && "Directive too small for extra bits.");
2622  AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2623  }
2624 }
2625 
2626 /// Transform a not absolute MCExpr containing a reference to a GOT
2627 /// equivalent global, by a target specific GOT pc relative access to the
2628 /// final symbol.
2629 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2630  const Constant *BaseCst,
2631  uint64_t Offset) {
2632  // The global @foo below illustrates a global that uses a got equivalent.
2633  //
2634  // @bar = global i32 42
2635  // @gotequiv = private unnamed_addr constant i32* @bar
2636  // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2637  // i64 ptrtoint (i32* @foo to i64))
2638  // to i32)
2639  //
2640  // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2641  // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2642  // form:
2643  //
2644  // foo = cstexpr, where
2645  // cstexpr := <gotequiv> - "." + <cst>
2646  // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2647  //
2648  // After canonicalization by evaluateAsRelocatable `ME` turns into:
2649  //
2650  // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2651  // gotpcrelcst := <offset from @foo base> + <cst>
2652  MCValue MV;
2653  if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2654  return;
2655  const MCSymbolRefExpr *SymA = MV.getSymA();
2656  if (!SymA)
2657  return;
2658 
2659  // Check that GOT equivalent symbol is cached.
2660  const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2661  if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2662  return;
2663 
2664  const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2665  if (!BaseGV)
2666  return;
2667 
2668  // Check for a valid base symbol
2669  const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2670  const MCSymbolRefExpr *SymB = MV.getSymB();
2671 
2672  if (!SymB || BaseSym != &SymB->getSymbol())
2673  return;
2674 
2675  // Make sure to match:
2676  //
2677  // gotpcrelcst := <offset from @foo base> + <cst>
2678  //
2679  // If gotpcrelcst is positive it means that we can safely fold the pc rel
2680  // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2681  // if the target knows how to encode it.
2682  int64_t GOTPCRelCst = Offset + MV.getConstant();
2683  if (GOTPCRelCst < 0)
2684  return;
2685  if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2686  return;
2687 
2688  // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2689  //
2690  // bar:
2691  // .long 42
2692  // gotequiv:
2693  // .quad bar
2694  // foo:
2695  // .long gotequiv - "." + <cst>
2696  //
2697  // is replaced by the target specific equivalent to:
2698  //
2699  // bar:
2700  // .long 42
2701  // foo:
2702  // .long bar@GOTPCREL+<gotpcrelcst>
2703  AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2704  const GlobalVariable *GV = Result.first;
2705  int NumUses = (int)Result.second;
2706  const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2707  const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2709  FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2710 
2711  // Update GOT equivalent usage information
2712  --NumUses;
2713  if (NumUses >= 0)
2714  AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2715 }
2716 
2717 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2718  AsmPrinter &AP, const Constant *BaseCV,
2719  uint64_t Offset) {
2720  uint64_t Size = DL.getTypeAllocSize(CV->getType());
2721 
2722  // Globals with sub-elements such as combinations of arrays and structs
2723  // are handled recursively by emitGlobalConstantImpl. Keep track of the
2724  // constant symbol base and the current position with BaseCV and Offset.
2725  if (!BaseCV && CV->hasOneUse())
2726  BaseCV = dyn_cast<Constant>(CV->user_back());
2727 
2728  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2729  return AP.OutStreamer->EmitZeros(Size);
2730 
2731  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2732  switch (Size) {
2733  case 1:
2734  case 2:
2735  case 4:
2736  case 8:
2737  if (AP.isVerbose())
2738  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2739  CI->getZExtValue());
2740  AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2741  return;
2742  default:
2744  return;
2745  }
2746  }
2747 
2748  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2749  return emitGlobalConstantFP(CFP, AP);
2750 
2751  if (isa<ConstantPointerNull>(CV)) {
2752  AP.OutStreamer->EmitIntValue(0, Size);
2753  return;
2754  }
2755 
2756  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2757  return emitGlobalConstantDataSequential(DL, CDS, AP);
2758 
2759  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2760  return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2761 
2762  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2763  return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2764 
2765  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2766  // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2767  // vectors).
2768  if (CE->getOpcode() == Instruction::BitCast)
2769  return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2770 
2771  if (Size > 8) {
2772  // If the constant expression's size is greater than 64-bits, then we have
2773  // to emit the value in chunks. Try to constant fold the value and emit it
2774  // that way.
2775  Constant *New = ConstantFoldConstant(CE, DL);
2776  if (New && New != CE)
2777  return emitGlobalConstantImpl(DL, New, AP);
2778  }
2779  }
2780 
2781  if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2782  return emitGlobalConstantVector(DL, V, AP);
2783 
2784  // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2785  // thread the streamer with EmitValue.
2786  const MCExpr *ME = AP.lowerConstant(CV);
2787 
2788  // Since lowerConstant already folded and got rid of all IR pointer and
2789  // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2790  // directly.
2792  handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2793 
2794  AP.OutStreamer->EmitValue(ME, Size);
2795 }
2796 
2797 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2799  uint64_t Size = DL.getTypeAllocSize(CV->getType());
2800  if (Size)
2801  emitGlobalConstantImpl(DL, CV, *this);
2802  else if (MAI->hasSubsectionsViaSymbols()) {
2803  // If the global has zero size, emit a single byte so that two labels don't
2804  // look like they are at the same location.
2805  OutStreamer->EmitIntValue(0, 1);
2806  }
2807 }
2808 
2810  // Target doesn't support this yet!
2811  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2812 }
2813 
2814 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2815  if (Offset > 0)
2816  OS << '+' << Offset;
2817  else if (Offset < 0)
2818  OS << Offset;
2819 }
2820 
2821 void AsmPrinter::emitNops(unsigned N) {
2822  MCInst Nop;
2823  MF->getSubtarget().getInstrInfo()->getNoop(Nop);
2824  for (; N; --N)
2825  EmitToStreamer(*OutStreamer, Nop);
2826 }
2827 
2828 //===----------------------------------------------------------------------===//
2829 // Symbol Lowering Routines.
2830 //===----------------------------------------------------------------------===//
2831 
2833  return OutContext.createTempSymbol(Name, true);
2834 }
2835 
2837  return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2838 }
2839 
2841  return MMI->getAddrLabelSymbol(BB);
2842 }
2843 
2844 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2845 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2846  if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
2847  const MachineConstantPoolEntry &CPE =
2848  MF->getConstantPool()->getConstants()[CPID];
2849  if (!CPE.isMachineConstantPoolEntry()) {
2850  const DataLayout &DL = MF->getDataLayout();
2851  SectionKind Kind = CPE.getSectionKind(&DL);
2852  const Constant *C = CPE.Val.ConstVal;
2853  unsigned Align = CPE.Alignment;
2854  if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
2855  getObjFileLowering().getSectionForConstant(DL, Kind, C, Align))) {
2856  if (MCSymbol *Sym = S->getCOMDATSymbol()) {
2857  if (Sym->isUndefined())
2858  OutStreamer->EmitSymbolAttribute(Sym, MCSA_Global);
2859  return Sym;
2860  }
2861  }
2862  }
2863  }
2864 
2865  const DataLayout &DL = getDataLayout();
2867  "CPI" + Twine(getFunctionNumber()) + "_" +
2868  Twine(CPID));
2869 }
2870 
2871 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2872 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2873  return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2874 }
2875 
2876 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2877 /// FIXME: privatize to AsmPrinter.
2878 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2879  const DataLayout &DL = getDataLayout();
2881  Twine(getFunctionNumber()) + "_" +
2882  Twine(UID) + "_set_" + Twine(MBBID));
2883 }
2884 
2886  StringRef Suffix) const {
2887  return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
2888 }
2889 
2890 /// Return the MCSymbol for the specified ExternalSymbol.
2892  SmallString<60> NameStr;
2893  Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2894  return OutContext.getOrCreateSymbol(NameStr);
2895 }
2896 
2897 /// PrintParentLoopComment - Print comments about parent loops of this one.
2899  unsigned FunctionNumber) {
2900  if (!Loop) return;
2902  OS.indent(Loop->getLoopDepth()*2)
2903  << "Parent Loop BB" << FunctionNumber << "_"
2904  << Loop->getHeader()->getNumber()
2905  << " Depth=" << Loop->getLoopDepth() << '\n';
2906 }
2907 
2908 /// PrintChildLoopComment - Print comments about child loops within
2909 /// the loop for this basic block, with nesting.
2911  unsigned FunctionNumber) {
2912  // Add child loop information
2913  for (const MachineLoop *CL : *Loop) {
2914  OS.indent(CL->getLoopDepth()*2)
2915  << "Child Loop BB" << FunctionNumber << "_"
2916  << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2917  << '\n';
2918  PrintChildLoopComment(OS, CL, FunctionNumber);
2919  }
2920 }
2921 
2922 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2924  const MachineLoopInfo *LI,
2925  const AsmPrinter &AP) {
2926  // Add loop depth information
2927  const MachineLoop *Loop = LI->getLoopFor(&MBB);
2928  if (!Loop) return;
2929 
2930  MachineBasicBlock *Header = Loop->getHeader();
2931  assert(Header && "No header for loop");
2932 
2933  // If this block is not a loop header, just print out what is the loop header
2934  // and return.
2935  if (Header != &MBB) {
2936  AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2937  Twine(AP.getFunctionNumber())+"_" +
2938  Twine(Loop->getHeader()->getNumber())+
2939  " Depth="+Twine(Loop->getLoopDepth()));
2940  return;
2941  }
2942 
2943  // Otherwise, it is a loop header. Print out information about child and
2944  // parent loops.
2945  raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2946 
2948 
2949  OS << "=>";
2950  OS.indent(Loop->getLoopDepth()*2-2);
2951 
2952  OS << "This ";
2953  if (Loop->empty())
2954  OS << "Inner ";
2955  OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2956 
2957  PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2958 }
2959 
2960 /// EmitBasicBlockStart - This method prints the label for the specified
2961 /// MachineBasicBlock, an alignment (if present) and a comment describing
2962 /// it if appropriate.
2964  // End the previous funclet and start a new one.
2965  if (MBB.isEHFuncletEntry()) {
2966  for (const HandlerInfo &HI : Handlers) {
2967  HI.Handler->endFunclet();
2968  HI.Handler->beginFunclet(MBB);
2969  }
2970  }
2971 
2972  // Emit an alignment directive for this block, if needed.
2973  const Align Alignment = MBB.getAlignment();
2974  if (Alignment != Align::None())
2975  EmitAlignment(Alignment);
2976 
2977  // If the block has its address taken, emit any labels that were used to
2978  // reference the block. It is possible that there is more than one label
2979  // here, because multiple LLVM BB's may have been RAUW'd to this block after
2980  // the references were generated.
2981  if (MBB.hasAddressTaken()) {
2982  const BasicBlock *BB = MBB.getBasicBlock();
2983  if (isVerbose())
2984  OutStreamer->AddComment("Block address taken");
2985 
2986  // MBBs can have their address taken as part of CodeGen without having
2987  // their corresponding BB's address taken in IR
2988  if (BB->hasAddressTaken())
2989  for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2990  OutStreamer->EmitLabel(Sym);
2991  }
2992 
2993  // Print some verbose block comments.
2994  if (isVerbose()) {
2995  if (const BasicBlock *BB = MBB.getBasicBlock()) {
2996  if (BB->hasName()) {
2997  BB->printAsOperand(OutStreamer->GetCommentOS(),
2998  /*PrintType=*/false, BB->getModule());
2999  OutStreamer->GetCommentOS() << '\n';
3000  }
3001  }
3002 
3003  assert(MLI != nullptr && "MachineLoopInfo should has been computed");
3004  emitBasicBlockLoopComments(MBB, MLI, *this);
3005  }
3006 
3007  // Print the main label for the block.
3008  if (MBB.pred_empty() ||
3010  !MBB.hasLabelMustBeEmitted())) {
3011  if (isVerbose()) {
3012  // NOTE: Want this comment at start of line, don't emit with AddComment.
3013  OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3014  false);
3015  }
3016  } else {
3017  if (isVerbose() && MBB.hasLabelMustBeEmitted())
3018  OutStreamer->AddComment("Label of block must be emitted");
3019  OutStreamer->EmitLabel(MBB.getSymbol());
3020  }
3021 }
3022 
3024 
3025 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
3026  bool IsDefinition) const {
3027  MCSymbolAttr Attr = MCSA_Invalid;
3028 
3029  switch (Visibility) {
3030  default: break;
3032  if (IsDefinition)
3033  Attr = MAI->getHiddenVisibilityAttr();
3034  else
3036  break;
3038  Attr = MAI->getProtectedVisibilityAttr();
3039  break;
3040  }
3041 
3042  if (Attr != MCSA_Invalid)
3043  OutStreamer->EmitSymbolAttribute(Sym, Attr);
3044 }
3045 
3046 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3047 /// exactly one predecessor and the control transfer mechanism between
3048 /// the predecessor and this block is a fall-through.
3049 bool AsmPrinter::
3051  // If this is a landing pad, it isn't a fall through. If it has no preds,
3052  // then nothing falls through to it.
3053  if (MBB->isEHPad() || MBB->pred_empty())
3054  return false;
3055 
3056  // If there isn't exactly one predecessor, it can't be a fall through.
3057  if (MBB->pred_size() > 1)
3058  return false;
3059 
3060  // The predecessor has to be immediately before this block.
3061  MachineBasicBlock *Pred = *MBB->pred_begin();
3062  if (!Pred->isLayoutSuccessor(MBB))
3063  return false;
3064 
3065  // If the block is completely empty, then it definitely does fall through.
3066  if (Pred->empty())
3067  return true;
3068 
3069  // Check the terminators in the previous blocks
3070  for (const auto &MI : Pred->terminators()) {
3071  // If it is not a simple branch, we are in a table somewhere.
3072  if (!MI.isBranch() || MI.isIndirectBranch())
3073  return false;
3074 
3075  // If we are the operands of one of the branches, this is not a fall
3076  // through. Note that targets with delay slots will usually bundle
3077  // terminators with the delay slot instruction.
3078  for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3079  if (OP->isJTI())
3080  return false;
3081  if (OP->isMBB() && OP->getMBB() == MBB)
3082  return false;
3083  }
3084  }
3085 
3086  return true;
3087 }
3088 
3089 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3090  if (!S.usesMetadata())
3091  return nullptr;
3092 
3093  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3094  gcp_map_type::iterator GCPI = GCMap.find(&S);
3095  if (GCPI != GCMap.end())
3096  return GCPI->second.get();
3097 
3098  auto Name = S.getName();
3099 
3102  E = GCMetadataPrinterRegistry::end(); I != E; ++I)
3103  if (Name == I->getName()) {
3104  std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
3105  GMP->S = &S;
3106  auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3107  return IterBool.first->second.get();
3108  }
3109 
3110  report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3111 }
3112 
3114  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3115  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3116  bool NeedsDefault = false;
3117  if (MI->begin() == MI->end())
3118  // No GC strategy, use the default format.
3119  NeedsDefault = true;
3120  else
3121  for (auto &I : *MI) {
3122  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3123  if (MP->emitStackMaps(SM, *this))
3124  continue;
3125  // The strategy doesn't have printer or doesn't emit custom stack maps.
3126  // Use the default format.
3127  NeedsDefault = true;
3128  }
3129 
3130  if (NeedsDefault)
3132 }
3133 
3134 /// Pin vtable to this file.
3136 
3138 
3139 // In the binary's "xray_instr_map" section, an array of these function entries
3140 // describes each instrumentation point. When XRay patches your code, the index
3141 // into this table will be given to your handler as a patch point identifier.
3143  const MCSymbol *CurrentFnSym) const {
3144  Out->EmitSymbolValue(Sled, Bytes);
3145  Out->EmitSymbolValue(CurrentFnSym, Bytes);
3146  auto Kind8 = static_cast<uint8_t>(Kind);
3147  Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3148  Out->EmitBinaryData(
3149  StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3150  Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3151  auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3152  assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3153  Out->EmitZeros(Padding);
3154 }
3155 
3157  if (Sleds.empty())
3158  return;
3159 
3160  auto PrevSection = OutStreamer->getCurrentSectionOnly();
3161  const Function &F = MF->getFunction();
3162  MCSection *InstMap = nullptr;
3163  MCSection *FnSledIndex = nullptr;
3165  auto Associated = dyn_cast<MCSymbolELF>(CurrentFnSym);
3166  assert(Associated != nullptr);
3168  std::string GroupName;
3169  if (F.hasComdat()) {
3170  Flags |= ELF::SHF_GROUP;
3171  GroupName = F.getComdat()->getName();
3172  }
3173 
3174  auto UniqueID = ++XRayFnUniqueID;
3175  InstMap =
3176  OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0,
3177  GroupName, UniqueID, Associated);
3178  FnSledIndex =
3179  OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0,
3180  GroupName, UniqueID, Associated);
3181  } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3182  InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3184  FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
3186  } else {
3187  llvm_unreachable("Unsupported target");
3188  }
3189 
3190  auto WordSizeBytes = MAI->getCodePointerSize();
3191 
3192  // Now we switch to the instrumentation map section. Because this is done
3193  // per-function, we are able to create an index entry that will represent the
3194  // range of sleds associated with a function.
3195  MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3196  OutStreamer->SwitchSection(InstMap);
3197  OutStreamer->EmitLabel(SledsStart);
3198  for (const auto &Sled : Sleds)
3199  Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
3200  MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3201  OutStreamer->EmitLabel(SledsEnd);
3202 
3203  // We then emit a single entry in the index per function. We use the symbols
3204  // that bound the instrumentation map as the range for a specific function.
3205  // Each entry here will be 2 * word size aligned, as we're writing down two
3206  // pointers. This should work for both 32-bit and 64-bit platforms.
3207  OutStreamer->SwitchSection(FnSledIndex);
3208  OutStreamer->EmitCodeAlignment(2 * WordSizeBytes);
3209  OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false);
3210  OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false);
3211  OutStreamer->SwitchSection(PrevSection);
3212  Sleds.clear();
3213 }
3214 
3216  SledKind Kind, uint8_t Version) {
3217  const Function &F = MI.getMF()->getFunction();
3218  auto Attr = F.getFnAttribute("function-instrument");
3219  bool LogArgs = F.hasFnAttribute("xray-log-args");
3220  bool AlwaysInstrument =
3221  Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3222  if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3223  Kind = SledKind::LOG_ARGS_ENTER;
3224  Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3225  AlwaysInstrument, &F, Version});
3226 }
3227 
3229  const Function &F = MF->getFunction();
3230  unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3231  (void)F.getFnAttribute("patchable-function-prefix")
3232  .getValueAsString()
3233  .getAsInteger(10, PatchableFunctionPrefix);
3234  (void)F.getFnAttribute("patchable-function-entry")
3235  .getValueAsString()
3236  .getAsInteger(10, PatchableFunctionEntry);
3237  if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3238  return;
3239  const unsigned PointerSize = getPointerSize();
3241  auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3242 
3243  // As of binutils 2.33, GNU as does not support section flag "o" or linkage
3244  // field "unique". Use SHF_LINK_ORDER if we are using the integrated
3245  // assembler.
3246  if (MAI->useIntegratedAssembler()) {
3247  Flags |= ELF::SHF_LINK_ORDER;
3248  std::string GroupName;
3249  if (F.hasComdat()) {
3250  Flags |= ELF::SHF_GROUP;
3251  GroupName = F.getComdat()->getName();
3252  }
3254  unsigned UniqueID =
3256  .try_emplace(Section, PatchableFunctionEntryID.size())
3257  .first->second;
3258  OutStreamer->SwitchSection(OutContext.getELFSection(
3259  "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0,
3260  GroupName, UniqueID, cast<MCSymbolELF>(CurrentFnSym)));
3261  } else {
3262  OutStreamer->SwitchSection(OutContext.getELFSection(
3263  "__patchable_function_entries", ELF::SHT_PROGBITS, Flags));
3264  }
3265  EmitAlignment(Align(PointerSize));
3266  OutStreamer->EmitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize);
3267  }
3268 }
3269 
3271  return OutStreamer->getContext().getDwarfVersion();
3272 }
3273 
3275  OutStreamer->getContext().setDwarfVersion(Version);
3276 }
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
Definition: ISDOpcodes.h:739
virtual void EmitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:454
const Function & getFunction() const
Definition: Function.h:133
void setDwarfVersion(uint16_t Version)
MachineConstantPoolValue * MachineCPVal
ProfileSummaryInfo * PSI
Definition: AsmPrinter.h:114
uint64_t CallInst * C
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:109
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:214
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:39
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:171
bool doesSetDirectiveSuppressReloc() const
Definition: MCAsmInfo.h:552
void emitInt64(uint64_t Value) const
Emit a long long directive and value.
virtual void EmitStartOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the start of their fi...
Definition: AsmPrinter.h:401
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
StringRef getTargetFeatureString() const
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool usesWindowsCFI() const
Definition: MCAsmInfo.h:616
MCSymbolAttr getHiddenVisibilityAttr() const
Definition: MCAsmInfo.h:584
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
SectionKind getKind() const
Definition: MCSection.h:111
const std::vector< MachineJumpTableEntry > & getJumpTables() const
bool isThreadData() const
Definition: SectionKind.h:153
union llvm::MachineConstantPoolEntry::@168 Val
The constant itself.
bool hasLocalLinkage() const
Definition: GlobalValue.h:445
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1210
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:54
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1620
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, const MachineLoopInfo *LI, const AsmPrinter &AP)
emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
DiagnosticInfoOptimizationBase::Argument NV
unsigned XRayFnUniqueID
Definition: AsmPrinter.h:284
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:95
bool hasDebugInfo() const
Returns true if valid debug info is present.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:329
static const char *const DbgTimerDescription
Definition: AsmPrinter.cpp:141
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1082
MCTargetOptions MCOptions
Machine level options.
virtual MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const
bool hasPrivateLinkage() const
Definition: GlobalValue.h:444
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function&#39;s prologue.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void EmitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative=false)
Special case of EmitValue that avoids the client having to pass in a MCExpr for MCSymbols.
Definition: MCStreamer.cpp:166
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:289
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
.type _foo, STT_OBJECT # aka
Definition: MCDirectives.h:25
This represents an "assembler immediate".
Definition: MCValue.h:39
static bool isGOTEquivalentCandidate(const GlobalVariable *GV, unsigned &NumGOTEquivUsers)
Only consider global GOT equivalents if at least one user is a cstexpr inside an initializer of anoth...
bool hasMachoTBSSDirective() const
Definition: MCAsmInfo.h:492
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:320
MCSection * getRemarksSection() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
Align getAlignment() const
getAlignment - Return the alignment of the function.
Not a valid directive.
Definition: MCDirectives.h:19
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
void redefineIfPossible()
Prepare this symbol to be redefined.
Definition: MCSymbol.h:223
bool needsSection() const
Check if the remarks also need to have associated metadata in a section.
MCSection * getTLSBSSSection() const
bool doesSupportDebugInformation() const
Definition: MCAsmInfo.h:596
bool hasSingleParameterDotFile() const
Definition: MCAsmInfo.h:568
bool doFinalization(Module &M) override
Shut down the asmprinter.
SmallVector< std::unique_ptr< GCStrategy >, 1 >::const_iterator iterator
Definition: GCMetadata.h:181
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:53
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static void emitGlobalConstantDataSequential(const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP)
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:624
virtual int getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:90
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
bool hasLinkOnceDirective() const
Definition: MCAsmInfo.h:580
bool isTargetIndex() const
isTargetIndex - Tests if this is a MO_TargetIndex operand.
unsigned getLoopDepth() const
Return the nesting level of this loop.
Definition: LoopInfo.h:97
Available for inspection, not emission.
Definition: GlobalValue.h:49
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1573
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:350
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:613
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:228
setjmp/longjmp based exceptions
uint16_t getDwarfVersion() const
CFIMoveType needsCFIMoves() const
Definition: AsmPrinter.cpp:963
virtual void EmitJumpTableInfo()
Print assembly representations of the jump tables used by the current function to the current output ...
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:297
unsigned Reg
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:432
virtual void EmitXXStructor(const DataLayout &DL, const Constant *CV)
Targets can override this to change how global constants that are part of a C++ static/global constru...
Definition: AsmPrinter.h:442
This file contains the declarations for metadata subclasses.
EK_Inline - Jump table entries are emitted inline at their point of use.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
virtual const TargetLowering * getTargetLowering() const
raw_ostream & indent(unsigned NumSpaces)
indent - Insert &#39;NumSpaces&#39; spaces.
bool hasDotTypeDotSizeDirective() const
Definition: MCAsmInfo.h:567
bool needsDwarfSectionOffsetDirective() const
Definition: MCAsmInfo.h:485
float convertToFloat() const
Definition: APFloat.h:1118
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2531
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
void EmitAlignment(Align Alignment, const GlobalObject *GV=nullptr) const
Emit an alignment directive to the specified power of two boundary.
Externally visible function.
Definition: GlobalValue.h:48
bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL)
If this constant is a constant offset from a global, return the global and the constant.
#define DEBUG_TYPE
Definition: AsmPrinter.cpp:136
bool hasPrologueData() const
Check whether this function has prologue data.
Definition: Function.h:761
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition: MCValue.h:52
static const char *const DWARFGroupName
Definition: AsmPrinter.cpp:138
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:543
virtual void EmitConstantPool()
Print to the current output stream assembly representations of the constants in the constant pool MCP...
bool hasDotLGloblDirective() const
Definition: MCAsmInfo.h:582
DebugLoc emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:872
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:472
unsigned getProgramPointerSize() const
F(f)
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:98
SmallVector< HandlerInfo, 1 > Handlers
A vector of all debug/EH info emitters we should use.
Definition: AsmPrinter.h:171
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1077
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:955
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
virtual void emitLinkerFlagsForUsed(raw_ostream &OS, const GlobalValue *GV) const
static const MCBinaryExpr * createMul(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:522
std::pair< const GlobalVariable *, unsigned > GOTEquivUsePair
Map global GOT equivalent MCSymbols to GlobalVariables and keep track of its number of uses by other ...
Definition: AsmPrinter.h:134
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:830
static const char *const DWARFGroupDescription
Definition: AsmPrinter.cpp:139
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool hasIdentDirective() const
Definition: MCAsmInfo.h:569
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:159
virtual void EmitDebugValue(const MCExpr *Value, unsigned Size) const
Emit the directive and value for debug thread local expression.
Definition: AsmPrinter.cpp:649
DenseMap< GCStrategy *, std::unique_ptr< GCMetadataPrinter > > gcp_map_type
Definition: AsmPrinter.cpp:154
Tentative definitions.
Definition: GlobalValue.h:58
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
Definition: Constants.h:142
virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
bool hasMachoZeroFillDirective() const
Definition: MCAsmInfo.h:491
WinEH::EncodingType getWinEHEncodingType() const
Definition: MCAsmInfo.h:603
bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition: Globals.cpp:314
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1566
Constant * getPrologueData() const
Get the prologue data associated with this function.
Definition: Function.cpp:1504
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:435
virtual MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const
const Triple & getTargetTriple() const
void emitRemarksSection(RemarkStreamer &RS)
MCSymbol * CurrentPatchableFunctionEntrySym
The symbol for the entry in __patchable_function_entires.
Definition: AsmPrinter.h:117
This represents a section on Windows.
Definition: MCSectionCOFF.h:26
remarks::RemarkSerializer & getSerializer()
Return the serializer used for this stream.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:195
The address of a basic block.
Definition: Constants.h:840
.cold (MachO)
Definition: MCDirectives.h:22
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
static const MCBinaryExpr * createXor(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:557
bool hasSection() const
Definition: GlobalValue.h:273
AnalysisUsage & addRequired()
int64_t getConstant() const
Definition: MCValue.h:46
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:585
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:48
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
A tuple of MDNodes.
Definition: Metadata.h:1334
bool hasPrefixData() const
Check whether this function has prefix data.
Definition: Function.h:752
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1712
Definition: BitVector.h:937
Emits exception handling directives.
Definition: EHStreamer.h:30
Align getPointerPrefAlignment(unsigned AS=0) const
Return target&#39;s alignment for stack-based pointers FIXME: The defaults need to be removed once all of...
Definition: DataLayout.cpp:645
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
StringRef getName() const
MCSymbol * createLinkerPrivateTempSymbol()
Create and return a new linker temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:220
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual void EmitEndOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the end of their file...
Definition: AsmPrinter.h:405
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
const HexagonInstrInfo * TII
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
static void emitGlobalConstantStruct(const DataLayout &DL, const ConstantStruct *CS, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
unsigned getPointerTypeSize(Type *Ty) const
Definition: DataLayout.h:417
MachineModuleInfoCOFF - This is a MachineModuleInfoImpl implementation for COFF targets.
const ConstantFP * getFPImm() const
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:429
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2505
Class to represent struct types.
Definition: DerivedTypes.h:238
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:160
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
virtual void emitModuleMetadata(MCStreamer &Streamer, Module &M) const
Emit the module-level metadata that the platform cares about.
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:876
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:477
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
iterator_range< iterator > terminators()
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:169
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
unsigned getNumOperands() const
Definition: Metadata.cpp:1078
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
bool getCommDirectiveSupportsAlignment() const
MCSection * getBSSSection() const
SmallVector< XRayFunctionEntry, 4 > Sleds
Definition: AsmPrinter.h:281
.local (ELF)
Definition: MCDirectives.h:36
An analysis pass which caches information about the entire Module.
Definition: GCMetadata.h:152
MCSection * getDataSection() const
MCSection * getStackSizesSection(const MCSection &TextSec) const
const char * getWeakRefDirective() const
Definition: MCAsmInfo.h:573
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Definition: DerivedTypes.h:398
.no_dead_strip (MachO)
Definition: MCDirectives.h:37
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
unsigned getCFIIndex() const
Align getAlignment() const
Return alignment of the basic block.
This file implements a class to represent arbitrary precision integral constant values and operations...
bool hasCommonLinkage() const
Definition: GlobalValue.h:449
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:725
Constant * getPrefixData() const
Get the prefix data associated with this function.
Definition: Function.cpp:1494
BlockT * getHeader() const
Definition: LoopInfo.h:105
static const char *const CodeViewLineTablesGroupName
Definition: AsmPrinter.cpp:146
unsigned getPointerSize() const
Return the pointer size from the TargetMachine.
Definition: AsmPrinter.cpp:224
Optional< unsigned > getFoldedRestoreSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a folded restore instruction.
Diagnostic information for optimization analysis remarks.
void emitNops(unsigned N)
Emit N NOP instructions.
void emitXRayTable()
Emit a table with all XRay instrumentation points.
Context object for machine code objects.
Definition: MCContext.h:65
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:265
bool hasExternalLinkage() const
Definition: GlobalValue.h:431
unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF, MachineModuleInfo *MMI)
static const MCBinaryExpr * createShl(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:537
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
Definition: AsmPrinter.cpp:248
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:86
bool isText() const
Definition: SectionKind.h:118
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:889
void EmitFunctionBody()
This method emits the body and trailer for a function.
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1632
static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS)
emitComments - Pretty-print comments for instructions.
Definition: AsmPrinter.cpp:790
const std::string & getName() const
Return the name of the GC strategy.
Definition: GCStrategy.h:86
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
.lglobl (XCOFF)
Definition: MCDirectives.h:31
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4525
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:552
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:222
MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Definition: MCContext.cpp:286
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition: APFloat.h:1187
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:454
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:574
virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:205
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table...
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset...
.type _foo, STT_GNU_IFUNC
Definition: MCDirectives.h:24
Optional< unsigned > getRestoreSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a restore instruction.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:62
.alt_entry (MachO)
Definition: MCDirectives.h:39
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:250
bool isBSSLocal() const
Definition: SectionKind.h:160
EK_BlockAddress - Each entry is a plain address of block, e.g.
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:151
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:137
BasicBlock * getBasicBlock() const
Definition: Constants.h:867
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
bool hasFunctionAlignment() const
Definition: MCAsmInfo.h:566
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:743
This class is a data container for one entry in a MachineConstantPool.
virtual const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *, const MachineBasicBlock *, unsigned, MCContext &) const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
LinkageTypes getLinkage() const
Definition: GlobalValue.h:460
virtual void EmitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
Protected struct HandlerInfo and Handlers permit target extended AsmPrinter adds their own handlers...
Definition: AsmPrinter.h:154
virtual const TargetInstrInfo * getInstrInfo() const
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:158
StringRef getTargetCPU() const
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
unsigned getAlignment() const
Definition: Globals.cpp:97
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:467
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:435
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:86
bool isVerbose() const
Return true if assembly output should contain comments.
Definition: AsmPrinter.h:213
bool hasNoDeadStrip() const
Definition: MCAsmInfo.h:570
const std::string & str() const
Definition: Triple.h:366
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2501
void emitGlobalGOTEquivs()
Constant expressions using GOT equivalent globals may not be eligible for PC relative GOT entry conve...
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:101
Value * getOperand(unsigned i) const
Definition: User.h:169
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, const Constant *BaseCst, uint64_t Offset)
Transform a not absolute MCExpr containing a reference to a GOT equivalent global, by a target specific GOT pc relative access to the final symbol.
const std::string & getSourceFileName() const
Get the module&#39;s original source file name.
Definition: Module.h:222
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false)
Definition: MCExpr.cpp:169
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
Definition: AsmPrinter.cpp:393
static void emitGlobalConstantArray(const DataLayout &DL, const ConstantArray *CA, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, unsigned Size, bool IsSectionRelative=false) const
Emit something like ".long Label+Offset" where the size in bytes of the directive is specified by Siz...
StringRef getName() const
TargetInstrInfo - Interface to description of machine instruction set.
bool hasAppendingLinkage() const
Definition: GlobalValue.h:442
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
WebAssembly Exception Handling.
virtual void getNoop(MCInst &NopInst) const
Return the noop instruction to use for a noop.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
bool hasProfileSummary()
Returns true if profile summary is available.
MCSection * getTLSExtraDataSection() const
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:539
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:147
ExternalWeak linkage description.
Definition: GlobalValue.h:57
virtual MCSection * getNonexecutableStackSection(MCContext &Ctx) const
Targets can implement this method to specify a section to switch to if the translation unit doesn&#39;t h...
Definition: MCAsmInfo.h:443
Optional< unsigned > getSpillSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a spill instruction.
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP)
emitDebugValueComment - This method handles the target-independent form of DBG_VALUE, returning true if it was able to do so.
Definition: AsmPrinter.cpp:847
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:769
void emitPatchableFunctionEntries()
#define P(N)
.data_region jt32
Definition: MCDirectives.h:61
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative...
void EmitZeros(uint64_t NumBytes)
Emit NumBytes worth of zeros.
Definition: MCStreamer.cpp:208
Streaming machine code generation interface.
Definition: MCStreamer.h:197
virtual void EmitFunctionBodyEnd()
Targets can override this to emit stuff after the last basic block in the function.
Definition: AsmPrinter.h:413
static const char *const EHTimerDescription
Definition: AsmPrinter.cpp:143
StringRef getName() const
Definition: Comdat.cpp:26
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:226
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
MCSymbol * CurrentFnBegin
Definition: AsmPrinter.h:150
.weak_def_can_be_hidden (MachO)
Definition: MCDirectives.h:46
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:236
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:121
bool getAsmPrinterFlag(CommentFlag Flag) const
Return whether an AsmPrinter flag is set.
Definition: MachineInstr.h:292
DenseMap< const MCSection *, unsigned > PatchableFunctionEntryID
Definition: AsmPrinter.h:293
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
const FunctionListType & getFunctionList() const
Get the Module&#39;s list of functions (constant).
Definition: Module.h:534
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:86
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
void takeDeletedSymbolsForFunction(const Function *F, std::vector< MCSymbol *> &Result)
If the specified function has had any references to address-taken blocks generated, but the block got deleted, return the symbol now so we can emit it.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual void emitLinkerFlagsForGlobal(raw_ostream &OS, const GlobalValue *GV) const
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:629
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
Definition: AsmPrinter.cpp:188
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
bool needsLocalForSize() const
Definition: MCAsmInfo.h:514
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
bool hasEHFunclets() const
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:654
This file contains the declarations for the subclasses of Constant, which represent the different fla...
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:486
MCSymbol * getAddrLabelSymbol(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
This is an alternative analysis pass to MachineBlockFrequencyInfo.
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const
Given a constant with the SectionKind, return a section that it should be placed in.
static Align getGVAlignment(const GlobalValue *GV, const DataLayout &DL, Align InAlign=Align::None())
Return the alignment for the specified GV.
Definition: AsmPrinter.cpp:164
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
MCSymbol * getSymbol(const GlobalValue *GV) const
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:532
unsigned EmitStackSizeSection
Emit section containing metadata on function stack sizes.
double convertToDouble() const
Definition: APFloat.h:1117
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:83
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:80
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:444
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
Represent the analysis usage information of a pass.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:47
const DILabel * getDebugLabel() const
Return the debug label referenced by this DBG_LABEL instruction.
constexpr double e
Definition: MathExtras.h:57
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:322
bool hasWeakDefCanBeHiddenDirective() const
Definition: MCAsmInfo.h:576
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit...
Definition: GlobalValue.h:370
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
LCOMM::LCOMMType getLCOMMDirectiveAlignmentType() const
Definition: MCAsmInfo.h:562
const Triple & getTargetTriple() const
bool useAssignmentForEHBegin() const
Definition: MCAsmInfo.h:513
op_range operands()
Definition: User.h:237
bool hasLinkerPrivateGlobalPrefix() const
Definition: DataLayout.h:298
static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintChildLoopComment - Print comments about child loops within the loop for this basic block...
self_iterator getIterator()
Definition: ilist_node.h:81
~AsmPrinter() override
Definition: AsmPrinter.cpp:194
Ty & getObjFileInfo()
Keep track of various per-function pieces of information for backends that would like to do so...
Constant Vector Declarations.
Definition: Constants.h:499
virtual void EmitFunctionDescriptor()
Definition: AsmPrinter.h:434
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
bool hasSubsectionsViaSymbols() const
Definition: MCAsmInfo.h:425
void emitFrameAlloc(const MachineInstr &MI)
.weak_reference (MachO)
Definition: MCDirectives.h:45
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:634
void computeGlobalGOTEquivs(Module &M)
Unnamed constant global variables solely contaning a pointer to another globals variable act like a g...
const Target & getTarget() const
static const char *const EHTimerName
Definition: AsmPrinter.cpp:142
bool hasWeakDefDirective() const
Definition: MCAsmInfo.h:574
bool isSplat(unsigned SplatSizeInBits) const
Check if the APInt consists of a repeated bit pattern.
Definition: APInt.cpp:556
void emitStackMaps(StackMaps &SM)
Emit the stack maps.
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
static constexpr const Align None()
Returns a default constructed Align which corresponds to no alignment.
Definition: Alignment.h:93
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:530
virtual const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Get the target specific PC relative GOT entry relocation.
Abstract base class for all machine specific constantpool value subclasses.
static void emitGlobalConstantVector(const DataLayout &DL, const ConstantVector *CV, AsmPrinter &AP)
size_t size() const
Definition: SmallVector.h:52
Optional< unsigned > getFoldedSpillSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a folded spill instruction.
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
virtual void markFunctionEnd()
bool isThreadBSS() const
Definition: SectionKind.h:152
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4393
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:532
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Windows x64, Windows Itanium (IA-64)
StringRef OperationEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:138
unsigned ForceDwarfFrameSection
Emit DWARF debug frame section.
static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintParentLoopComment - Print comments about parent loops of this one.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:40
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
MCSection * getDrectveSection() const
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:733
DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
unsigned first
void serializeToStackMapSection()
If there is any stack map data, create a stack map section and serialize the map info into it...
Definition: StackMaps.cpp:548
unsigned getPointerSize(unsigned AS) const
Get the pointer size for this target.
iterator_range< expr_op_iterator > expr_ops() const
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:619
bool hasWeakLinkage() const
Definition: GlobalValue.h:439
bool isBSS() const
Definition: SectionKind.h:159
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:499
const std::vector< MachineConstantPoolEntry > & getConstants() const
const APFloat & getValueAPF() const
Definition: Constants.h:302
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:396
unsigned getFunctionNumber() const
Return a unique ID for the current function.
Definition: AsmPrinter.cpp:210
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
unsigned getNumOperands() const
Definition: User.h:191
void emitCFIInstruction(const MachineInstr &MI)
Definition: AsmPrinter.cpp:978
virtual void emitImplicitDef(const MachineInstr *MI) const
Targets can override this to customize the output of IMPLICIT_DEF instructions in verbose mode...
Definition: AsmPrinter.cpp:818
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition: Constants.h:250
unsigned Alignment
The required alignment for this entry.
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static iterator begin()
MCSymbol * CurrentFnDescSym
The symbol for the current function descriptor on AIX.
Definition: AsmPrinter.h:125
virtual TargetLoweringObjectFile * getObjFileLowering() const
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition: AsmPrinter.h:135
virtual bool isVirtualSection() const =0
Check whether this section is "virtual", that is has no actual object file contents.
static const char *const CodeViewLineTablesGroupDescription
Definition: AsmPrinter.cpp:147
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Definition: Alignment.h:117
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:449
const MCSymbol & getSymbol() const
Definition: MCExpr.h:342
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
virtual void EmitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition: AsmPrinter.h:425
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:250
MachineOperand class - Representation of each machine instruction operand.
This is the base class for a remark serializer.
bool isCommon() const
Definition: SectionKind.h:163
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:2760
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition: Constants.h:656
Module.h This file contains the declarations for the Module class.
void beginModule()
Emit all Dwarf sections that should come prior to the content.
Definition: DwarfDebug.cpp:956
unsigned EmitAddrsig
Emit address-significance table.
Information about stack frame layout on the target.
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:233
bool EmitSpecialLLVMGlobal(const GlobalVariable *GV)
Check to see if the specified global is a special global used by LLVM.
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:202
uint64_t getSizeInBytes() const
Definition: DataLayout.h:593
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:568
bool usesMetadata() const
If set, appropriate metadata tables must be emitted by the back-end (assembler, JIT, or otherwise).
Definition: GCStrategy.h:117
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:203
void emitInt32(int Value) const
Emit a long directive and value.
MCSymbolAttr
Definition: MCDirectives.h:18
void print(raw_ostream &OS, bool isSigned) const
Definition: APInt.cpp:2299
int64_t getImm() const
MachineDominatorTree * MDT
This is a pointer to the current MachineLoopInfo.
Definition: AsmPrinter.h:104
unsigned pred_size() const
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:605
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:837
This file contains constants used for implementing Dwarf debug support.
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:241
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
Definition: APInt.h:69
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character &#39;\1&#39;, drop it.
Definition: GlobalValue.h:481
virtual void EmitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:409
MCSymbol * getCurExceptionSym()
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
bool isOSBinFormatXCOFF() const
Tests whether the OS uses the XCOFF binary format.
Definition: Triple.h:644
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
void setPreservesAll()
Set by analyses that do not transform their input at all.
iterator_range< user_iterator > users()
Definition: Value.h:420
bool useIntegratedAssembler() const
Return true if assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:640
unsigned getNumElements() const
Streamer for remarks.
bool hasComdat() const
Definition: GlobalObject.h:119
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition: Constants.h:432
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
FunctionNumber(functionNumber)
Definition: LLParser.cpp:2836
iterator end() const
Definition: GCMetadata.h:195
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:271
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP)
This method handles the target-independent form of DBG_LABEL, returning true if it was able to do so...
Definition: AsmPrinter.cpp:941
Iterators for registry entries.
Definition: Registry.h:83
virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:691
const Comdat * getComdat() const
Definition: GlobalObject.h:120
LoopT * getParentLoop() const
Definition: LoopInfo.h:106
MachineLoopInfo * MLI
This is a pointer to the current MachineLoopInfo.
Definition: AsmPrinter.h:107
Representation of each machine instruction.
Definition: MachineInstr.h:63
static const char *const CFGuardName
Definition: AsmPrinter.cpp:144
static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, AsmPrinter &AP, const Constant *BaseCV=nullptr, uint64_t Offset=0)
void emitInitialRawDwarfLocDirective(const MachineFunction &MF)
Emits inital debug location directive.
Definition: AsmPrinter.cpp:237
void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const
This emits linkage information about GVSym based on GV, if this is supported by the target...
Definition: AsmPrinter.cpp:400
virtual std::unique_ptr< MetaSerializer > metaSerializer(raw_ostream &OS, Optional< StringRef > ExternalFilename=None)=0
Return the corresponding metadata serializer.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
Definition: AsmPrinter.cpp:258
GCStrategy describes a garbage collector algorithm&#39;s code generation requirements, and provides overridable hooks for those needs which cannot be abstractly described.
Definition: GCStrategy.h:66
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:215
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:607
SequentialType * getType() const
Specialize the getType() method to always return a SequentialType, which reduces the amount of castin...
Definition: Constants.h:633
APFloat getElementAsAPFloat(unsigned i) const
If this is a sequential container of floating point type, return the specified element as an APFloat...
Definition: Constants.cpp:2808
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:588
.type _foo,
Definition: MCDirectives.h:30
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:130
iterator begin() const
begin/end - Iterators for used strategies.
Definition: GCMetadata.h:194
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4290
bool isEHPad() const
Returns true if the block is a landing pad.
Optional< StringRef > getFilename() const
Return the filename that the remark diagnostics are emitted to.
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:220
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
bool isPositionIndependent() const
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
VectorType * getType() const
Specialize the getType() method to always return a VectorType, which reduces the amount of casting ne...
Definition: Constants.h:521
.type _foo, STT_FUNC # aka
Definition: MCDirectives.h:23
MCSymbol * GetJTSetSymbol(unsigned UID, unsigned MBBID) const
Return the symbol for the specified jump table .set FIXME: privatize to AsmPrinter.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
TargetOptions Options
virtual ~AsmPrinterHandler()
Pin vtable to this file.
No exception support.
const NodeList & List
Definition: RDFGraph.cpp:201
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
Windows Exception Handling.
static unsigned getNumGlobalVariableUses(const Constant *C)
Compute the number of Global Variables that uses a Constant.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
virtual const TargetFrameLowering * getFrameLowering() const
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
iterator end()
Definition: DenseMap.h:82
Generic base class for all target subtargets.
SectionKind getSectionKind(const DataLayout *DL) const
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
static gcp_map_type & getGCMap(void *&P)
Definition: AsmPrinter.cpp:156
static const MCBinaryExpr * createMod(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:517
void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const
Emit something like ".long Hi-Lo" where the size in bytes of the directive is specified by Size and H...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Type * getValueType() const
Definition: GlobalValue.h:279
static const char *const CFGuardDescription
Definition: AsmPrinter.cpp:145
uint32_t Size
Definition: Profile.cpp:46
bool hasAltEntry() const
Definition: MCAsmInfo.h:571
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
const Constant * getIndirectSymbol() const
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
TypeSize getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition: DataLayout.h:499
.weak_definition (MachO)
Definition: MCDirectives.h:44
virtual void EmitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
Definition: AsmPrinter.cpp:774
MachineBlockFrequencyInfo * MBFI
Definition: AsmPrinter.h:112
const Module * getModule() const
bool hasLabelMustBeEmitted() const
Test whether this block must have its label emitted.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:249
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:286
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
bool empty() const
Definition: LoopInfo.h:151
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:196
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:411
DILocalScope * getScope() const
Get the local scope for this label.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool needsFunctionDescriptors() const
Definition: MCAsmInfo.h:668
INLINEASM_BR - Terminator version of inline asm. Used by asm-goto.
Definition: ISDOpcodes.h:728
void stable_sort(R &&Range)
Definition: STLExtras.h:1306
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:516
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:424
MCSymbol * getMCSymbol() const
void EmitGlobalConstant(const DataLayout &DL, const Constant *CV)
Print a general LLVM constant to the .s file.
void emitInt8(int Value) const
Emit a byte directive and value.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1484
JTEntryKind getEntryKind() const
static const unsigned Nop
Instruction opcodes emitted via means other than CodeGen.
bool isThreadLocal() const
Definition: SectionKind.h:148
bool hasInitializer() const
Definitions have initializers, declarations don&#39;t.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
ExceptionHandling
Windows CE ARM, PowerPC, SH3, SH4.
static const char *const DbgTimerName
Definition: AsmPrinter.cpp:140
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:279
const DILocalVariable * getDebugVariable() const
Return the debug variable referenced by this DBG_VALUE instruction.
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:602
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:333
static iterator end()
Definition: Registry.h:99
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition: AsmPrinter.h:130
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:111
const DataLayout & getDataLayout() const
Return information about data layout.
Definition: AsmPrinter.cpp:218
Type * getElementType() const
Definition: DerivedTypes.h:399
GCMetadataPrinter - Emits GC metadata as assembly code.
bool isThreadLocal() const
If the value is "Thread Local", its value isn&#39;t shared by the threads.
Definition: GlobalValue.h:250
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
iterator_range< global_iterator > globals()
Definition: Module.h:588
IRTranslator LLVM IR MI
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition: AsmPrinter.h:110
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:433
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
A single uniqued string.
Definition: Metadata.h:604
virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative...
APInt bitcastToAPInt() const
Definition: APFloat.h:1114
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2524
DWARF-like instruction based exceptions.
Register getReg() const
getReg - Returns the register number.
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: Pass.h:309
bool isBigEndian() const
Definition: DataLayout.h:233
const MCSection * getCurrentSection() const
Return the current section we are emitting to.
Definition: AsmPrinter.cpp:244
void EmitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition=true) const
This emits visibility information about symbol, if this is supported by the target.
unsigned getOpcode() const
Definition: MCInst.h:172
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
DILocalScope * getScope() const
Get the local scope for this variable.
VersionTuple getSDKVersion() const
Get the build SDK version metadata.
Definition: Module.cpp:589
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1083
void emit(int, MCStreamer *, const MCSymbol *) const
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
const ConstantInt * getCImm() const
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:150
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
MCSymbolAttr getHiddenDeclarationVisibilityAttr() const
Definition: MCAsmInfo.h:586
static SectionKind getReadOnly()
Definition: SectionKind.h:181
MCSymbol * createTempSymbol(const Twine &Name) const
MCSymbolAttr getProtectedVisibilityAttr() const
Definition: MCAsmInfo.h:590
StructType * getType() const
Specialization - reduce amount of casting.
Definition: Constants.h:486
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
const uint64_t Version
Definition: InstrProf.h:980
void emitStackSizeSection(const MachineFunction &MF)
bool use_empty() const
Definition: Value.h:343
#define OP(n)
Definition: regex2.h:73
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase, but as an MCExpr.
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:277
.end_data_region
Definition: MCDirectives.h:62
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol...
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
User * user_back()
Definition: Value.h:406
void emitInt16(int Value) const
Emit a short directive and value.
This class contains meta information specific to a module.
This file describes how to lower LLVM code to machine code.
Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition: Type.cpp:536
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:2849
MCSubtargetInfo & getSubtargetCopy(const MCSubtargetInfo &STI)
Definition: MCContext.cpp:575