LLVM  4.0.0
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 "CodeViewDebug.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "WinException.h"
19 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCExpr.h"
38 #include "llvm/MC/MCInst.h"
39 #include "llvm/MC/MCSection.h"
40 #include "llvm/MC/MCSectionELF.h"
41 #include "llvm/MC/MCSectionMachO.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbolELF.h"
44 #include "llvm/MC/MCValue.h"
46 #include "llvm/Support/Format.h"
49 #include "llvm/Support/Timer.h"
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "asm-printer"
59 
60 static const char *const DWARFGroupName = "dwarf";
61 static const char *const DWARFGroupDescription = "DWARF Emission";
62 static const char *const DbgTimerName = "emit";
63 static const char *const DbgTimerDescription = "Debug Info Emission";
64 static const char *const EHTimerName = "write_exception";
65 static const char *const EHTimerDescription = "DWARF Exception Writer";
66 static const char *const CodeViewLineTablesGroupName = "linetables";
67 static const char *const CodeViewLineTablesGroupDescription =
68  "CodeView Line Tables";
69 
70 STATISTIC(EmittedInsts, "Number of machine instrs printed");
71 
72 char AsmPrinter::ID = 0;
73 
75 static gcp_map_type &getGCMap(void *&P) {
76  if (!P)
77  P = new gcp_map_type();
78  return *(gcp_map_type*)P;
79 }
80 
81 
82 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
83 /// value in log2 form. This rounds up to the preferred alignment if possible
84 /// and legal.
85 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
86  unsigned InBits = 0) {
87  unsigned NumBits = 0;
88  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
89  NumBits = DL.getPreferredAlignmentLog(GVar);
90 
91  // If InBits is specified, round it to it.
92  if (InBits > NumBits)
93  NumBits = InBits;
94 
95  // If the GV has a specified alignment, take it into account.
96  if (GV->getAlignment() == 0)
97  return NumBits;
98 
99  unsigned GVAlign = Log2_32(GV->getAlignment());
100 
101  // If the GVAlign is larger than NumBits, or if we are required to obey
102  // NumBits because the GV has an assigned section, obey it.
103  if (GVAlign > NumBits || GV->hasSection())
104  NumBits = GVAlign;
105  return NumBits;
106 }
107 
108 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
109  : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
110  OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)),
111  isCFIMoveForDebugging(false), LastMI(nullptr), LastFn(0), Counter(~0U) {
112  DD = nullptr;
113  MMI = nullptr;
114  LI = nullptr;
115  MF = nullptr;
116  CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr;
117  CurrentFnBegin = nullptr;
118  CurrentFnEnd = nullptr;
119  GCMetadataPrinters = nullptr;
120  VerboseAsm = OutStreamer->isVerboseAsm();
121 }
122 
124  assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
125 
126  if (GCMetadataPrinters) {
127  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
128 
129  delete &GCMap;
130  GCMetadataPrinters = nullptr;
131  }
132 }
133 
135  return TM.isPositionIndependent();
136 }
137 
138 /// getFunctionNumber - Return a unique ID for the current function.
139 ///
141  return MF->getFunctionNumber();
142 }
143 
145  return *TM.getObjFileLowering();
146 }
147 
149  return MMI->getModule()->getDataLayout();
150 }
151 
152 // Do not use the cached DataLayout because some client use it without a Module
153 // (llvm-dsymutil, llvm-dwarfdump).
154 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); }
155 
157  assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
158  return MF->getSubtarget<MCSubtargetInfo>();
159 }
160 
163 }
164 
165 /// getCurrentSection() - Return the current section we are emitting to.
167  return OutStreamer->getCurrentSectionOnly();
168 }
169 
171  AU.setPreservesAll();
175  if (isVerbose())
177 }
178 
180  MMI = getAnalysisIfAvailable<MachineModuleInfo>();
181 
182  // Initialize TargetLoweringObjectFile.
184  .Initialize(OutContext, TM);
185 
186  OutStreamer->InitSections(false);
187 
188  // Emit the version-min deplyment target directive if needed.
189  //
190  // FIXME: If we end up with a collection of these sorts of Darwin-specific
191  // or ELF-specific things, it may make sense to have a platform helper class
192  // that will work with the target helper class. For now keep it here, as the
193  // alternative is duplicated code in each of the target asm printers that
194  // use the directive, where it would need the same conditionalization
195  // anyway.
196  const Triple &TT = TM.getTargetTriple();
197  // If there is a version specified, Major will be non-zero.
198  if (TT.isOSDarwin() && TT.getOSMajorVersion() != 0) {
199  unsigned Major, Minor, Update;
200  MCVersionMinType VersionType;
201  if (TT.isWatchOS()) {
202  VersionType = MCVM_WatchOSVersionMin;
203  TT.getWatchOSVersion(Major, Minor, Update);
204  } else if (TT.isTvOS()) {
205  VersionType = MCVM_TvOSVersionMin;
206  TT.getiOSVersion(Major, Minor, Update);
207  } else if (TT.isMacOSX()) {
208  VersionType = MCVM_OSXVersionMin;
209  if (!TT.getMacOSXVersion(Major, Minor, Update))
210  Major = 0;
211  } else {
212  VersionType = MCVM_IOSVersionMin;
213  TT.getiOSVersion(Major, Minor, Update);
214  }
215  if (Major != 0)
216  OutStreamer->EmitVersionMin(VersionType, Major, Minor, Update);
217  }
218 
219  // Allow the target to emit any magic that it wants at the start of the file.
221 
222  // Very minimal debug info. It is ignored if we emit actual debug info. If we
223  // don't, this at least helps the user find where a global came from.
225  // .file "foo.c"
226  OutStreamer->EmitFileDirective(M.getModuleIdentifier());
227  }
228 
229  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
230  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
231  for (auto &I : *MI)
232  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
233  MP->beginAssembly(M, *MI, *this);
234 
235  // Emit module-level inline asm if it exists.
236  if (!M.getModuleInlineAsm().empty()) {
237  // We're at the module level. Construct MCSubtarget from the default CPU
238  // and target triple.
239  std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
242  OutStreamer->AddComment("Start of file scope inline assembly");
243  OutStreamer->AddBlankLine();
244  EmitInlineAsm(M.getModuleInlineAsm()+"\n",
246  OutStreamer->AddComment("End of file scope inline assembly");
247  OutStreamer->AddBlankLine();
248  }
249 
251  bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
252  if (EmitCodeView && (TM.getTargetTriple().isKnownWindowsMSVCEnvironment() ||
254  Handlers.push_back(HandlerInfo(new CodeViewDebug(this),
258  }
259  if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
260  DD = new DwarfDebug(this, &M);
261  DD->beginModule();
262  Handlers.push_back(HandlerInfo(DD, DbgTimerName, DbgTimerDescription,
264  }
265  }
266 
267  switch (MAI->getExceptionHandlingType()) {
271  isCFIMoveForDebugging = true;
273  break;
274  for (auto &F: M.getFunctionList()) {
275  // If the module contains any function with unwind data,
276  // .eh_frame has to be emitted.
277  // Ignore functions that won't get emitted.
278  if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) {
279  isCFIMoveForDebugging = false;
280  break;
281  }
282  }
283  break;
284  default:
285  isCFIMoveForDebugging = false;
286  break;
287  }
288 
289  EHStreamer *ES = nullptr;
290  switch (MAI->getExceptionHandlingType()) {
292  break;
295  ES = new DwarfCFIException(this);
296  break;
298  ES = new ARMException(this);
299  break;
301  switch (MAI->getWinEHEncodingType()) {
302  default: llvm_unreachable("unsupported unwinding information encoding");
304  break;
307  ES = new WinException(this);
308  break;
309  }
310  break;
311  }
312  if (ES)
313  Handlers.push_back(HandlerInfo(ES, EHTimerName, EHTimerDescription,
315  return false;
316 }
317 
318 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
320  return false;
321 
322  return canBeOmittedFromSymbolTable(GV);
323 }
324 
325 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
326  GlobalValue::LinkageTypes Linkage = GV->getLinkage();
327  switch (Linkage) {
333  if (MAI->hasWeakDefDirective()) {
334  // .globl _foo
335  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
336 
337  if (!canBeHidden(GV, *MAI))
338  // .weak_definition _foo
339  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
340  else
341  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
342  } else if (MAI->hasLinkOnceDirective()) {
343  // .globl _foo
344  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
345  //NOTE: linkonce is handled by the section the symbol was assigned to.
346  } else {
347  // .weak _foo
348  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
349  }
350  return;
352  // If external, declare as a global symbol: .globl _foo
353  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
354  return;
357  return;
361  llvm_unreachable("Should never emit this");
362  }
363  llvm_unreachable("Unknown linkage type!");
364 }
365 
367  const GlobalValue *GV) const {
368  TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
369 }
370 
372  return TM.getSymbol(GV);
373 }
374 
375 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
377  bool IsEmuTLSVar = TM.Options.EmulatedTLS && GV->isThreadLocal();
378  assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
379  "No emulated TLS variables in the common section");
380 
381  // Never emit TLS variable xyz in emulated TLS model.
382  // The initialization value is in __emutls_t.xyz instead of xyz.
383  if (IsEmuTLSVar)
384  return;
385 
386  if (GV->hasInitializer()) {
387  // Check to see if this is a special global used by LLVM, if so, emit it.
388  if (EmitSpecialLLVMGlobal(GV))
389  return;
390 
391  // Skip the emission of global equivalents. The symbol can be emitted later
392  // on by emitGlobalGOTEquivs in case it turns out to be needed.
393  if (GlobalGOTEquivs.count(getSymbol(GV)))
394  return;
395 
396  if (isVerbose()) {
397  // When printing the control variable __emutls_v.*,
398  // we don't need to print the original TLS variable name.
399  GV->printAsOperand(OutStreamer->GetCommentOS(),
400  /*PrintType=*/false, GV->getParent());
401  OutStreamer->GetCommentOS() << '\n';
402  }
403  }
404 
405  MCSymbol *GVSym = getSymbol(GV);
406  MCSymbol *EmittedSym = GVSym;
407 
408  // getOrCreateEmuTLSControlSym only creates the symbol with name and default
409  // attributes.
410  // GV's or GVSym's attributes will be used for the EmittedSym.
411  EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
412 
413  if (!GV->hasInitializer()) // External globals require no extra code.
414  return;
415 
416  GVSym->redefineIfPossible();
417  if (GVSym->isDefined() || GVSym->isVariable())
418  report_fatal_error("symbol '" + Twine(GVSym->getName()) +
419  "' is already defined");
420 
422  OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
423 
425 
426  const DataLayout &DL = GV->getParent()->getDataLayout();
427  uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
428 
429  // If the alignment is specified, we *must* obey it. Overaligning a global
430  // with a specified alignment is a prompt way to break globals emitted to
431  // sections and expected to be contiguous (e.g. ObjC metadata).
432  unsigned AlignLog = getGVAlignmentLog2(GV, DL);
433 
434  for (const HandlerInfo &HI : Handlers) {
435  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
436  HI.TimerGroupName, HI.TimerGroupDescription,
438  HI.Handler->setSymbolSize(GVSym, Size);
439  }
440 
441  // Handle common symbols
442  if (GVKind.isCommon()) {
443  if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
444  unsigned Align = 1 << AlignLog;
446  Align = 0;
447 
448  // .comm _foo, 42, 4
449  OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
450  return;
451  }
452 
453  // Determine to which section this global should be emitted.
454  MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
455 
456  // If we have a bss global going to a section that supports the
457  // zerofill directive, do so here.
458  if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
459  TheSection->isVirtualSection()) {
460  if (Size == 0)
461  Size = 1; // zerofill of 0 bytes is undefined.
462  unsigned Align = 1 << AlignLog;
463  EmitLinkage(GV, GVSym);
464  // .zerofill __DATA, __bss, _foo, 400, 5
465  OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
466  return;
467  }
468 
469  // If this is a BSS local symbol and we are emitting in the BSS
470  // section use .lcomm/.comm directive.
471  if (GVKind.isBSSLocal() &&
472  getObjFileLowering().getBSSSection() == TheSection) {
473  if (Size == 0)
474  Size = 1; // .comm Foo, 0 is undefined, avoid it.
475  unsigned Align = 1 << AlignLog;
476 
477  // Use .lcomm only if it supports user-specified alignment.
478  // Otherwise, while it would still be correct to use .lcomm in some
479  // cases (e.g. when Align == 1), the external assembler might enfore
480  // some -unknown- default alignment behavior, which could cause
481  // spurious differences between external and integrated assembler.
482  // Prefer to simply fall back to .local / .comm in this case.
484  // .lcomm _foo, 42
485  OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
486  return;
487  }
488 
489  if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
490  Align = 0;
491 
492  // .local _foo
493  OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
494  // .comm _foo, 42, 4
495  OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
496  return;
497  }
498 
499  // Handle thread local data for mach-o which requires us to output an
500  // additional structure of data and mangle the original symbol so that we
501  // can reference it later.
502  //
503  // TODO: This should become an "emit thread local global" method on TLOF.
504  // All of this macho specific stuff should be sunk down into TLOFMachO and
505  // stuff like "TLSExtraDataSection" should no longer be part of the parent
506  // TLOF class. This will also make it more obvious that stuff like
507  // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
508  // specific code.
509  if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
510  // Emit the .tbss symbol
511  MCSymbol *MangSym =
512  OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
513 
514  if (GVKind.isThreadBSS()) {
515  TheSection = getObjFileLowering().getTLSBSSSection();
516  OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
517  } else if (GVKind.isThreadData()) {
518  OutStreamer->SwitchSection(TheSection);
519 
520  EmitAlignment(AlignLog, GV);
521  OutStreamer->EmitLabel(MangSym);
522 
524  GV->getInitializer());
525  }
526 
527  OutStreamer->AddBlankLine();
528 
529  // Emit the variable struct for the runtime.
531 
532  OutStreamer->SwitchSection(TLVSect);
533  // Emit the linkage here.
534  EmitLinkage(GV, GVSym);
535  OutStreamer->EmitLabel(GVSym);
536 
537  // Three pointers in size:
538  // - __tlv_bootstrap - used to make sure support exists
539  // - spare pointer, used when mapped by the runtime
540  // - pointer to mangled symbol above with initializer
541  unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
542  OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
543  PtrSize);
544  OutStreamer->EmitIntValue(0, PtrSize);
545  OutStreamer->EmitSymbolValue(MangSym, PtrSize);
546 
547  OutStreamer->AddBlankLine();
548  return;
549  }
550 
551  MCSymbol *EmittedInitSym = GVSym;
552 
553  OutStreamer->SwitchSection(TheSection);
554 
555  EmitLinkage(GV, EmittedInitSym);
556  EmitAlignment(AlignLog, GV);
557 
558  OutStreamer->EmitLabel(EmittedInitSym);
559 
561 
563  // .size foo, 42
564  OutStreamer->emitELFSize(EmittedInitSym,
566 
567  OutStreamer->AddBlankLine();
568 }
569 
570 /// Emit the directive and value for debug thread local expression
571 ///
572 /// \p Value - The value to emit.
573 /// \p Size - The size of the integer (in bytes) to emit.
575  unsigned Size) const {
576  OutStreamer->EmitValue(Value, Size);
577 }
578 
579 /// EmitFunctionHeader - This method emits the header for the current
580 /// function.
581 void AsmPrinter::EmitFunctionHeader() {
582  // Print out constants referenced by the function
584 
585  // Print the 'header' of function.
586  const Function *F = MF->getFunction();
587 
588  OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(F, TM));
589  EmitVisibility(CurrentFnSym, F->getVisibility());
590 
591  EmitLinkage(F, CurrentFnSym);
592  if (MAI->hasFunctionAlignment())
594 
596  OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
597 
598  if (isVerbose()) {
599  F->printAsOperand(OutStreamer->GetCommentOS(),
600  /*PrintType=*/false, F->getParent());
601  OutStreamer->GetCommentOS() << '\n';
602  }
603 
604  // Emit the prefix data.
605  if (F->hasPrefixData())
607 
608  // Emit the CurrentFnSym. This is a virtual function to allow targets to
609  // do their wild and crazy things as required.
611 
612  // If the function had address-taken blocks that got deleted, then we have
613  // references to the dangling symbols. Emit them at the start of the function
614  // so that we don't get references to undefined symbols.
615  std::vector<MCSymbol*> DeadBlockSyms;
616  MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
617  for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
618  OutStreamer->AddComment("Address taken block that was later removed");
619  OutStreamer->EmitLabel(DeadBlockSyms[i]);
620  }
621 
622  if (CurrentFnBegin) {
623  if (MAI->useAssignmentForEHBegin()) {
625  OutStreamer->EmitLabel(CurPos);
626  OutStreamer->EmitAssignment(CurrentFnBegin,
628  } else {
629  OutStreamer->EmitLabel(CurrentFnBegin);
630  }
631  }
632 
633  // Emit pre-function debug and/or EH information.
634  for (const HandlerInfo &HI : Handlers) {
635  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
636  HI.TimerGroupDescription, TimePassesIsEnabled);
637  HI.Handler->beginFunction(MF);
638  }
639 
640  // Emit the prologue data.
641  if (F->hasPrologueData())
643 }
644 
645 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
646 /// function. This can be overridden by targets as required to do custom stuff.
649 
650  // The function label could have already been emitted if two symbols end up
651  // conflicting due to asm renaming. Detect this and emit an error.
652  if (CurrentFnSym->isVariable())
654  "' is a protected alias");
655  if (CurrentFnSym->isDefined())
657  "' label emitted multiple times to assembly file");
658 
659  return OutStreamer->EmitLabel(CurrentFnSym);
660 }
661 
662 /// emitComments - Pretty-print comments for instructions.
663 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
664  const MachineFunction *MF = MI.getParent()->getParent();
665  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
666 
667  // Check for spills and reloads
668  int FI;
669 
670  const MachineFrameInfo &MFI = MF->getFrameInfo();
671 
672  // We assume a single instruction only has a spill or reload, not
673  // both.
674  const MachineMemOperand *MMO;
675  if (TII->isLoadFromStackSlotPostFE(MI, FI)) {
676  if (MFI.isSpillSlotObjectIndex(FI)) {
677  MMO = *MI.memoperands_begin();
678  CommentOS << MMO->getSize() << "-byte Reload\n";
679  }
680  } else if (TII->hasLoadFromStackSlot(MI, MMO, FI)) {
681  if (MFI.isSpillSlotObjectIndex(FI))
682  CommentOS << MMO->getSize() << "-byte Folded Reload\n";
683  } else if (TII->isStoreToStackSlotPostFE(MI, FI)) {
684  if (MFI.isSpillSlotObjectIndex(FI)) {
685  MMO = *MI.memoperands_begin();
686  CommentOS << MMO->getSize() << "-byte Spill\n";
687  }
688  } else if (TII->hasStoreToStackSlot(MI, MMO, FI)) {
689  if (MFI.isSpillSlotObjectIndex(FI))
690  CommentOS << MMO->getSize() << "-byte Folded Spill\n";
691  }
692 
693  // Check for spill-induced copies
695  CommentOS << " Reload Reuse\n";
696 }
697 
698 /// emitImplicitDef - This method emits the specified machine instruction
699 /// that is an implicit def.
701  unsigned RegNo = MI->getOperand(0).getReg();
702 
703  SmallString<128> Str;
704  raw_svector_ostream OS(Str);
705  OS << "implicit-def: "
706  << PrintReg(RegNo, MF->getSubtarget().getRegisterInfo());
707 
708  OutStreamer->AddComment(OS.str());
709  OutStreamer->AddBlankLine();
710 }
711 
712 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
713  std::string Str;
714  raw_string_ostream OS(Str);
715  OS << "kill:";
716  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
717  const MachineOperand &Op = MI->getOperand(i);
718  assert(Op.isReg() && "KILL instruction must have only register operands");
719  OS << ' '
720  << PrintReg(Op.getReg(),
722  << (Op.isDef() ? "<def>" : "<kill>");
723  }
724  AP.OutStreamer->AddComment(OS.str());
725  AP.OutStreamer->AddBlankLine();
726 }
727 
728 /// emitDebugValueComment - This method handles the target-independent form
729 /// of DBG_VALUE, returning true if it was able to do so. A false return
730 /// means the target will need to handle MI in EmitInstruction.
732  // This code handles only the 4-operand target-independent form.
733  if (MI->getNumOperands() != 4)
734  return false;
735 
736  SmallString<128> Str;
737  raw_svector_ostream OS(Str);
738  OS << "DEBUG_VALUE: ";
739 
740  const DILocalVariable *V = MI->getDebugVariable();
741  if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
742  StringRef Name = SP->getDisplayName();
743  if (!Name.empty())
744  OS << Name << ":";
745  }
746  OS << V->getName();
747 
748  const DIExpression *Expr = MI->getDebugExpression();
749  auto Fragment = Expr->getFragmentInfo();
750  if (Fragment)
751  OS << " [fragment offset=" << Fragment->OffsetInBits
752  << " size=" << Fragment->SizeInBits << "]";
753  OS << " <- ";
754 
755  // The second operand is only an offset if it's an immediate.
756  bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
757  int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
758 
759  for (unsigned i = 0; i < Expr->getNumElements(); ++i) {
760  uint64_t Op = Expr->getElement(i);
761  if (Op == dwarf::DW_OP_LLVM_fragment) {
762  // There can't be any operands after this in a valid expression
763  break;
764  } else if (Deref) {
765  // We currently don't support extra Offsets or derefs after the first
766  // one. Bail out early instead of emitting an incorrect comment
767  OS << " [complex expression]";
768  AP.OutStreamer->emitRawComment(OS.str());
769  return true;
770  } else if (Op == dwarf::DW_OP_deref) {
771  Deref = true;
772  continue;
773  }
774 
775  uint64_t ExtraOffset = Expr->getElement(i++);
776  if (Op == dwarf::DW_OP_plus)
777  Offset += ExtraOffset;
778  else {
779  assert(Op == dwarf::DW_OP_minus);
780  Offset -= ExtraOffset;
781  }
782  }
783 
784  // Register or immediate value. Register 0 means undef.
785  if (MI->getOperand(0).isFPImm()) {
786  APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
787  if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
788  OS << (double)APF.convertToFloat();
789  } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
790  OS << APF.convertToDouble();
791  } else {
792  // There is no good way to print long double. Convert a copy to
793  // double. Ah well, it's only a comment.
794  bool ignored;
796  &ignored);
797  OS << "(long double) " << APF.convertToDouble();
798  }
799  } else if (MI->getOperand(0).isImm()) {
800  OS << MI->getOperand(0).getImm();
801  } else if (MI->getOperand(0).isCImm()) {
802  MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
803  } else {
804  unsigned Reg;
805  if (MI->getOperand(0).isReg()) {
806  Reg = MI->getOperand(0).getReg();
807  } else {
808  assert(MI->getOperand(0).isFI() && "Unknown operand type");
810  Offset += TFI->getFrameIndexReference(*AP.MF,
811  MI->getOperand(0).getIndex(), Reg);
812  Deref = true;
813  }
814  if (Reg == 0) {
815  // Suppress offset, it is not meaningful here.
816  OS << "undef";
817  // NOTE: Want this comment at start of line, don't emit with AddComment.
818  AP.OutStreamer->emitRawComment(OS.str());
819  return true;
820  }
821  if (Deref)
822  OS << '[';
823  OS << PrintReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
824  }
825 
826  if (Deref)
827  OS << '+' << Offset << ']';
828 
829  // NOTE: Want this comment at start of line, don't emit with AddComment.
830  AP.OutStreamer->emitRawComment(OS.str());
831  return true;
832 }
833 
837  return CFI_M_EH;
838 
839  if (MMI->hasDebugInfo())
840  return CFI_M_Debug;
841 
842  return CFI_M_None;
843 }
844 
847 }
848 
850  ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
851  if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
852  ExceptionHandlingType != ExceptionHandling::ARM)
853  return;
854 
855  if (needsCFIMoves() == CFI_M_None)
856  return;
857 
858  const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
859  unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
860  const MCCFIInstruction &CFI = Instrs[CFIIndex];
861  emitCFIInstruction(CFI);
862 }
863 
865  // The operands are the MCSymbol and the frame offset of the allocation.
866  MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
867  int FrameOffset = MI.getOperand(1).getImm();
868 
869  // Emit a symbol assignment.
870  OutStreamer->EmitAssignment(FrameAllocSym,
871  MCConstantExpr::create(FrameOffset, OutContext));
872 }
873 
874 /// EmitFunctionBody - This method emits the body and trailer for a
875 /// function.
877  EmitFunctionHeader();
878 
879  // Emit target-specific gunk before the function body.
881 
882  bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
883 
884  // Print out code for the function.
885  bool HasAnyRealCode = false;
886  for (auto &MBB : *MF) {
887  // Print a label for the basic block.
889  for (auto &MI : MBB) {
890 
891  // Print the assembly for the instruction.
892  if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
893  !MI.isDebugValue()) {
894  HasAnyRealCode = true;
895  ++EmittedInsts;
896  }
897 
898  if (ShouldPrintDebugScopes) {
899  for (const HandlerInfo &HI : Handlers) {
900  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
901  HI.TimerGroupName, HI.TimerGroupDescription,
903  HI.Handler->beginInstruction(&MI);
904  }
905  }
906 
907  if (isVerbose())
908  emitComments(MI, OutStreamer->GetCommentOS());
909 
910  switch (MI.getOpcode()) {
911  case TargetOpcode::CFI_INSTRUCTION:
913  break;
914 
915  case TargetOpcode::LOCAL_ESCAPE:
917  break;
918 
920  case TargetOpcode::GC_LABEL:
921  OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
922  break;
924  EmitInlineAsm(&MI);
925  break;
926  case TargetOpcode::DBG_VALUE:
927  if (isVerbose()) {
928  if (!emitDebugValueComment(&MI, *this))
930  }
931  break;
932  case TargetOpcode::IMPLICIT_DEF:
933  if (isVerbose()) emitImplicitDef(&MI);
934  break;
935  case TargetOpcode::KILL:
936  if (isVerbose()) emitKill(&MI, *this);
937  break;
938  default:
940  break;
941  }
942 
943  if (ShouldPrintDebugScopes) {
944  for (const HandlerInfo &HI : Handlers) {
945  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
946  HI.TimerGroupName, HI.TimerGroupDescription,
948  HI.Handler->endInstruction();
949  }
950  }
951  }
952 
953  EmitBasicBlockEnd(MBB);
954  }
955 
956  // If the function is empty and the object file uses .subsections_via_symbols,
957  // then we need to emit *something* to the function body to prevent the
958  // labels from collapsing together. Just emit a noop.
959  if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) {
960  MCInst Noop;
961  MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop);
962  OutStreamer->AddComment("avoids zero-length function");
963 
964  // Targets can opt-out of emitting the noop here by leaving the opcode
965  // unspecified.
966  if (Noop.getOpcode())
967  OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
968  }
969 
970  const Function *F = MF->getFunction();
971  for (const auto &BB : *F) {
972  if (!BB.hasAddressTaken())
973  continue;
974  MCSymbol *Sym = GetBlockAddressSymbol(&BB);
975  if (Sym->isDefined())
976  continue;
977  OutStreamer->AddComment("Address of block that was removed by CodeGen");
978  OutStreamer->EmitLabel(Sym);
979  }
980 
981  // Emit target-specific gunk after the function body.
983 
984  if (!MF->getLandingPads().empty() || MMI->hasDebugInfo() ||
985  MF->hasEHFunclets() || MAI->hasDotTypeDotSizeDirective()) {
986  // Create a symbol for the end of function.
987  CurrentFnEnd = createTempSymbol("func_end");
988  OutStreamer->EmitLabel(CurrentFnEnd);
989  }
990 
991  // If the target wants a .size directive for the size of the function, emit
992  // it.
994  // We can get the size as difference between the function label and the
995  // temp label.
996  const MCExpr *SizeExp = MCBinaryExpr::createSub(
997  MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
999  OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1000  }
1001 
1002  for (const HandlerInfo &HI : Handlers) {
1003  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1004  HI.TimerGroupDescription, TimePassesIsEnabled);
1005  HI.Handler->markFunctionEnd();
1006  }
1007 
1008  // Print out jump tables referenced by the function.
1010 
1011  // Emit post-function debug and/or EH information.
1012  for (const HandlerInfo &HI : Handlers) {
1013  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1014  HI.TimerGroupDescription, TimePassesIsEnabled);
1015  HI.Handler->endFunction(MF);
1016  }
1017 
1018  OutStreamer->AddBlankLine();
1019 }
1020 
1021 /// \brief Compute the number of Global Variables that uses a Constant.
1022 static unsigned getNumGlobalVariableUses(const Constant *C) {
1023  if (!C)
1024  return 0;
1025 
1026  if (isa<GlobalVariable>(C))
1027  return 1;
1028 
1029  unsigned NumUses = 0;
1030  for (auto *CU : C->users())
1031  NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1032 
1033  return NumUses;
1034 }
1035 
1036 /// \brief Only consider global GOT equivalents if at least one user is a
1037 /// cstexpr inside an initializer of another global variables. Also, don't
1038 /// handle cstexpr inside instructions. During global variable emission,
1039 /// candidates are skipped and are emitted later in case at least one cstexpr
1040 /// isn't replaced by a PC relative GOT entry access.
1042  unsigned &NumGOTEquivUsers) {
1043  // Global GOT equivalents are unnamed private globals with a constant
1044  // pointer initializer to another global symbol. They must point to a
1045  // GlobalVariable or Function, i.e., as GlobalValue.
1046  if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1047  !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1048  !dyn_cast<GlobalValue>(GV->getOperand(0)))
1049  return false;
1050 
1051  // To be a got equivalent, at least one of its users need to be a constant
1052  // expression used by another global variable.
1053  for (auto *U : GV->users())
1054  NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1055 
1056  return NumGOTEquivUsers > 0;
1057 }
1058 
1059 /// \brief Unnamed constant global variables solely contaning a pointer to
1060 /// another globals variable is equivalent to a GOT table entry; it contains the
1061 /// the address of another symbol. Optimize it and replace accesses to these
1062 /// "GOT equivalents" by using the GOT entry for the final global instead.
1063 /// Compute GOT equivalent candidates among all global variables to avoid
1064 /// emitting them if possible later on, after it use is replaced by a GOT entry
1065 /// access.
1067  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1068  return;
1069 
1070  for (const auto &G : M.globals()) {
1071  unsigned NumGOTEquivUsers = 0;
1072  if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1073  continue;
1074 
1075  const MCSymbol *GOTEquivSym = getSymbol(&G);
1076  GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1077  }
1078 }
1079 
1080 /// \brief Constant expressions using GOT equivalent globals may not be eligible
1081 /// for PC relative GOT entry conversion, in such cases we need to emit such
1082 /// globals we previously omitted in EmitGlobalVariable.
1084  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1085  return;
1086 
1087  SmallVector<const GlobalVariable *, 8> FailedCandidates;
1088  for (auto &I : GlobalGOTEquivs) {
1089  const GlobalVariable *GV = I.second.first;
1090  unsigned Cnt = I.second.second;
1091  if (Cnt)
1092  FailedCandidates.push_back(GV);
1093  }
1094  GlobalGOTEquivs.clear();
1095 
1096  for (auto *GV : FailedCandidates)
1097  EmitGlobalVariable(GV);
1098 }
1099 
1100 void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
1101  const GlobalIndirectSymbol& GIS) {
1102  MCSymbol *Name = getSymbol(&GIS);
1103 
1104  if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
1105  OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
1106  else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
1107  OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
1108  else
1109  assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage");
1110 
1111  // Set the symbol type to function if the alias has a function type.
1112  // This affects codegen when the aliasee is not a function.
1113  if (GIS.getType()->getPointerElementType()->isFunctionTy()) {
1114  OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1115  if (isa<GlobalIFunc>(GIS))
1116  OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
1117  }
1118 
1119  EmitVisibility(Name, GIS.getVisibility());
1120 
1121  const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
1122 
1123  if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1124  OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry);
1125 
1126  // Emit the directives as assignments aka .set:
1127  OutStreamer->EmitAssignment(Name, Expr);
1128 
1129  if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
1130  // If the aliasee does not correspond to a symbol in the output, i.e. the
1131  // alias is not of an object or the aliased object is private, then set the
1132  // size of the alias symbol from the type of the alias. We don't do this in
1133  // other situations as the alias and aliasee having differing types but same
1134  // size may be intentional.
1135  const GlobalObject *BaseObject = GA->getBaseObject();
1136  if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
1137  (!BaseObject || BaseObject->hasPrivateLinkage())) {
1138  const DataLayout &DL = M.getDataLayout();
1139  uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
1140  OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
1141  }
1142  }
1143 }
1144 
1146  // Set the MachineFunction to nullptr so that we can catch attempted
1147  // accesses to MF specific features at the module level and so that
1148  // we can conditionalize accesses based on whether or not it is nullptr.
1149  MF = nullptr;
1150 
1151  // Gather all GOT equivalent globals in the module. We really need two
1152  // passes over the globals: one to compute and another to avoid its emission
1153  // in EmitGlobalVariable, otherwise we would not be able to handle cases
1154  // where the got equivalent shows up before its use.
1156 
1157  // Emit global variables.
1158  for (const auto &G : M.globals())
1160 
1161  // Emit remaining GOT equivalent globals.
1163 
1164  // Emit visibility info for declarations
1165  for (const Function &F : M) {
1166  if (!F.isDeclarationForLinker())
1167  continue;
1170  continue;
1171 
1172  MCSymbol *Name = getSymbol(&F);
1173  EmitVisibility(Name, V, false);
1174  }
1175 
1177 
1178  // Emit module flags.
1180  M.getModuleFlagsMetadata(ModuleFlags);
1181  if (!ModuleFlags.empty())
1182  TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, TM);
1183 
1186 
1187  // Output stubs for external and common global variables.
1189  if (!Stubs.empty()) {
1190  OutStreamer->SwitchSection(TLOF.getDataSection());
1191  const DataLayout &DL = M.getDataLayout();
1192 
1193  for (const auto &Stub : Stubs) {
1194  OutStreamer->EmitLabel(Stub.first);
1195  OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
1196  DL.getPointerSize());
1197  }
1198  }
1199  }
1200 
1201  // Finalize debug and EH information.
1202  for (const HandlerInfo &HI : Handlers) {
1203  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1204  HI.TimerGroupDescription, TimePassesIsEnabled);
1205  HI.Handler->endModule();
1206  delete HI.Handler;
1207  }
1208  Handlers.clear();
1209  DD = nullptr;
1210 
1211  // If the target wants to know about weak references, print them all.
1212  if (MAI->getWeakRefDirective()) {
1213  // FIXME: This is not lazy, it would be nice to only print weak references
1214  // to stuff that is actually used. Note that doing so would require targets
1215  // to notice uses in operands (due to constant exprs etc). This should
1216  // happen with the MC stuff eventually.
1217 
1218  // Print out module-level global objects here.
1219  for (const auto &GO : M.global_objects()) {
1220  if (!GO.hasExternalWeakLinkage())
1221  continue;
1222  OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1223  }
1224  }
1225 
1226  OutStreamer->AddBlankLine();
1227 
1228  // Print aliases in topological order, that is, for each alias a = b,
1229  // b must be printed before a.
1230  // This is because on some targets (e.g. PowerPC) linker expects aliases in
1231  // such an order to generate correct TOC information.
1234  for (const auto &Alias : M.aliases()) {
1235  for (const GlobalAlias *Cur = &Alias; Cur;
1236  Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1237  if (!AliasVisited.insert(Cur).second)
1238  break;
1239  AliasStack.push_back(Cur);
1240  }
1241  for (const GlobalAlias *AncestorAlias : reverse(AliasStack))
1242  emitGlobalIndirectSymbol(M, *AncestorAlias);
1243  AliasStack.clear();
1244  }
1245  for (const auto &IFunc : M.ifuncs())
1246  emitGlobalIndirectSymbol(M, IFunc);
1247 
1248  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1249  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1250  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1251  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1252  MP->finishAssembly(M, *MI, *this);
1253 
1254  // Emit llvm.ident metadata in an '.ident' directive.
1255  EmitModuleIdents(M);
1256 
1257  // Emit __morestack address if needed for indirect calls.
1258  if (MMI->usesMorestackAddr()) {
1259  unsigned Align = 1;
1260  MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1262  /*C=*/nullptr, Align);
1263  OutStreamer->SwitchSection(ReadOnlySection);
1264 
1265  MCSymbol *AddrSymbol =
1266  OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1267  OutStreamer->EmitLabel(AddrSymbol);
1268 
1269  unsigned PtrSize = M.getDataLayout().getPointerSize(0);
1270  OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1271  PtrSize);
1272  }
1273 
1274  // If we don't have any trampolines, then we don't require stack memory
1275  // to be executable. Some targets have a directive to declare this.
1276  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1277  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1279  OutStreamer->SwitchSection(S);
1280 
1281  // Allow the target to emit any magic that it wants at the end of the file,
1282  // after everything else has gone out.
1283  EmitEndOfAsmFile(M);
1284 
1285  MMI = nullptr;
1286 
1287  OutStreamer->Finish();
1288  OutStreamer->reset();
1289 
1290  return false;
1291 }
1292 
1294  if (!CurExceptionSym)
1295  CurExceptionSym = createTempSymbol("exception");
1296  return CurExceptionSym;
1297 }
1298 
1300  this->MF = &MF;
1301  // Get the function symbol.
1304  CurrentFnBegin = nullptr;
1305  CurExceptionSym = nullptr;
1306  bool NeedsLocalForSize = MAI->needsLocalForSize();
1307  if (!MF.getLandingPads().empty() || MMI->hasDebugInfo() ||
1308  MF.hasEHFunclets() || NeedsLocalForSize) {
1309  CurrentFnBegin = createTempSymbol("func_begin");
1310  if (NeedsLocalForSize)
1311  CurrentFnSymForSize = CurrentFnBegin;
1312  }
1313 
1314  if (isVerbose())
1315  LI = &getAnalysis<MachineLoopInfo>();
1316 }
1317 
1318 namespace {
1319 // Keep track the alignment, constpool entries per Section.
1320  struct SectionCPs {
1321  MCSection *S;
1322  unsigned Alignment;
1324  SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
1325  };
1326 }
1327 
1328 /// EmitConstantPool - Print to the current output stream assembly
1329 /// representations of the constants in the constant pool MCP. This is
1330 /// used to print out constants which have been "spilled to memory" by
1331 /// the code generator.
1332 ///
1334  const MachineConstantPool *MCP = MF->getConstantPool();
1335  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1336  if (CP.empty()) return;
1337 
1338  // Calculate sections for constant pool entries. We collect entries to go into
1339  // the same section together to reduce amount of section switch statements.
1340  SmallVector<SectionCPs, 4> CPSections;
1341  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1342  const MachineConstantPoolEntry &CPE = CP[i];
1343  unsigned Align = CPE.getAlignment();
1344 
1345  SectionKind Kind = CPE.getSectionKind(&getDataLayout());
1346 
1347  const Constant *C = nullptr;
1348  if (!CPE.isMachineConstantPoolEntry())
1349  C = CPE.Val.ConstVal;
1350 
1352  Kind, C, Align);
1353 
1354  // The number of sections are small, just do a linear search from the
1355  // last section to the first.
1356  bool Found = false;
1357  unsigned SecIdx = CPSections.size();
1358  while (SecIdx != 0) {
1359  if (CPSections[--SecIdx].S == S) {
1360  Found = true;
1361  break;
1362  }
1363  }
1364  if (!Found) {
1365  SecIdx = CPSections.size();
1366  CPSections.push_back(SectionCPs(S, Align));
1367  }
1368 
1369  if (Align > CPSections[SecIdx].Alignment)
1370  CPSections[SecIdx].Alignment = Align;
1371  CPSections[SecIdx].CPEs.push_back(i);
1372  }
1373 
1374  // Now print stuff into the calculated sections.
1375  const MCSection *CurSection = nullptr;
1376  unsigned Offset = 0;
1377  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1378  for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1379  unsigned CPI = CPSections[i].CPEs[j];
1380  MCSymbol *Sym = GetCPISymbol(CPI);
1381  if (!Sym->isUndefined())
1382  continue;
1383 
1384  if (CurSection != CPSections[i].S) {
1385  OutStreamer->SwitchSection(CPSections[i].S);
1386  EmitAlignment(Log2_32(CPSections[i].Alignment));
1387  CurSection = CPSections[i].S;
1388  Offset = 0;
1389  }
1390 
1391  MachineConstantPoolEntry CPE = CP[CPI];
1392 
1393  // Emit inter-object padding for alignment.
1394  unsigned AlignMask = CPE.getAlignment() - 1;
1395  unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1396  OutStreamer->EmitZeros(NewOffset - Offset);
1397 
1398  Type *Ty = CPE.getType();
1399  Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
1400 
1401  OutStreamer->EmitLabel(Sym);
1402  if (CPE.isMachineConstantPoolEntry())
1404  else
1406  }
1407  }
1408 }
1409 
1410 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1411 /// by the current function to the current output stream.
1412 ///
1414  const DataLayout &DL = MF->getDataLayout();
1415  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1416  if (!MJTI) return;
1417  if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1418  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1419  if (JT.empty()) return;
1420 
1421  // Pick the directive to use to print the jump table entries, and switch to
1422  // the appropriate section.
1423  const Function *F = MF->getFunction();
1425  bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
1427  *F);
1428  if (JTInDiffSection) {
1429  // Drop it in the readonly section.
1430  MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, TM);
1431  OutStreamer->SwitchSection(ReadOnlySection);
1432  }
1433 
1435 
1436  // Jump tables in code sections are marked with a data_region directive
1437  // where that's supported.
1438  if (!JTInDiffSection)
1439  OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1440 
1441  for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1442  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1443 
1444  // If this jump table was deleted, ignore it.
1445  if (JTBBs.empty()) continue;
1446 
1447  // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
1448  /// emit a .set directive for each unique entry.
1452  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1453  const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1454  for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1455  const MachineBasicBlock *MBB = JTBBs[ii];
1456  if (!EmittedSets.insert(MBB).second)
1457  continue;
1458 
1459  // .set LJTSet, LBB32-base
1460  const MCExpr *LHS =
1462  OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1463  MCBinaryExpr::createSub(LHS, Base,
1464  OutContext));
1465  }
1466  }
1467 
1468  // On some targets (e.g. Darwin) we want to emit two consecutive labels
1469  // before each jump table. The first label is never referenced, but tells
1470  // the assembler and linker the extents of the jump table object. The
1471  // second label is actually referenced by the code.
1472  if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
1473  // FIXME: This doesn't have to have any specific name, just any randomly
1474  // named and numbered 'l' label would work. Simplify GetJTISymbol.
1475  OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
1476 
1477  OutStreamer->EmitLabel(GetJTISymbol(JTI));
1478 
1479  for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1480  EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1481  }
1482  if (!JTInDiffSection)
1483  OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1484 }
1485 
1486 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1487 /// current stream.
1488 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1489  const MachineBasicBlock *MBB,
1490  unsigned UID) const {
1491  assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1492  const MCExpr *Value = nullptr;
1493  switch (MJTI->getEntryKind()) {
1495  llvm_unreachable("Cannot emit EK_Inline jump table entry");
1498  MJTI, MBB, UID, OutContext);
1499  break;
1501  // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1502  // .word LBB123
1503  Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1504  break;
1506  // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1507  // with a relocation as gp-relative, e.g.:
1508  // .gprel32 LBB123
1509  MCSymbol *MBBSym = MBB->getSymbol();
1510  OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1511  return;
1512  }
1513 
1515  // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1516  // with a relocation as gp-relative, e.g.:
1517  // .gpdword LBB123
1518  MCSymbol *MBBSym = MBB->getSymbol();
1519  OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
1520  return;
1521  }
1522 
1524  // Each entry is the address of the block minus the address of the jump
1525  // table. This is used for PIC jump tables where gprel32 is not supported.
1526  // e.g.:
1527  // .word LBB123 - LJTI1_2
1528  // If the .set directive avoids relocations, this is emitted as:
1529  // .set L4_5_set_123, LBB123 - LJTI1_2
1530  // .word L4_5_set_123
1532  Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
1533  OutContext);
1534  break;
1535  }
1536  Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1537  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1538  const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
1539  Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1540  break;
1541  }
1542  }
1543 
1544  assert(Value && "Unknown entry kind!");
1545 
1546  unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
1547  OutStreamer->EmitValue(Value, EntrySize);
1548 }
1549 
1550 
1551 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1552 /// special global used by LLVM. If so, emit it and return true, otherwise
1553 /// do nothing and return false.
1555  if (GV->getName() == "llvm.used") {
1556  if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1557  EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1558  return true;
1559  }
1560 
1561  // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1562  if (GV->getSection() == "llvm.metadata" ||
1564  return true;
1565 
1566  if (!GV->hasAppendingLinkage()) return false;
1567 
1568  assert(GV->hasInitializer() && "Not a special LLVM global!");
1569 
1570  if (GV->getName() == "llvm.global_ctors") {
1571  EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1572  /* isCtor */ true);
1573 
1574  return true;
1575  }
1576 
1577  if (GV->getName() == "llvm.global_dtors") {
1578  EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
1579  /* isCtor */ false);
1580 
1581  return true;
1582  }
1583 
1584  report_fatal_error("unknown special variable");
1585 }
1586 
1587 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1588 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1589 /// is true, as being used with this directive.
1590 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1591  // Should be an array of 'i8*'.
1592  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1593  const GlobalValue *GV =
1595  if (GV)
1596  OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1597  }
1598 }
1599 
1600 namespace {
1601 struct Structor {
1602  Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
1603  int Priority;
1605  llvm::GlobalValue *ComdatKey;
1606 };
1607 } // end namespace
1608 
1609 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1610 /// priority.
1611 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
1612  bool isCtor) {
1613  // Should be an array of '{ int, void ()* }' structs. The first value is the
1614  // init priority.
1615  if (!isa<ConstantArray>(List)) return;
1616 
1617  // Sanity check the structors list.
1618  const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1619  if (!InitList) return; // Not an array!
1620  StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1621  // FIXME: Only allow the 3-field form in LLVM 4.0.
1622  if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
1623  return; // Not an array of two or three elements!
1624  if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1625  !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1626  if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
1627  return; // Not (int, ptr, ptr).
1628 
1629  // Gather the structors in a form that's convenient for sorting by priority.
1630  SmallVector<Structor, 8> Structors;
1631  for (Value *O : InitList->operands()) {
1633  if (!CS) continue; // Malformed.
1634  if (CS->getOperand(1)->isNullValue())
1635  break; // Found a null terminator, skip the rest.
1636  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1637  if (!Priority) continue; // Malformed.
1638  Structors.push_back(Structor());
1639  Structor &S = Structors.back();
1640  S.Priority = Priority->getLimitedValue(65535);
1641  S.Func = CS->getOperand(1);
1642  if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
1643  S.ComdatKey =
1644  dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
1645  }
1646 
1647  // Emit the function pointers in the target-specific order
1648  unsigned Align = Log2_32(DL.getPointerPrefAlignment());
1649  std::stable_sort(Structors.begin(), Structors.end(),
1650  [](const Structor &L,
1651  const Structor &R) { return L.Priority < R.Priority; });
1652  for (Structor &S : Structors) {
1654  const MCSymbol *KeySym = nullptr;
1655  if (GlobalValue *GV = S.ComdatKey) {
1657  // If the associated variable is available_externally, some other TU
1658  // will provide its dynamic initializer.
1659  continue;
1660 
1661  KeySym = getSymbol(GV);
1662  }
1663  MCSection *OutputSection =
1664  (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
1665  : Obj.getStaticDtorSection(S.Priority, KeySym));
1666  OutStreamer->SwitchSection(OutputSection);
1667  if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
1668  EmitAlignment(Align);
1669  EmitXXStructor(DL, S.Func);
1670  }
1671 }
1672 
1673 void AsmPrinter::EmitModuleIdents(Module &M) {
1674  if (!MAI->hasIdentDirective())
1675  return;
1676 
1677  if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1678  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1679  const MDNode *N = NMD->getOperand(i);
1680  assert(N->getNumOperands() == 1 &&
1681  "llvm.ident metadata entry can have only one operand");
1682  const MDString *S = cast<MDString>(N->getOperand(0));
1683  OutStreamer->EmitIdent(S->getString());
1684  }
1685  }
1686 }
1687 
1688 //===--------------------------------------------------------------------===//
1689 // Emission and print routines
1690 //
1691 
1692 /// EmitInt8 - Emit a byte directive and value.
1693 ///
1694 void AsmPrinter::EmitInt8(int Value) const {
1695  OutStreamer->EmitIntValue(Value, 1);
1696 }
1697 
1698 /// EmitInt16 - Emit a short directive and value.
1699 ///
1700 void AsmPrinter::EmitInt16(int Value) const {
1701  OutStreamer->EmitIntValue(Value, 2);
1702 }
1703 
1704 /// EmitInt32 - Emit a long directive and value.
1705 ///
1706 void AsmPrinter::EmitInt32(int Value) const {
1707  OutStreamer->EmitIntValue(Value, 4);
1708 }
1709 
1710 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
1711 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
1712 /// .set if it avoids relocations.
1714  unsigned Size) const {
1715  OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
1716 }
1717 
1718 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1719 /// where the size in bytes of the directive is specified by Size and Label
1720 /// specifies the label. This implicitly uses .set if it is available.
1722  unsigned Size,
1723  bool IsSectionRelative) const {
1724  if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1725  OutStreamer->EmitCOFFSecRel32(Label, Offset);
1726  if (Size > 4)
1727  OutStreamer->EmitZeros(Size - 4);
1728  return;
1729  }
1730 
1731  // Emit Label+Offset (or just Label if Offset is zero)
1732  const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
1733  if (Offset)
1734  Expr = MCBinaryExpr::createAdd(
1735  Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1736 
1737  OutStreamer->EmitValue(Expr, Size);
1738 }
1739 
1740 //===----------------------------------------------------------------------===//
1741 
1742 // EmitAlignment - Emit an alignment directive to the specified power of
1743 // two boundary. For example, if you pass in 3 here, you will get an 8
1744 // byte alignment. If a global value is specified, and if that global has
1745 // an explicit alignment requested, it will override the alignment request
1746 // if required for correctness.
1747 //
1748 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
1749  if (GV)
1750  NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
1751 
1752  if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1753 
1754  assert(NumBits <
1755  static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
1756  "undefined behavior");
1757  if (getCurrentSection()->getKind().isText())
1758  OutStreamer->EmitCodeAlignment(1u << NumBits);
1759  else
1760  OutStreamer->EmitValueToAlignment(1u << NumBits);
1761 }
1762 
1763 //===----------------------------------------------------------------------===//
1764 // Constant emission.
1765 //===----------------------------------------------------------------------===//
1766 
1768  MCContext &Ctx = OutContext;
1769 
1770  if (CV->isNullValue() || isa<UndefValue>(CV))
1771  return MCConstantExpr::create(0, Ctx);
1772 
1773  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1774  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1775 
1776  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1777  return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
1778 
1779  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1781 
1782  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1783  if (!CE) {
1784  llvm_unreachable("Unknown constant value to lower!");
1785  }
1786 
1787  switch (CE->getOpcode()) {
1788  default:
1789  // If the code isn't optimized, there may be outstanding folding
1790  // opportunities. Attempt to fold the expression using DataLayout as a
1791  // last resort before giving up.
1793  if (C != CE)
1794  return lowerConstant(C);
1795 
1796  // Otherwise report the problem to the user.
1797  {
1798  std::string S;
1799  raw_string_ostream OS(S);
1800  OS << "Unsupported expression in static initializer: ";
1801  CE->printAsOperand(OS, /*PrintType=*/false,
1802  !MF ? nullptr : MF->getFunction()->getParent());
1803  report_fatal_error(OS.str());
1804  }
1805  case Instruction::GetElementPtr: {
1806  // Generate a symbolic expression for the byte address
1807  APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
1808  cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
1809 
1810  const MCExpr *Base = lowerConstant(CE->getOperand(0));
1811  if (!OffsetAI)
1812  return Base;
1813 
1814  int64_t Offset = OffsetAI.getSExtValue();
1815  return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
1816  Ctx);
1817  }
1818 
1819  case Instruction::Trunc:
1820  // We emit the value and depend on the assembler to truncate the generated
1821  // expression properly. This is important for differences between
1822  // blockaddress labels. Since the two labels are in the same function, it
1823  // is reasonable to treat their delta as a 32-bit value.
1825  case Instruction::BitCast:
1826  return lowerConstant(CE->getOperand(0));
1827 
1828  case Instruction::IntToPtr: {
1829  const DataLayout &DL = getDataLayout();
1830 
1831  // Handle casts to pointers by changing them into casts to the appropriate
1832  // integer type. This promotes constant folding and simplifies this code.
1833  Constant *Op = CE->getOperand(0);
1835  false/*ZExt*/);
1836  return lowerConstant(Op);
1837  }
1838 
1839  case Instruction::PtrToInt: {
1840  const DataLayout &DL = getDataLayout();
1841 
1842  // Support only foldable casts to/from pointers that can be eliminated by
1843  // changing the pointer to the appropriately sized integer type.
1844  Constant *Op = CE->getOperand(0);
1845  Type *Ty = CE->getType();
1846 
1847  const MCExpr *OpExpr = lowerConstant(Op);
1848 
1849  // We can emit the pointer value into this slot if the slot is an
1850  // integer slot equal to the size of the pointer.
1851  if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1852  return OpExpr;
1853 
1854  // Otherwise the pointer is smaller than the resultant integer, mask off
1855  // the high bits so we are sure to get a proper truncation if the input is
1856  // a constant expr.
1857  unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1858  const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
1859  return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
1860  }
1861 
1862  case Instruction::Sub: {
1863  GlobalValue *LHSGV;
1864  APInt LHSOffset;
1865  if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
1866  getDataLayout())) {
1867  GlobalValue *RHSGV;
1868  APInt RHSOffset;
1869  if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
1870  getDataLayout())) {
1871  const MCExpr *RelocExpr =
1872  getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
1873  if (!RelocExpr)
1874  RelocExpr = MCBinaryExpr::createSub(
1875  MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
1876  MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
1877  int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
1878  if (Addend != 0)
1879  RelocExpr = MCBinaryExpr::createAdd(
1880  RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
1881  return RelocExpr;
1882  }
1883  }
1884  }
1885  // else fallthrough
1886 
1887  // The MC library also has a right-shift operator, but it isn't consistently
1888  // signed or unsigned between different targets.
1889  case Instruction::Add:
1890  case Instruction::Mul:
1891  case Instruction::SDiv:
1892  case Instruction::SRem:
1893  case Instruction::Shl:
1894  case Instruction::And:
1895  case Instruction::Or:
1896  case Instruction::Xor: {
1897  const MCExpr *LHS = lowerConstant(CE->getOperand(0));
1898  const MCExpr *RHS = lowerConstant(CE->getOperand(1));
1899  switch (CE->getOpcode()) {
1900  default: llvm_unreachable("Unknown binary operator constant cast expr");
1901  case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
1902  case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1903  case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
1904  case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
1905  case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
1906  case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
1907  case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
1908  case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
1909  case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
1910  }
1911  }
1912  }
1913 }
1914 
1915 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
1916  AsmPrinter &AP,
1917  const Constant *BaseCV = nullptr,
1918  uint64_t Offset = 0);
1919 
1920 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
1921 
1922 /// isRepeatedByteSequence - Determine whether the given value is
1923 /// composed of a repeated sequence of identical bytes and return the
1924 /// byte value. If it is not a repeated sequence, return -1.
1926  StringRef Data = V->getRawDataValues();
1927  assert(!Data.empty() && "Empty aggregates should be CAZ node");
1928  char C = Data[0];
1929  for (unsigned i = 1, e = Data.size(); i != e; ++i)
1930  if (Data[i] != C) return -1;
1931  return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1932 }
1933 
1934 
1935 /// isRepeatedByteSequence - Determine whether the given value is
1936 /// composed of a repeated sequence of identical bytes and return the
1937 /// byte value. If it is not a repeated sequence, return -1.
1938 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
1939  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1940  uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
1941  assert(Size % 8 == 0);
1942 
1943  // Extend the element to take zero padding into account.
1944  APInt Value = CI->getValue().zextOrSelf(Size);
1945  if (!Value.isSplat(8))
1946  return -1;
1947 
1948  return Value.zextOrTrunc(8).getZExtValue();
1949  }
1950  if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1951  // Make sure all array elements are sequences of the same repeated
1952  // byte.
1953  assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1954  Constant *Op0 = CA->getOperand(0);
1955  int Byte = isRepeatedByteSequence(Op0, DL);
1956  if (Byte == -1)
1957  return -1;
1958 
1959  // All array elements must be equal.
1960  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
1961  if (CA->getOperand(i) != Op0)
1962  return -1;
1963  return Byte;
1964  }
1965 
1966  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1967  return isRepeatedByteSequence(CDS);
1968 
1969  return -1;
1970 }
1971 
1973  const ConstantDataSequential *CDS,
1974  AsmPrinter &AP) {
1975 
1976  // See if we can aggregate this into a .fill, if so, emit it as such.
1977  int Value = isRepeatedByteSequence(CDS, DL);
1978  if (Value != -1) {
1979  uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
1980  // Don't emit a 1-byte object as a .fill.
1981  if (Bytes > 1)
1982  return AP.OutStreamer->emitFill(Bytes, Value);
1983  }
1984 
1985  // If this can be emitted with .ascii/.asciz, emit it as such.
1986  if (CDS->isString())
1987  return AP.OutStreamer->EmitBytes(CDS->getAsString());
1988 
1989  // Otherwise, emit the values in successive locations.
1990  unsigned ElementByteSize = CDS->getElementByteSize();
1991  if (isa<IntegerType>(CDS->getElementType())) {
1992  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1993  if (AP.isVerbose())
1994  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
1995  CDS->getElementAsInteger(i));
1996  AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
1997  ElementByteSize);
1998  }
1999  } else {
2000  for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2001  emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP);
2002  }
2003 
2004  unsigned Size = DL.getTypeAllocSize(CDS->getType());
2005  unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
2006  CDS->getNumElements();
2007  if (unsigned Padding = Size - EmittedSize)
2008  AP.OutStreamer->EmitZeros(Padding);
2009 
2010 }
2011 
2012 static void emitGlobalConstantArray(const DataLayout &DL,
2013  const ConstantArray *CA, AsmPrinter &AP,
2014  const Constant *BaseCV, uint64_t Offset) {
2015  // See if we can aggregate some values. Make sure it can be
2016  // represented as a series of bytes of the constant value.
2017  int Value = isRepeatedByteSequence(CA, DL);
2018 
2019  if (Value != -1) {
2020  uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2021  AP.OutStreamer->emitFill(Bytes, Value);
2022  }
2023  else {
2024  for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2025  emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2026  Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2027  }
2028  }
2029 }
2030 
2031 static void emitGlobalConstantVector(const DataLayout &DL,
2032  const ConstantVector *CV, AsmPrinter &AP) {
2033  for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2034  emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
2035 
2036  unsigned Size = DL.getTypeAllocSize(CV->getType());
2037  unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2038  CV->getType()->getNumElements();
2039  if (unsigned Padding = Size - EmittedSize)
2040  AP.OutStreamer->EmitZeros(Padding);
2041 }
2042 
2043 static void emitGlobalConstantStruct(const DataLayout &DL,
2044  const ConstantStruct *CS, AsmPrinter &AP,
2045  const Constant *BaseCV, uint64_t Offset) {
2046  // Print the fields in successive locations. Pad to align if needed!
2047  unsigned Size = DL.getTypeAllocSize(CS->getType());
2048  const StructLayout *Layout = DL.getStructLayout(CS->getType());
2049  uint64_t SizeSoFar = 0;
2050  for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2051  const Constant *Field = CS->getOperand(i);
2052 
2053  // Print the actual field value.
2054  emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2055 
2056  // Check if padding is needed and insert one or more 0s.
2057  uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2058  uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2059  - Layout->getElementOffset(i)) - FieldSize;
2060  SizeSoFar += FieldSize + PadSize;
2061 
2062  // Insert padding - this may include padding to increase the size of the
2063  // current field up to the ABI size (if the struct is not packed) as well
2064  // as padding to ensure that the next field starts at the right offset.
2065  AP.OutStreamer->EmitZeros(PadSize);
2066  }
2067  assert(SizeSoFar == Layout->getSizeInBytes() &&
2068  "Layout of constant struct may be incorrect!");
2069 }
2070 
2071 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2072  APInt API = CFP->getValueAPF().bitcastToAPInt();
2073 
2074  // First print a comment with what we think the original floating-point value
2075  // should have been.
2076  if (AP.isVerbose()) {
2078  CFP->getValueAPF().toString(StrVal);
2079 
2080  if (CFP->getType())
2081  CFP->getType()->print(AP.OutStreamer->GetCommentOS());
2082  else
2083  AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
2084  AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2085  }
2086 
2087  // Now iterate through the APInt chunks, emitting them in endian-correct
2088  // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2089  // floats).
2090  unsigned NumBytes = API.getBitWidth() / 8;
2091  unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2092  const uint64_t *p = API.getRawData();
2093 
2094  // PPC's long double has odd notions of endianness compared to how LLVM
2095  // handles it: p[0] goes first for *big* endian on PPC.
2096  if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) {
2097  int Chunk = API.getNumWords() - 1;
2098 
2099  if (TrailingBytes)
2100  AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
2101 
2102  for (; Chunk >= 0; --Chunk)
2103  AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2104  } else {
2105  unsigned Chunk;
2106  for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2107  AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
2108 
2109  if (TrailingBytes)
2110  AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
2111  }
2112 
2113  // Emit the tail padding for the long double.
2114  const DataLayout &DL = AP.getDataLayout();
2115  AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
2116  DL.getTypeStoreSize(CFP->getType()));
2117 }
2118 
2120  const DataLayout &DL = AP.getDataLayout();
2121  unsigned BitWidth = CI->getBitWidth();
2122 
2123  // Copy the value as we may massage the layout for constants whose bit width
2124  // is not a multiple of 64-bits.
2125  APInt Realigned(CI->getValue());
2126  uint64_t ExtraBits = 0;
2127  unsigned ExtraBitsSize = BitWidth & 63;
2128 
2129  if (ExtraBitsSize) {
2130  // The bit width of the data is not a multiple of 64-bits.
2131  // The extra bits are expected to be at the end of the chunk of the memory.
2132  // Little endian:
2133  // * Nothing to be done, just record the extra bits to emit.
2134  // Big endian:
2135  // * Record the extra bits to emit.
2136  // * Realign the raw data to emit the chunks of 64-bits.
2137  if (DL.isBigEndian()) {
2138  // Basically the structure of the raw data is a chunk of 64-bits cells:
2139  // 0 1 BitWidth / 64
2140  // [chunk1][chunk2] ... [chunkN].
2141  // The most significant chunk is chunkN and it should be emitted first.
2142  // However, due to the alignment issue chunkN contains useless bits.
2143  // Realign the chunks so that they contain only useless information:
2144  // ExtraBits 0 1 (BitWidth / 64) - 1
2145  // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2146  ExtraBits = Realigned.getRawData()[0] &
2147  (((uint64_t)-1) >> (64 - ExtraBitsSize));
2148  Realigned = Realigned.lshr(ExtraBitsSize);
2149  } else
2150  ExtraBits = Realigned.getRawData()[BitWidth / 64];
2151  }
2152 
2153  // We don't expect assemblers to support integer data directives
2154  // for more than 64 bits, so we emit the data in at most 64-bit
2155  // quantities at a time.
2156  const uint64_t *RawData = Realigned.getRawData();
2157  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2158  uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2159  AP.OutStreamer->EmitIntValue(Val, 8);
2160  }
2161 
2162  if (ExtraBitsSize) {
2163  // Emit the extra bits after the 64-bits chunks.
2164 
2165  // Emit a directive that fills the expected size.
2166  uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
2167  Size -= (BitWidth / 64) * 8;
2168  assert(Size && Size * 8 >= ExtraBitsSize &&
2169  (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2170  == ExtraBits && "Directive too small for extra bits.");
2171  AP.OutStreamer->EmitIntValue(ExtraBits, Size);
2172  }
2173 }
2174 
2175 /// \brief Transform a not absolute MCExpr containing a reference to a GOT
2176 /// equivalent global, by a target specific GOT pc relative access to the
2177 /// final symbol.
2178 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2179  const Constant *BaseCst,
2180  uint64_t Offset) {
2181  // The global @foo below illustrates a global that uses a got equivalent.
2182  //
2183  // @bar = global i32 42
2184  // @gotequiv = private unnamed_addr constant i32* @bar
2185  // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2186  // i64 ptrtoint (i32* @foo to i64))
2187  // to i32)
2188  //
2189  // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2190  // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2191  // form:
2192  //
2193  // foo = cstexpr, where
2194  // cstexpr := <gotequiv> - "." + <cst>
2195  // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2196  //
2197  // After canonicalization by evaluateAsRelocatable `ME` turns into:
2198  //
2199  // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2200  // gotpcrelcst := <offset from @foo base> + <cst>
2201  //
2202  MCValue MV;
2203  if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2204  return;
2205  const MCSymbolRefExpr *SymA = MV.getSymA();
2206  if (!SymA)
2207  return;
2208 
2209  // Check that GOT equivalent symbol is cached.
2210  const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2211  if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2212  return;
2213 
2214  const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2215  if (!BaseGV)
2216  return;
2217 
2218  // Check for a valid base symbol
2219  const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2220  const MCSymbolRefExpr *SymB = MV.getSymB();
2221 
2222  if (!SymB || BaseSym != &SymB->getSymbol())
2223  return;
2224 
2225  // Make sure to match:
2226  //
2227  // gotpcrelcst := <offset from @foo base> + <cst>
2228  //
2229  // If gotpcrelcst is positive it means that we can safely fold the pc rel
2230  // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2231  // if the target knows how to encode it.
2232  //
2233  int64_t GOTPCRelCst = Offset + MV.getConstant();
2234  if (GOTPCRelCst < 0)
2235  return;
2236  if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2237  return;
2238 
2239  // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2240  //
2241  // bar:
2242  // .long 42
2243  // gotequiv:
2244  // .quad bar
2245  // foo:
2246  // .long gotequiv - "." + <cst>
2247  //
2248  // is replaced by the target specific equivalent to:
2249  //
2250  // bar:
2251  // .long 42
2252  // foo:
2253  // .long bar@GOTPCREL+<gotpcrelcst>
2254  //
2255  AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2256  const GlobalVariable *GV = Result.first;
2257  int NumUses = (int)Result.second;
2258  const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
2259  const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
2261  FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
2262 
2263  // Update GOT equivalent usage information
2264  --NumUses;
2265  if (NumUses >= 0)
2266  AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
2267 }
2268 
2269 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
2270  AsmPrinter &AP, const Constant *BaseCV,
2271  uint64_t Offset) {
2272  uint64_t Size = DL.getTypeAllocSize(CV->getType());
2273 
2274  // Globals with sub-elements such as combinations of arrays and structs
2275  // are handled recursively by emitGlobalConstantImpl. Keep track of the
2276  // constant symbol base and the current position with BaseCV and Offset.
2277  if (!BaseCV && CV->hasOneUse())
2278  BaseCV = dyn_cast<Constant>(CV->user_back());
2279 
2280  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2281  return AP.OutStreamer->EmitZeros(Size);
2282 
2283  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2284  switch (Size) {
2285  case 1:
2286  case 2:
2287  case 4:
2288  case 8:
2289  if (AP.isVerbose())
2290  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2291  CI->getZExtValue());
2292  AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
2293  return;
2294  default:
2296  return;
2297  }
2298  }
2299 
2300  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2301  return emitGlobalConstantFP(CFP, AP);
2302 
2303  if (isa<ConstantPointerNull>(CV)) {
2304  AP.OutStreamer->EmitIntValue(0, Size);
2305  return;
2306  }
2307 
2308  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2309  return emitGlobalConstantDataSequential(DL, CDS, AP);
2310 
2311  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2312  return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
2313 
2314  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2315  return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
2316 
2317  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2318  // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2319  // vectors).
2320  if (CE->getOpcode() == Instruction::BitCast)
2321  return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
2322 
2323  if (Size > 8) {
2324  // If the constant expression's size is greater than 64-bits, then we have
2325  // to emit the value in chunks. Try to constant fold the value and emit it
2326  // that way.
2327  Constant *New = ConstantFoldConstant(CE, DL);
2328  if (New && New != CE)
2329  return emitGlobalConstantImpl(DL, New, AP);
2330  }
2331  }
2332 
2333  if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2334  return emitGlobalConstantVector(DL, V, AP);
2335 
2336  // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
2337  // thread the streamer with EmitValue.
2338  const MCExpr *ME = AP.lowerConstant(CV);
2339 
2340  // Since lowerConstant already folded and got rid of all IR pointer and
2341  // integer casts, detect GOT equivalent accesses by looking into the MCExpr
2342  // directly.
2344  handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
2345 
2346  AP.OutStreamer->EmitValue(ME, Size);
2347 }
2348 
2349 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2351  uint64_t Size = DL.getTypeAllocSize(CV->getType());
2352  if (Size)
2353  emitGlobalConstantImpl(DL, CV, *this);
2354  else if (MAI->hasSubsectionsViaSymbols()) {
2355  // If the global has zero size, emit a single byte so that two labels don't
2356  // look like they are at the same location.
2357  OutStreamer->EmitIntValue(0, 1);
2358  }
2359 }
2360 
2362  // Target doesn't support this yet!
2363  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2364 }
2365 
2366 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2367  if (Offset > 0)
2368  OS << '+' << Offset;
2369  else if (Offset < 0)
2370  OS << Offset;
2371 }
2372 
2373 //===----------------------------------------------------------------------===//
2374 // Symbol Lowering Routines.
2375 //===----------------------------------------------------------------------===//
2376 
2378  return OutContext.createTempSymbol(Name, true);
2379 }
2380 
2382  return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2383 }
2384 
2386  return MMI->getAddrLabelSymbol(BB);
2387 }
2388 
2389 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2390 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2391  const DataLayout &DL = getDataLayout();
2393  "CPI" + Twine(getFunctionNumber()) + "_" +
2394  Twine(CPID));
2395 }
2396 
2397 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2398 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2399  return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2400 }
2401 
2402 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2403 /// FIXME: privatize to AsmPrinter.
2404 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2405  const DataLayout &DL = getDataLayout();
2407  Twine(getFunctionNumber()) + "_" +
2408  Twine(UID) + "_set_" + Twine(MBBID));
2409 }
2410 
2412  StringRef Suffix) const {
2413  return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
2414 }
2415 
2416 /// Return the MCSymbol for the specified ExternalSymbol.
2418  SmallString<60> NameStr;
2419  Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
2420  return OutContext.getOrCreateSymbol(NameStr);
2421 }
2422 
2423 
2424 
2425 /// PrintParentLoopComment - Print comments about parent loops of this one.
2427  unsigned FunctionNumber) {
2428  if (!Loop) return;
2430  OS.indent(Loop->getLoopDepth()*2)
2431  << "Parent Loop BB" << FunctionNumber << "_"
2432  << Loop->getHeader()->getNumber()
2433  << " Depth=" << Loop->getLoopDepth() << '\n';
2434 }
2435 
2436 
2437 /// PrintChildLoopComment - Print comments about child loops within
2438 /// the loop for this basic block, with nesting.
2440  unsigned FunctionNumber) {
2441  // Add child loop information
2442  for (const MachineLoop *CL : *Loop) {
2443  OS.indent(CL->getLoopDepth()*2)
2444  << "Child Loop BB" << FunctionNumber << "_"
2445  << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
2446  << '\n';
2447  PrintChildLoopComment(OS, CL, FunctionNumber);
2448  }
2449 }
2450 
2451 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2453  const MachineLoopInfo *LI,
2454  const AsmPrinter &AP) {
2455  // Add loop depth information
2456  const MachineLoop *Loop = LI->getLoopFor(&MBB);
2457  if (!Loop) return;
2458 
2459  MachineBasicBlock *Header = Loop->getHeader();
2460  assert(Header && "No header for loop");
2461 
2462  // If this block is not a loop header, just print out what is the loop header
2463  // and return.
2464  if (Header != &MBB) {
2465  AP.OutStreamer->AddComment(" in Loop: Header=BB" +
2466  Twine(AP.getFunctionNumber())+"_" +
2467  Twine(Loop->getHeader()->getNumber())+
2468  " Depth="+Twine(Loop->getLoopDepth()));
2469  return;
2470  }
2471 
2472  // Otherwise, it is a loop header. Print out information about child and
2473  // parent loops.
2474  raw_ostream &OS = AP.OutStreamer->GetCommentOS();
2475 
2477 
2478  OS << "=>";
2479  OS.indent(Loop->getLoopDepth()*2-2);
2480 
2481  OS << "This ";
2482  if (Loop->empty())
2483  OS << "Inner ";
2484  OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2485 
2486  PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2487 }
2488 
2489 
2490 /// EmitBasicBlockStart - This method prints the label for the specified
2491 /// MachineBasicBlock, an alignment (if present) and a comment describing
2492 /// it if appropriate.
2494  // End the previous funclet and start a new one.
2495  if (MBB.isEHFuncletEntry()) {
2496  for (const HandlerInfo &HI : Handlers) {
2497  HI.Handler->endFunclet();
2498  HI.Handler->beginFunclet(MBB);
2499  }
2500  }
2501 
2502  // Emit an alignment directive for this block, if needed.
2503  if (unsigned Align = MBB.getAlignment())
2504  EmitAlignment(Align);
2505 
2506  // If the block has its address taken, emit any labels that were used to
2507  // reference the block. It is possible that there is more than one label
2508  // here, because multiple LLVM BB's may have been RAUW'd to this block after
2509  // the references were generated.
2510  if (MBB.hasAddressTaken()) {
2511  const BasicBlock *BB = MBB.getBasicBlock();
2512  if (isVerbose())
2513  OutStreamer->AddComment("Block address taken");
2514 
2515  // MBBs can have their address taken as part of CodeGen without having
2516  // their corresponding BB's address taken in IR
2517  if (BB->hasAddressTaken())
2518  for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
2519  OutStreamer->EmitLabel(Sym);
2520  }
2521 
2522  // Print some verbose block comments.
2523  if (isVerbose()) {
2524  if (const BasicBlock *BB = MBB.getBasicBlock()) {
2525  if (BB->hasName()) {
2526  BB->printAsOperand(OutStreamer->GetCommentOS(),
2527  /*PrintType=*/false, BB->getModule());
2528  OutStreamer->GetCommentOS() << '\n';
2529  }
2530  }
2531  emitBasicBlockLoopComments(MBB, LI, *this);
2532  }
2533 
2534  // Print the main label for the block.
2535  if (MBB.pred_empty() ||
2537  if (isVerbose()) {
2538  // NOTE: Want this comment at start of line, don't emit with AddComment.
2539  OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
2540  }
2541  } else {
2542  OutStreamer->EmitLabel(MBB.getSymbol());
2543  }
2544 }
2545 
2546 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2547  bool IsDefinition) const {
2548  MCSymbolAttr Attr = MCSA_Invalid;
2549 
2550  switch (Visibility) {
2551  default: break;
2553  if (IsDefinition)
2554  Attr = MAI->getHiddenVisibilityAttr();
2555  else
2557  break;
2559  Attr = MAI->getProtectedVisibilityAttr();
2560  break;
2561  }
2562 
2563  if (Attr != MCSA_Invalid)
2564  OutStreamer->EmitSymbolAttribute(Sym, Attr);
2565 }
2566 
2567 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2568 /// exactly one predecessor and the control transfer mechanism between
2569 /// the predecessor and this block is a fall-through.
2570 bool AsmPrinter::
2572  // If this is a landing pad, it isn't a fall through. If it has no preds,
2573  // then nothing falls through to it.
2574  if (MBB->isEHPad() || MBB->pred_empty())
2575  return false;
2576 
2577  // If there isn't exactly one predecessor, it can't be a fall through.
2578  if (MBB->pred_size() > 1)
2579  return false;
2580 
2581  // The predecessor has to be immediately before this block.
2582  MachineBasicBlock *Pred = *MBB->pred_begin();
2583  if (!Pred->isLayoutSuccessor(MBB))
2584  return false;
2585 
2586  // If the block is completely empty, then it definitely does fall through.
2587  if (Pred->empty())
2588  return true;
2589 
2590  // Check the terminators in the previous blocks
2591  for (const auto &MI : Pred->terminators()) {
2592  // If it is not a simple branch, we are in a table somewhere.
2593  if (!MI.isBranch() || MI.isIndirectBranch())
2594  return false;
2595 
2596  // If we are the operands of one of the branches, this is not a fall
2597  // through. Note that targets with delay slots will usually bundle
2598  // terminators with the delay slot instruction.
2599  for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
2600  if (OP->isJTI())
2601  return false;
2602  if (OP->isMBB() && OP->getMBB() == MBB)
2603  return false;
2604  }
2605  }
2606 
2607  return true;
2608 }
2609 
2610 
2611 
2612 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
2613  if (!S.usesMetadata())
2614  return nullptr;
2615 
2616  assert(!S.useStatepoints() && "statepoints do not currently support custom"
2617  " stackmap formats, please see the documentation for a description of"
2618  " the default format. If you really need a custom serialized format,"
2619  " please file a bug");
2620 
2621  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2622  gcp_map_type::iterator GCPI = GCMap.find(&S);
2623  if (GCPI != GCMap.end())
2624  return GCPI->second.get();
2625 
2626  auto Name = S.getName();
2627 
2630  E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2631  if (Name == I->getName()) {
2632  std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
2633  GMP->S = &S;
2634  auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
2635  return IterBool.first->second.get();
2636  }
2637 
2638  report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2639 }
2640 
2641 /// Pin vtable to this file.
2643 
2645 
2646 // In the binary's "xray_instr_map" section, an array of these function entries
2647 // describes each instrumentation point. When XRay patches your code, the index
2648 // into this table will be given to your handler as a patch point identifier.
2650  const MCSymbol *CurrentFnSym) const {
2651  Out->EmitSymbolValue(Sled, Bytes);
2652  Out->EmitSymbolValue(CurrentFnSym, Bytes);
2653  auto Kind8 = static_cast<uint8_t>(Kind);
2654  Out->EmitBytes(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
2655  Out->EmitBytes(
2656  StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
2657  Out->EmitZeros(2 * Bytes - 2); // Pad the previous two entries
2658 }
2659 
2661  if (Sleds.empty())
2662  return;
2663 
2664  auto PrevSection = OutStreamer->getCurrentSectionOnly();
2665  auto Fn = MF->getFunction();
2666  MCSection *Section = nullptr;
2668  if (Fn->hasComdat()) {
2669  Section = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
2671  Fn->getComdat()->getName());
2672  } else {
2673  Section = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
2674  ELF::SHF_ALLOC);
2675  }
2676  } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
2677  Section = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
2679  } else {
2680  llvm_unreachable("Unsupported target");
2681  }
2682 
2683  // Before we switch over, we force a reference to a label inside the
2684  // xray_instr_map section. Since this function is always called just
2685  // before the function's end, we assume that this is happening after
2686  // the last return instruction.
2687 
2688  auto WordSizeBytes = TM.getPointerSize();
2689  MCSymbol *Tmp = OutContext.createTempSymbol("xray_synthetic_", true);
2690  OutStreamer->EmitCodeAlignment(16);
2691  OutStreamer->EmitSymbolValue(Tmp, WordSizeBytes, false);
2692  OutStreamer->SwitchSection(Section);
2693  OutStreamer->EmitLabel(Tmp);
2694  for (const auto &Sled : Sleds)
2695  Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
2696 
2697  OutStreamer->SwitchSection(PrevSection);
2698  Sleds.clear();
2699 }
2700 
2702  SledKind Kind) {
2703  auto Fn = MI.getParent()->getParent()->getFunction();
2704  auto Attr = Fn->getFnAttribute("function-instrument");
2705  bool AlwaysInstrument =
2706  Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
2707  Sleds.emplace_back(
2708  XRayFunctionEntry{ Sled, CurrentFnSym, Kind, AlwaysInstrument, Fn });
2709 }
2710 
2712  return OutStreamer->getContext().getDwarfVersion();
2713 }
2714 
2716  OutStreamer->getContext().setDwarfVersion(Version);
2717 }
MachineLoop * L
std::vector< XRayFunctionEntry > Sleds
Definition: AsmPrinter.h:219
virtual void EmitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:376
void setDwarfVersion(uint16_t Version)
MachineConstantPoolValue * MachineCPVal
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:40
bool usesMetadata() const
If set, appropriate metadata tables must be emitted by the back-end (assembler, JIT, or otherwise).
Definition: GCStrategy.h:159
void push_back(const T &Elt)
Definition: SmallVector.h:211
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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:330
bool isEHPad() const
Returns true if the block is a landing pad.
bool doesSupportDebugInformation() const
Definition: MCAsmInfo.h:534
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:102
bool useAssignmentForEHBegin() const
Definition: MCAsmInfo.h:474
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
LinkageTypes getLinkage() const
Definition: GlobalValue.h:429
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:177
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
unsigned getAlignment() const
getAlignment - Return the alignment (log2, not bytes) of the function.
SectionKind getSectionKind(const DataLayout *DL) const
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:284
StringRef getTargetCPU() const
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:55
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:219
unsigned getOSMajorVersion() const
getOSMajorVersion - Return just the major version number, this is specialized because it is a common ...
Definition: Triple.h:312
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:575
Constant * getPrologueData() const
Get the prologue data associated with this function.
Definition: Function.cpp:1238
static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, const MachineLoopInfo *LI, const AsmPrinter &AP)
emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1309
bool hasIdentDirective() const
Definition: MCAsmInfo.h:516
bool needsLocalForSize() const
Definition: MCAsmInfo.h:475
const MCSymbol & getSymbol() const
Definition: MCExpr.h:311
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:84
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:298
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:371
static const char *const DbgTimerDescription
Definition: AsmPrinter.cpp:63
MCTargetOptions MCOptions
Machine level options.
STATISTIC(NumFunctions,"Total number of functions")
size_t i
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
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:120
.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...
WinEH::EncodingType getWinEHEncodingType() const
Definition: MCAsmInfo.h:539
const ConstantFP * getFPImm() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
Not a valid directive.
Definition: MCDirectives.h:20
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
void redefineIfPossible()
Prepare this symbol to be redefined.
Definition: MCSymbol.h:227
float convertToFloat() const
Definition: APFloat.h:1014
const DataLayout & getDataLayout() const
Return information about data layout.
Definition: AsmPrinter.cpp:148
bool doFinalization(Module &M) override
Shut down the asmprinter.
void EmitInt8(int Value) const
Emit a byte directive and value.
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:54
static void emitGlobalConstantDataSequential(const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP)
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:79
MCSymbol * getSymbol(const GlobalValue *GV) const
bool canBeOmittedFromSymbolTable(const GlobalValue *GV)
void print(raw_ostream &OS, bool isSigned) const
Definition: APInt.cpp:2257
.watchos_version_min
Definition: MCDirectives.h:68
uint64_t getElement(unsigned I) const
DILocalScope * getScope() const
Get the local scope for this variable.
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
Definition: Constants.h:148
void getWatchOSVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) const
getWatchOSVersion - Parse the version number as with getOSVersion.
Definition: Triple.cpp:1052
unsigned getNumOperands() const
Definition: User.h:167
Available for inspection, not emission.
Definition: GlobalValue.h:50
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1040
DWARF-like instruction based exceptions.
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...
virtual void EmitBytes(StringRef Data)
Emit the bytes in Data into the output.
Definition: MCStreamer.cpp:807
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...
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...
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index's element.
Definition: Constants.cpp:2641
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:196
.ios_version_min
Definition: MCDirectives.h:65
bool hasAppendingLinkage() const
Definition: GlobalValue.h:412
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:367
EK_Inline - Jump table entries are emitted inline at their point of use.
unsigned getPointerPrefAlignment(unsigned AS=0) const
Return target's alignment for stack-based pointers FIXME: The defaults need to be removed once all of...
Definition: DataLayout.cpp:599
const MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:87
static int Counter
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
bool isBSS() const
Definition: SectionKind.h:160
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
virtual void EmitDebugValue(const MCExpr *Value, unsigned Size) const
Emit the directive and value for debug thread local expression.
Definition: AsmPrinter.cpp:574
Externally visible function.
Definition: GlobalValue.h:49
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:148
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:402
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.
static const char *const DWARFGroupName
Definition: AsmPrinter.cpp:60
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
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...
virtual void EmitConstantPool()
Print to the current output stream assembly representations of the constants in the constant pool MCP...
MCSection * getDataSection() const
LoopT * getParentLoop() const
Definition: LoopInfo.h:103
unsigned getFunctionNumber() const
Return a unique ID for the current function.
Definition: AsmPrinter.cpp:140
const std::string & str() const
Definition: Triple.h:339
bool hasPrologueData() const
Check whether this function has prologue data.
Definition: Function.h:599
Metadata node.
Definition: Metadata.h:830
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:433
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:234
void EmitInt32(int Value) const
Emit a long directive and value.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
setjmp/longjmp based exceptions
const char * getWeakRefDirective() const
Definition: MCAsmInfo.h:520
.macosx_version_min
Definition: MCDirectives.h:66
ELFYAML::ELF_STV Visibility
Definition: ELFYAML.cpp:661
LCOMM::LCOMMType getLCOMMDirectiveAlignmentType() const
Definition: MCAsmInfo.h:510
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset...
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:156
static const MCBinaryExpr * createMul(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:473
Type * getElementType() const
Definition: DerivedTypes.h:462
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:712
static const char *const DWARFGroupDescription
Definition: AsmPrinter.cpp:61
bool hasLinkOnceDirective() const
Definition: MCAsmInfo.h:525
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:999
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1182
Tentative definitions.
Definition: GlobalValue.h:59
virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
Definition: MCStreamer.cpp:765
BlockT * getHeader() const
Definition: LoopInfo.h:102
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:366
Type * getPointerElementType() const
Definition: Type.h:358
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition: DataLayout.h:418
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
bool hasMachoTBSSDirective() const
Definition: MCAsmInfo.h:461
const Triple & getTargetTriple() const
unsigned getPointerTypeSize(Type *Ty) const
Definition: DataLayout.h:360
MCSymbolAttr getHiddenVisibilityAttr() const
Definition: MCAsmInfo.h:527
bool isMacOSX() const
isMacOSX - Is this a Mac OS X triple.
Definition: Triple.h:427
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
The address of a basic block.
Definition: Constants.h:822
static const MCBinaryExpr * createXor(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:501
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:496
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
A tuple of MDNodes.
Definition: Metadata.h:1282
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:1535
bool getAsmPrinterFlag(CommentFlag Flag) const
Return whether an AsmPrinter flag is set.
Definition: MachineInstr.h:141
Emits exception handling directives.
Definition: EHStreamer.h:32
bool hasCommonLinkage() const
Definition: GlobalValue.h:419
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool hasWeakDefDirective() const
Definition: MCAsmInfo.h:521
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
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.
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:334
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
const HexagonInstrInfo * TII
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:566
unsigned getCFIIndex() const
static void emitGlobalConstantStruct(const DataLayout &DL, const ConstantStruct *CS, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:143
bool hasSection() const
Definition: GlobalValue.h:255
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...
Class to represent struct types.
Definition: DerivedTypes.h:199
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
This class is basically a combination of TimeRegion and Timer.
Definition: Timer.h:160
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3) const
Definition: APFloat.h:1055
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:437
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
virtual TargetLoweringObjectFile * getObjFileLowering() const
iterator end() const
Definition: GCMetadata.h:198
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:308
const Module * getModule() const
Reg
All possible values of the reg field in the ModR/M byte.
iterator_range< iterator > terminators()
APInt bitcastToAPInt() const
Definition: APFloat.h:1012
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:161
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool hasMachoZeroFillDirective() const
Definition: MCAsmInfo.h:460
bool hasAltEntry() const
Definition: MCAsmInfo.h:518
.local (ELF)
Definition: MCDirectives.h:35
Only used in LLVM metadata.
Definition: Dwarf.h:112
uint16_t getDwarfVersion() const
An analysis pass which caches information about the entire Module.
Definition: GCMetadata.h:155
bool hasDebugInfo() const
Returns true if valid debug info is present.
StringRef getName() const
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:193
.no_dead_strip (MachO)
Definition: MCDirectives.h:36
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
bool hasPrivateLinkage() const
Definition: GlobalValue.h:414
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:589
bool isSplat(unsigned SplatSizeInBits) const
Check if the APInt consists of a repeated bit pattern.
Definition: APInt.cpp:640
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:277
static const char *const CodeViewLineTablesGroupName
Definition: AsmPrinter.cpp:66
void emitXRayTable()
Emit a table with all XRay instrumentation points.
Context object for machine code objects.
Definition: MCContext.h:51
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:241
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static const MCBinaryExpr * createShl(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:485
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
Definition: AsmPrinter.cpp:170
unsigned getCodeViewFlag() const
Returns the CodeView Version by checking module flags.
Definition: Module.cpp:475
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:873
void EmitFunctionBody()
This method emits the body and trailer for a function.
Definition: AsmPrinter.cpp:876
virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const
Check for post-frame ptr elimination stack locations as well.
static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS)
emitComments - Pretty-print comments for instructions.
Definition: AsmPrinter.cpp:663
#define F(x, y, z)
Definition: MD5.cpp:51
MCSection * getBSSSection() const
APInt zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:1015
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4139
bool useStatepoints() const
Returns true if this strategy is expecting the use of gc.statepoints, and false otherwise.
Definition: GCStrategy.h:115
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:497
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
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:274
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:564
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table...
MachineBasicBlock * MBB
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:3473
#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
const std::string & getName() const
Return the name of the GC strategy.
Definition: GCStrategy.h:101
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition: MCValue.h:52
const MCSection * getCurrentSection() const
Return the current section we are emitting to.
Definition: AsmPrinter.cpp:166
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:256
Function Alias Analysis false
.alt_entry (MachO)
Definition: MCDirectives.h:38
void EmitInt16(int Value) const
Emit a short directive and value.
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:81
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
EK_BlockAddress - Each entry is a plain address of block, e.g.
static Optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
SequentialType * getType() const
Specialize the getType() method to always return a SequentialType, which reduces the amount of castin...
Definition: Constants.h:619
This class is a data container for one entry in a MachineConstantPool.
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
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:700
int64_t getImm() const
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:429
bool isTvOS() const
Is this an Apple tvOS triple.
Definition: Triple.h:441
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:135
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:157
Type * getElementType() const
Definition: DerivedTypes.h:336
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...
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:90
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...
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:150
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 BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
Definition: AsmPrinter.cpp:318
static void emitGlobalConstantArray(const DataLayout &DL, const ConstantArray *CA, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
bool getCommDirectiveSupportsAlignment() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:131
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
TargetInstrInfo - Interface to description of machine instruction set.
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:517
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:57
ExternalWeak linkage description.
Definition: GlobalValue.h:58
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
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:731
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
bool needsDwarfSectionOffsetDirective() const
Definition: MCAsmInfo.h:454
unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
#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...
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:104
void EmitZeros(uint64_t NumBytes)
Emit NumBytes worth of zeros.
Definition: MCStreamer.cpp:173
Streaming machine code generation interface.
Definition: MCStreamer.h:161
virtual void EmitFunctionBodyEnd()
Targets can override this to emit stuff after the last basic block in the function.
Definition: AsmPrinter.h:342
static const char *const EHTimerDescription
Definition: AsmPrinter.cpp:65
virtual MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:218
unsigned getNumElements() const
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
MCSymbolAttr getHiddenDeclarationVisibilityAttr() const
Definition: MCAsmInfo.h:528
.weak_def_can_be_hidden (MachO)
Definition: MCDirectives.h:45
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:95
MCSymbolAttr getProtectedVisibilityAttr() const
Definition: MCAsmInfo.h:531
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.
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:75
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
.tvos_version_min
Definition: MCDirectives.h:67
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
Definition: AsmPrinter.cpp:108
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
This is an important base class in LLVM.
Definition: Constant.h:42
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2321
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1321
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.
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition: Constants.h:642
bool isThreadData() const
Definition: SectionKind.h:154
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:279
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind)
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2295
MCSymbol * getAddrLabelSymbol(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:145
MCSymbol * GetJTSetSymbol(unsigned UID, unsigned MBBID) const
Return the symbol for the specified jump table .set FIXME: privatize to AsmPrinter.
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
Definition: APInt.h:1947
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:269
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:368
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Definition: APInt.h:1952
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:481
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:71
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
bool hasFunctionAlignment() const
Definition: MCAsmInfo.h:513
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:67
Represent the analysis usage information of a pass.
virtual MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const
bool isWatchOS() const
Is this an Apple watchOS triple.
Definition: Triple.h:446
uint32_t Offset
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:3368
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
bool isPositionIndependent() const
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1255
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
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:340
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
uint64_t getNumElements() const
Definition: DerivedTypes.h:335
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:23
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:538
Value * getOperand(unsigned i) const
Definition: User.h:145
op_range operands()
Definition: User.h:213
static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintChildLoopComment - Print comments about child loops within the loop for this basic block...
DenseMap< GCStrategy *, std::unique_ptr< GCMetadataPrinter > > gcp_map_type
Definition: AsmPrinter.cpp:74
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
~AsmPrinter() override
Definition: AsmPrinter.cpp:123
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:490
void getiOSVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) const
getiOSVersion - Parse the version number as with getOSVersion.
Definition: Triple.cpp:1026
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
void emitFrameAlloc(const MachineInstr &MI)
Definition: AsmPrinter.cpp:864
.weak_reference (MachO)
Definition: MCDirectives.h:44
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
void computeGlobalGOTEquivs(Module &M)
Unnamed constant global variables solely contaning a pointer to another globals variable act like a g...
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:232
static const char *const EHTimerName
Definition: AsmPrinter.cpp:64
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol...
bool isBSSLocal() const
Definition: SectionKind.h:161
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:2585
bool isThreadBSS() const
Definition: SectionKind.h:153
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:48
bool hasWeakLinkage() const
Definition: GlobalValue.h:409
Abstract base class for all machine specific constantpool value subclasses.
static void emitGlobalConstantVector(const DataLayout &DL, const ConstantVector *CV, AsmPrinter &AP)
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
Definition: Module.cpp:468
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
virtual void markFunctionEnd()
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
Definition: raw_ostream.h:479
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isThreadLocal() const
Definition: SectionKind.h:149
Windows x64, Windows Itanium (IA-64)
static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, unsigned FunctionNumber)
PrintParentLoopComment - Print comments about parent loops of this one.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:594
void EmitAlignment(unsigned NumBits, const GlobalObject *GO=nullptr) const
Emit an alignment directive to the specified power of two boundary.
unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global, returned in log form.
Definition: DataLayout.cpp:791
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:226
virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const
Check for post-frame ptr elimination stack locations as well.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:455
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
Definition: Module.h:478
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:709
virtual const TargetFrameLowering * getFrameLowering() const
bool hasExternalLinkage() const
Definition: GlobalValue.h:401
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1034
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:187
void emitCFIInstruction(const MachineInstr &MI)
Definition: AsmPrinter.cpp:849
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition: Constants.h:430
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:425
bool doesSetDirectiveSuppressReloc() const
Definition: MCAsmInfo.h:503
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
static iterator begin()
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:204
SymbolListTy GetGVStubList()
Accessor methods to return the set of stubs in sorted order.
StringRef getTargetFeatureString() const
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition: AsmPrinter.h:105
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:47
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:408
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:67
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:354
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:51
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
void beginModule()
Emit all Dwarf sections that should come prior to the content.
Definition: DwarfDebug.cpp:501
virtual const TargetLowering * getTargetLowering() const
MCSection * getTLSExtraDataSection() const
Information about stack frame layout on the target.
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:161
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:503
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:415
BasicBlock * getBasicBlock() const
Definition: Constants.h:851
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:490
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:515
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.
MCSymbol * createTempSymbol(const Twine &Name) const
MCSymbolAttr
Definition: MCDirectives.h:19
bool isDefined(bool SetUsed=true) const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:245
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:134
DWARF expression.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
Collects and handles line tables information in a CodeView format.
Definition: CodeViewDebug.h:37
unsigned Log2_32(uint32_t Value)
Log2_32 - This function returns the floor log base 2 of the specified value, -1 if the value is zero...
Definition: MathExtras.h:513
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
const ConstantInt * getCImm() const
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
unsigned getOpcode() const
Definition: MCInst.h:159
void emit(int, MCStreamer *, const MCSymbol *) const
virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const
Targets can override this to emit stuff at the start of a basic block.
Class for arbitrary precision integers.
Definition: APInt.h:77
ConstantArray - Constant Array Declarations.
Definition: Constants.h:411
bool hasInitializer() const
Definitions have initializers, declarations don't.
virtual void EmitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:338
MCSymbol * getCurExceptionSym()
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
bool hasSingleParameterDotFile() const
Definition: MCAsmInfo.h:515
bool hasEHFunclets() const
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const
unsigned EmulatedTLS
EmulatedTLS - This flag enables emulated TLS model, using emutls function in the runtime library...
void setPreservesAll()
Set by analyses that do not transform their input at all.
StructType * getType() const
Specialization - reduce amount of casting.
Definition: Constants.h:477
iterator_range< user_iterator > users()
Definition: Value.h:370
const GlobalObject * getBaseObject() const
Definition: GlobalValue.h:517
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:130
virtual void emitModuleFlags(MCStreamer &Streamer, ArrayRef< Module::ModuleFlagEntry > Flags, const TargetMachine &TM) const
Emit the module flags that the platform cares about.
FunctionNumber(functionNumber)
Definition: LLParser.cpp:2459
double convertToDouble() const
Definition: APFloat.h:1013
static const fltSemantics & IEEEdouble()
Definition: APFloat.cpp:103
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
Definition: APInt.h:1942
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
Iterators for registry entries.
Definition: Registry.h:84
virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:405
Representation of each machine instruction.
Definition: MachineInstr.h:52
iterator begin() const
begin/end - Iterators for used strategies.
Definition: GCMetadata.h:197
static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, AsmPrinter &AP, const Constant *BaseCV=nullptr, uint64_t Offset=0)
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:259
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:384
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:265
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
bool hasNoDeadStrip() const
Definition: MCAsmInfo.h:517
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
Definition: AsmPrinter.cpp:179
GCStrategy describes a garbage collector algorithm's code generation requirements, and provides overridable hooks for those needs which cannot be abstractly described.
Definition: GCStrategy.h:78
void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:565
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:199
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:578
.type _foo,
Definition: MCDirectives.h:30
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:114
bool hasLinkerPrivateGlobalPrefix() const
Definition: DataLayout.h:262
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:188
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:108
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:368
.type _foo, STT_FUNC # aka
Definition: MCDirectives.h:23
virtual ~AsmPrinterHandler()
Pin vtable to this file.
const NodeList & List
Definition: RDFGraph.cpp:205
static unsigned getNumGlobalVariableUses(const Constant *C)
Compute the number of Global Variables that uses a Constant.
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:383
virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
Definition: AsmPrinter.h:351
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2314
MCSymbol * getMCSymbol() const
MCSubtargetInfo - Generic base class for all target subtargets.
unsigned getPointerSize() const
Return the pointer size from the TargetMachine.
Definition: AsmPrinter.cpp:154
static gcp_map_type & getGCMap(void *&P)
Definition: AsmPrinter.cpp:75
static const MCBinaryExpr * createMod(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:469
bool getMacOSXVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) const
getMacOSXVersion - Parse the version number as with getOSVersion and then translate generic "darwin" ...
Definition: Triple.cpp:985
bool isString() const
This method returns true if this is an array of i8.
Definition: Constants.cpp:2649
bool hasPrefixData() const
Check whether this function has prefix data.
Definition: Function.h:590
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:287
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:53
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
Definition: Attributes.cpp:153
virtual const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *, const MachineBasicBlock *, unsigned, MCContext &) const
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
const Triple & getTargetTriple() const
getTargetTriple - Return the target triple string.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:391
Constant * getPrefixData() const
Get the prefix data associated with this function.
Definition: Function.cpp:1228
.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:85
virtual void EmitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
Definition: AsmPrinter.cpp:647
bool isCommon() const
Definition: SectionKind.h:164
JTEntryKind getEntryKind() const
const Constant * getIndirectSymbol() const
bool hasLocalLinkage() const
Definition: GlobalValue.h:415
const DILocalVariable * getDebugVariable() const
Return the debug variable referenced by this DBG_VALUE instruction.
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:289
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
const APFloat & getValueAPF() const
Definition: Constants.h:300
CFIMoveType needsCFIMoves()
Definition: AsmPrinter.cpp:834
VectorType * getType() const
Specialize the getType() method to always return a VectorType, which reduces the amount of casting ne...
Definition: Constants.h:512
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2291
unsigned getPointerSize() const
Get the pointer size for this target.
unsigned getReg() const
getReg - Returns the register number.
bool use_empty() const
Definition: Value.h:299
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...
virtual MCSection * getNonexecutableStackSection(MCContext &Ctx) const
Targets can implement this method to specify a section to switch to if the translation unit doesn't h...
Definition: MCAsmInfo.h:415
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:144
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getAlignment() const
Definition: Globals.cpp:72
int64_t getConstant() const
Definition: MCValue.h:46
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:341
virtual const TargetInstrInfo * getInstrInfo() const
void EmitGlobalConstant(const DataLayout &DL, const Constant *CV)
Print a general LLVM constant to the .s file.
MCVersionMinType
Definition: MCDirectives.h:64
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
LLVM Value Representation.
Definition: Value.h:71
bool isKnownWindowsMSVCEnvironment() const
Checks if the environment is MSVC.
Definition: Triple.h:508
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...
bool hasSubsectionsViaSymbols() const
Definition: MCAsmInfo.h:397
ExceptionHandling
Windows CE ARM, PowerPC, SH3, SH4.
static const char *const DbgTimerName
Definition: AsmPrinter.cpp:62
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:239
bool isWindowsItaniumEnvironment() const
Definition: Triple.h:516
bool hasWeakDefCanBeHiddenDirective() const
Definition: MCAsmInfo.h:522
uint64_t getSize() const
Return the size in bytes of the memory reference.
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:44
bool empty() const
Definition: LoopInfo.h:136
const Target & getTarget() const
Primary interface to the complete machine description for the target machine.
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition: AsmPrinter.h:100
GCMetadataPrinter - Emits GC metadata as assembly code.
const std::vector< MachineConstantPoolEntry > & getConstants() const
iterator_range< global_iterator > globals()
Definition: Module.h:524
IRTranslator LLVM IR MI
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
A single uniqued string.
Definition: Metadata.h:586
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative...
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
No exception support.
union llvm::MachineConstantPoolEntry::@35 Val
The constant itself.
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:26
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:608
MCSection * getTLSBSSSection() const
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:289
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
bool hasDotTypeDotSizeDirective() const
Definition: MCAsmInfo.h:514
bool isVerbose() const
Return true if assembly output should contain comments.
Definition: AsmPrinter.h:162
bool isBigEndian() const
Definition: DataLayout.h:221
unsigned getLoopDepth() const
Return the nesting level of this loop.
Definition: LoopInfo.h:95
static SectionKind getReadOnly()
Definition: SectionKind.h:182
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
const uint64_t Version
Definition: InstrProf.h:799
bool isDeclarationForLinker() const
Definition: GlobalValue.h:496
#define OP(n)
Definition: regex2.h:70
unsigned pred_size() const
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:149
.end_data_region
Definition: MCDirectives.h:61
Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition: Type.cpp:554
User * user_back()
Definition: Value.h:356
This class contains meta information specific to a module.
This file describes how to lower LLVM code to machine code.
unsigned getAlignment() const
Return alignment of the basic block.
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:256
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:358
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1262
bool usesWindowsCFI() const
Definition: MCAsmInfo.h:552
MCSubtargetInfo & getSubtargetCopy(const MCSubtargetInfo &STI)
Definition: MCContext.cpp:465