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