LLVM  14.0.0git
AsmPrinter.cpp
Go to the documentation of this file.
1 //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AsmPrinter class.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "CodeViewDebug.h"
15 #include "DwarfDebug.h"
16 #include "DwarfException.h"
17 #include "PseudoProbePrinter.h"
18 #include "WasmException.h"
19 #include "WinCFGuard.h"
20 #include "WinException.h"
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
36 #include "llvm/BinaryFormat/COFF.h"
38 #include "llvm/BinaryFormat/ELF.h"
56 #include "llvm/CodeGen/StackMaps.h"
62 #include "llvm/Config/config.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/Comdat.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GCStrategy.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalIFunc.h"
74 #include "llvm/IR/GlobalObject.h"
75 #include "llvm/IR/GlobalValue.h"
76 #include "llvm/IR/GlobalVariable.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Mangler.h"
79 #include "llvm/IR/Metadata.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/Operator.h"
82 #include "llvm/IR/PseudoProbe.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/Value.h"
85 #include "llvm/MC/MCAsmInfo.h"
86 #include "llvm/MC/MCContext.h"
87 #include "llvm/MC/MCDirectives.h"
88 #include "llvm/MC/MCDwarf.h"
89 #include "llvm/MC/MCExpr.h"
90 #include "llvm/MC/MCInst.h"
91 #include "llvm/MC/MCSection.h"
92 #include "llvm/MC/MCSectionCOFF.h"
93 #include "llvm/MC/MCSectionELF.h"
94 #include "llvm/MC/MCSectionMachO.h"
95 #include "llvm/MC/MCSectionXCOFF.h"
96 #include "llvm/MC/MCStreamer.h"
98 #include "llvm/MC/MCSymbol.h"
99 #include "llvm/MC/MCSymbolELF.h"
100 #include "llvm/MC/MCSymbolXCOFF.h"
101 #include "llvm/MC/MCTargetOptions.h"
102 #include "llvm/MC/MCValue.h"
103 #include "llvm/MC/SectionKind.h"
104 #include "llvm/MC/TargetRegistry.h"
105 #include "llvm/Pass.h"
106 #include "llvm/Remarks/Remark.h"
110 #include "llvm/Support/Casting.h"
112 #include "llvm/Support/Compiler.h"
114 #include "llvm/Support/FileSystem.h"
115 #include "llvm/Support/Format.h"
116 #include "llvm/Support/MathExtras.h"
117 #include "llvm/Support/Path.h"
118 #include "llvm/Support/Timer.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <cinttypes>
126 #include <cstdint>
127 #include <iterator>
128 #include <limits>
129 #include <memory>
130 #include <string>
131 #include <utility>
132 #include <vector>
133 
134 using namespace llvm;
135 
136 #define DEBUG_TYPE "asm-printer"
137 
138 // FIXME: this option currently only applies to DWARF, and not CodeView, tables
139 static cl::opt<bool>
140  DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
141  cl::desc("Disable debug info printing"));
142 
143 const char DWARFGroupName[] = "dwarf";
144 const char DWARFGroupDescription[] = "DWARF Emission";
145 const char DbgTimerName[] = "emit";
146 const char DbgTimerDescription[] = "Debug Info Emission";
147 const char EHTimerName[] = "write_exception";
148 const char EHTimerDescription[] = "DWARF Exception Writer";
149 const char CFGuardName[] = "Control Flow Guard";
150 const char CFGuardDescription[] = "Control Flow Guard";
151 const char CodeViewLineTablesGroupName[] = "linetables";
152 const char CodeViewLineTablesGroupDescription[] = "CodeView Line Tables";
153 const char PPTimerName[] = "emit";
154 const char PPTimerDescription[] = "Pseudo Probe Emission";
155 const char PPGroupName[] = "pseudo probe";
156 const char PPGroupDescription[] = "Pseudo Probe Emission";
157 
158 STATISTIC(EmittedInsts, "Number of machine instrs printed");
159 
160 char AsmPrinter::ID = 0;
161 
163 
164 static gcp_map_type &getGCMap(void *&P) {
165  if (!P)
166  P = new gcp_map_type();
167  return *(gcp_map_type*)P;
168 }
169 
170 /// getGVAlignment - Return the alignment to use for the specified global
171 /// value. This rounds up to the preferred alignment if possible and legal.
173  Align InAlign) {
174  Align Alignment;
175  if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
176  Alignment = DL.getPreferredAlign(GVar);
177 
178  // If InAlign is specified, round it to it.
179  if (InAlign > Alignment)
180  Alignment = InAlign;
181 
182  // If the GV has a specified alignment, take it into account.
183  const MaybeAlign GVAlign(GV->getAlignment());
184  if (!GVAlign)
185  return Alignment;
186 
187  assert(GVAlign && "GVAlign must be set");
188 
189  // If the GVAlign is larger than NumBits, or if we are required to obey
190  // NumBits because the GV has an assigned section, obey it.
191  if (*GVAlign > Alignment || GV->hasSection())
192  Alignment = *GVAlign;
193  return Alignment;
194 }
195 
196 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
197  : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
198  OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
199  VerboseAsm = OutStreamer->isVerboseAsm();
200 }
201 
203  assert(!DD && Handlers.size() == NumUserHandlers &&
204  "Debug/EH info didn't get finalized");
205 
206  if (GCMetadataPrinters) {
207  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
208 
209  delete &GCMap;
210  GCMetadataPrinters = nullptr;
211  }
212 }
213 
215  return TM.isPositionIndependent();
216 }
217 
218 /// getFunctionNumber - Return a unique ID for the current function.
220  return MF->getFunctionNumber();
221 }
222 
224  return *TM.getObjFileLowering();
225 }
226 
228  return MMI->getModule()->getDataLayout();
229 }
230 
231 // Do not use the cached DataLayout because some client use it without a Module
232 // (dsymutil, llvm-dwarfdump).
233 unsigned AsmPrinter::getPointerSize() const {
234  return TM.getPointerSize(0); // FIXME: Default address space
235 }
236 
238  assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
239  return MF->getSubtarget<MCSubtargetInfo>();
240 }
241 
243  S.emitInstruction(Inst, getSubtargetInfo());
244 }
245 
247  if (DD) {
248  assert(OutStreamer->hasRawTextSupport() &&
249  "Expected assembly output mode.");
250  (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
251  }
252 }
253 
254 /// getCurrentSection() - Return the current section we are emitting to.
256  return OutStreamer->getCurrentSectionOnly();
257 }
258 
260  AU.setPreservesAll();
264 }
265 
267  auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
268  MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
269 
270  // Initialize TargetLoweringObjectFile.
272  .Initialize(OutContext, TM);
273 
275  .getModuleMetadata(M);
276 
277  OutStreamer->initSections(false, *TM.getMCSubtargetInfo());
278 
281 
282  // Emit the version-min deployment target directive if needed.
283  //
284  // FIXME: If we end up with a collection of these sorts of Darwin-specific
285  // or ELF-specific things, it may make sense to have a platform helper class
286  // that will work with the target helper class. For now keep it here, as the
287  // alternative is duplicated code in each of the target asm printers that
288  // use the directive, where it would need the same conditionalization
289  // anyway.
290  const Triple &Target = TM.getTargetTriple();
291  OutStreamer->emitVersionForTarget(Target, M.getSDKVersion());
292 
293  // Allow the target to emit any magic that it wants at the start of the file.
295 
296  // Very minimal debug info. It is ignored if we emit actual debug info. If we
297  // don't, this at least helps the user find where a global came from.
299  // .file "foo.c"
300 
301  SmallString<128> FileName;
303  FileName = llvm::sys::path::filename(M.getSourceFileName());
304  else
305  FileName = M.getSourceFileName();
306  if (MAI->hasFourStringsDotFile()) {
307 #ifdef PACKAGE_VENDOR
308  const char VerStr[] =
309  PACKAGE_VENDOR " " PACKAGE_NAME " version " PACKAGE_VERSION;
310 #else
311  const char VerStr[] = PACKAGE_NAME " version " PACKAGE_VERSION;
312 #endif
313  // TODO: Add timestamp and description.
314  OutStreamer->emitFileDirective(FileName, VerStr, "", "");
315  } else {
316  OutStreamer->emitFileDirective(FileName);
317  }
318  }
319 
320  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
321  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
322  for (auto &I : *MI)
323  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
324  MP->beginAssembly(M, *MI, *this);
325 
326  // Emit module-level inline asm if it exists.
327  if (!M.getModuleInlineAsm().empty()) {
328  OutStreamer->AddComment("Start of file scope inline assembly");
329  OutStreamer->AddBlankLine();
330  emitInlineAsm(M.getModuleInlineAsm() + "\n", *TM.getMCSubtargetInfo(),
332  OutStreamer->AddComment("End of file scope inline assembly");
333  OutStreamer->AddBlankLine();
334  }
335 
337  bool EmitCodeView = M.getCodeViewFlag();
338  if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
339  Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
343  }
344  if (!EmitCodeView || M.getDwarfVersion()) {
346  DD = new DwarfDebug(this);
347  Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
350  }
351  }
352  }
353 
354  if (M.getNamedMetadata(PseudoProbeDescMetadataName)) {
355  PP = new PseudoProbeHandler(this);
356  Handlers.emplace_back(std::unique_ptr<PseudoProbeHandler>(PP), PPTimerName,
358  }
359 
360  switch (MAI->getExceptionHandlingType()) {
362  // We may want to emit CFI for debug.
367  for (auto &F : M.getFunctionList()) {
369  ModuleCFISection = getFunctionCFISectionType(F);
370  // If any function needsUnwindTableEntry(), it needs .eh_frame and hence
371  // the module needs .eh_frame. If we have found that case, we are done.
372  if (ModuleCFISection == CFISection::EH)
373  break;
374  }
376  ModuleCFISection != CFISection::EH);
377  break;
378  default:
379  break;
380  }
381 
382  EHStreamer *ES = nullptr;
383  switch (MAI->getExceptionHandlingType()) {
385  if (!needsCFIForDebug())
386  break;
390  ES = new DwarfCFIException(this);
391  break;
393  ES = new ARMException(this);
394  break;
396  switch (MAI->getWinEHEncodingType()) {
397  default: llvm_unreachable("unsupported unwinding information encoding");
399  break;
402  ES = new WinException(this);
403  break;
404  }
405  break;
407  ES = new WasmException(this);
408  break;
410  ES = new AIXException(this);
411  break;
412  }
413  if (ES)
414  Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
417 
418  // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2).
419  if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard")))
420  Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
423 
424  for (const HandlerInfo &HI : Handlers) {
425  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
426  HI.TimerGroupDescription, TimePassesIsEnabled);
427  HI.Handler->beginModule(&M);
428  }
429 
430  return false;
431 }
432 
433 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
435  return false;
436 
437  return GV->canBeOmittedFromSymbolTable();
438 }
439 
440 void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
442  switch (Linkage) {
448  if (MAI->hasWeakDefDirective()) {
449  // .globl _foo
450  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
451 
452  if (!canBeHidden(GV, *MAI))
453  // .weak_definition _foo
454  OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition);
455  else
456  OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
457  } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) {
458  // .globl _foo
459  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
460  //NOTE: linkonce is handled by the section the symbol was assigned to.
461  } else {
462  // .weak _foo
463  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak);
464  }
465  return;
467  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global);
468  return;
471  return;
475  llvm_unreachable("Should never emit this");
476  }
477  llvm_unreachable("Unknown linkage type!");
478 }
479 
481  const GlobalValue *GV) const {
482  TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
483 }
484 
486  return TM.getSymbol(GV);
487 }
488 
490  // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an
491  // exact definion (intersection of GlobalValue::hasExactDefinition() and
492  // !isInterposable()). These linkages include: external, appending, internal,
493  // private. It may be profitable to use a local alias for external. The
494  // assembler would otherwise be conservative and assume a global default
495  // visibility symbol can be interposable, even if the code generator already
496  // assumed it.
498  const Module &M = *GV.getParent();
500  M.getPIELevel() == PIELevel::Default && GV.isDSOLocal())
501  return getSymbolWithGlobalValueBase(&GV, "$local");
502  }
503  return TM.getSymbol(&GV);
504 }
505 
506 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
508  bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
509  assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
510  "No emulated TLS variables in the common section");
511 
512  // Never emit TLS variable xyz in emulated TLS model.
513  // The initialization value is in __emutls_t.xyz instead of xyz.
514  if (IsEmuTLSVar)
515  return;
516 
517  if (GV->hasInitializer()) {
518  // Check to see if this is a special global used by LLVM, if so, emit it.
519  if (emitSpecialLLVMGlobal(GV))
520  return;
521 
522  // Skip the emission of global equivalents. The symbol can be emitted later
523  // on by emitGlobalGOTEquivs in case it turns out to be needed.
524  if (GlobalGOTEquivs.count(getSymbol(GV)))
525  return;
526 
527  if (isVerbose()) {
528  // When printing the control variable __emutls_v.*,
529  // we don't need to print the original TLS variable name.
530  GV->printAsOperand(OutStreamer->GetCommentOS(),
531  /*PrintType=*/false, GV->getParent());
532  OutStreamer->GetCommentOS() << '\n';
533  }
534  }
535 
536  MCSymbol *GVSym = getSymbol(GV);
537  MCSymbol *EmittedSym = GVSym;
538 
539  // getOrCreateEmuTLSControlSym only creates the symbol with name and default
540  // attributes.
541  // GV's or GVSym's attributes will be used for the EmittedSym.
542  emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
543 
544  if (!GV->hasInitializer()) // External globals require no extra code.
545  return;
546 
547  GVSym->redefineIfPossible();
548  if (GVSym->isDefined() || GVSym->isVariable())
549  OutContext.reportError(SMLoc(), "symbol '" + Twine(GVSym->getName()) +
550  "' is already defined");
551 
553  OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
554 
556 
557  const DataLayout &DL = GV->getParent()->getDataLayout();
558  uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
559 
560  // If the alignment is specified, we *must* obey it. Overaligning a global
561  // with a specified alignment is a prompt way to break globals emitted to
562  // sections and expected to be contiguous (e.g. ObjC metadata).
563  const Align Alignment = getGVAlignment(GV, DL);
564 
565  for (const HandlerInfo &HI : Handlers) {
566  NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
567  HI.TimerGroupName, HI.TimerGroupDescription,
569  HI.Handler->setSymbolSize(GVSym, Size);
570  }
571 
572  // Handle common symbols
573  if (GVKind.isCommon()) {
574  if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
575  // .comm _foo, 42, 4
576  const bool SupportsAlignment =
578  OutStreamer->emitCommonSymbol(GVSym, Size,
579  SupportsAlignment ? Alignment.value() : 0);
580  return;
581  }
582 
583  // Determine to which section this global should be emitted.
584  MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
585 
586  // If we have a bss global going to a section that supports the
587  // zerofill directive, do so here.
588  if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
589  TheSection->isVirtualSection()) {
590  if (Size == 0)
591  Size = 1; // zerofill of 0 bytes is undefined.
592  emitLinkage(GV, GVSym);
593  // .zerofill __DATA, __bss, _foo, 400, 5
594  OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value());
595  return;
596  }
597 
598  // If this is a BSS local symbol and we are emitting in the BSS
599  // section use .lcomm/.comm directive.
600  if (GVKind.isBSSLocal() &&
601  getObjFileLowering().getBSSSection() == TheSection) {
602  if (Size == 0)
603  Size = 1; // .comm Foo, 0 is undefined, avoid it.
604 
605  // Use .lcomm only if it supports user-specified alignment.
606  // Otherwise, while it would still be correct to use .lcomm in some
607  // cases (e.g. when Align == 1), the external assembler might enfore
608  // some -unknown- default alignment behavior, which could cause
609  // spurious differences between external and integrated assembler.
610  // Prefer to simply fall back to .local / .comm in this case.
612  // .lcomm _foo, 42
613  OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value());
614  return;
615  }
616 
617  // .local _foo
618  OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local);
619  // .comm _foo, 42, 4
620  const bool SupportsAlignment =
622  OutStreamer->emitCommonSymbol(GVSym, Size,
623  SupportsAlignment ? Alignment.value() : 0);
624  return;
625  }
626 
627  // Handle thread local data for mach-o which requires us to output an
628  // additional structure of data and mangle the original symbol so that we
629  // can reference it later.
630  //
631  // TODO: This should become an "emit thread local global" method on TLOF.
632  // All of this macho specific stuff should be sunk down into TLOFMachO and
633  // stuff like "TLSExtraDataSection" should no longer be part of the parent
634  // TLOF class. This will also make it more obvious that stuff like
635  // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
636  // specific code.
637  if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
638  // Emit the .tbss symbol
639  MCSymbol *MangSym =
640  OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
641 
642  if (GVKind.isThreadBSS()) {
643  TheSection = getObjFileLowering().getTLSBSSSection();
644  OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value());
645  } else if (GVKind.isThreadData()) {
646  OutStreamer->SwitchSection(TheSection);
647 
648  emitAlignment(Alignment, GV);
649  OutStreamer->emitLabel(MangSym);
650 
652  GV->getInitializer());
653  }
654 
655  OutStreamer->AddBlankLine();
656 
657  // Emit the variable struct for the runtime.
659 
660  OutStreamer->SwitchSection(TLVSect);
661  // Emit the linkage here.
662  emitLinkage(GV, GVSym);
663  OutStreamer->emitLabel(GVSym);
664 
665  // Three pointers in size:
666  // - __tlv_bootstrap - used to make sure support exists
667  // - spare pointer, used when mapped by the runtime
668  // - pointer to mangled symbol above with initializer
669  unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
670  OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
671  PtrSize);
672  OutStreamer->emitIntValue(0, PtrSize);
673  OutStreamer->emitSymbolValue(MangSym, PtrSize);
674 
675  OutStreamer->AddBlankLine();
676  return;
677  }
678 
679  MCSymbol *EmittedInitSym = GVSym;
680 
681  OutStreamer->SwitchSection(TheSection);
682 
683  emitLinkage(GV, EmittedInitSym);
684  emitAlignment(Alignment, GV);
685 
686  OutStreamer->emitLabel(EmittedInitSym);
687  MCSymbol *LocalAlias = getSymbolPreferLocal(*GV);
688  if (LocalAlias != EmittedInitSym)
689  OutStreamer->emitLabel(LocalAlias);
690 
692 
694  // .size foo, 42
695  OutStreamer->emitELFSize(EmittedInitSym,
697 
698  OutStreamer->AddBlankLine();
699 }
700 
701 /// Emit the directive and value for debug thread local expression
702 ///
703 /// \p Value - The value to emit.
704 /// \p Size - The size of the integer (in bytes) to emit.
705 void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
706  OutStreamer->emitValue(Value, Size);
707 }
708 
709 void AsmPrinter::emitFunctionHeaderComment() {}
710 
711 /// EmitFunctionHeader - This method emits the header for the current
712 /// function.
713 void AsmPrinter::emitFunctionHeader() {
714  const Function &F = MF->getFunction();
715 
716  if (isVerbose())
717  OutStreamer->GetCommentOS()
718  << "-- Begin function "
719  << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
720 
721  // Print out constants referenced by the function
723 
724  // Print the 'header' of function.
725  // If basic block sections are desired, explicitly request a unique section
726  // for this function's entry block.
727  if (MF->front().isBeginSection())
728  MF->setSection(getObjFileLowering().getUniqueSectionForFunction(F, TM));
729  else
730  MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM));
731  OutStreamer->SwitchSection(MF->getSection());
732 
734  emitVisibility(CurrentFnSym, F.getVisibility());
735 
738 
740  if (MAI->hasFunctionAlignment())
742 
744  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
745 
746  if (F.hasFnAttribute(Attribute::Cold))
747  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold);
748 
749  if (isVerbose()) {
750  F.printAsOperand(OutStreamer->GetCommentOS(),
751  /*PrintType=*/false, F.getParent());
752  emitFunctionHeaderComment();
753  OutStreamer->GetCommentOS() << '\n';
754  }
755 
756  // Emit the prefix data.
757  if (F.hasPrefixData()) {
758  if (MAI->hasSubsectionsViaSymbols()) {
759  // Preserving prefix data on platforms which use subsections-via-symbols
760  // is a bit tricky. Here we introduce a symbol for the prefix data
761  // and use the .alt_entry attribute to mark the function's real entry point
762  // as an alternative entry point to the prefix-data symbol.
764  OutStreamer->emitLabel(PrefixSym);
765 
766  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
767 
768  // Emit an .alt_entry directive for the actual function symbol.
769  OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
770  } else {
771  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
772  }
773  }
774 
775  // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily
776  // place prefix data before NOPs.
777  unsigned PatchableFunctionPrefix = 0;
778  unsigned PatchableFunctionEntry = 0;
779  (void)F.getFnAttribute("patchable-function-prefix")
780  .getValueAsString()
781  .getAsInteger(10, PatchableFunctionPrefix);
782  (void)F.getFnAttribute("patchable-function-entry")
783  .getValueAsString()
784  .getAsInteger(10, PatchableFunctionEntry);
785  if (PatchableFunctionPrefix) {
789  emitNops(PatchableFunctionPrefix);
790  } else if (PatchableFunctionEntry) {
791  // May be reassigned when emitting the body, to reference the label after
792  // the initial BTI (AArch64) or endbr32/endbr64 (x86).
794  }
795 
796  // Emit the function descriptor. This is a virtual function to allow targets
797  // to emit their specific function descriptor. Right now it is only used by
798  // the AIX target. The PowerPC 64-bit V1 ELF target also uses function
799  // descriptors and should be converted to use this hook as well.
802 
803  // Emit the CurrentFnSym. This is a virtual function to allow targets to do
804  // their wild and crazy things as required.
806 
807  // If the function had address-taken blocks that got deleted, then we have
808  // references to the dangling symbols. Emit them at the start of the function
809  // so that we don't get references to undefined symbols.
810  std::vector<MCSymbol*> DeadBlockSyms;
811  MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
812  for (MCSymbol *DeadBlockSym : DeadBlockSyms) {
813  OutStreamer->AddComment("Address taken block that was later removed");
814  OutStreamer->emitLabel(DeadBlockSym);
815  }
816 
817  if (CurrentFnBegin) {
818  if (MAI->useAssignmentForEHBegin()) {
820  OutStreamer->emitLabel(CurPos);
821  OutStreamer->emitAssignment(CurrentFnBegin,
823  } else {
824  OutStreamer->emitLabel(CurrentFnBegin);
825  }
826  }
827 
828  // Emit pre-function debug and/or EH information.
829  for (const HandlerInfo &HI : Handlers) {
830  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
831  HI.TimerGroupDescription, TimePassesIsEnabled);
832  HI.Handler->beginFunction(MF);
833  }
834 
835  // Emit the prologue data.
836  if (F.hasPrologueData())
837  emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
838 }
839 
840 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
841 /// function. This can be overridden by targets as required to do custom stuff.
844 
845  // The function label could have already been emitted if two symbols end up
846  // conflicting due to asm renaming. Detect this and emit an error.
847  if (CurrentFnSym->isVariable())
849  "' is a protected alias");
850 
851  OutStreamer->emitLabel(CurrentFnSym);
852 
855  if (Sym != CurrentFnSym)
856  OutStreamer->emitLabel(Sym);
857  }
858 }
859 
860 /// emitComments - Pretty-print comments for instructions.
861 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
862  const MachineFunction *MF = MI.getMF();
863  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
864 
865  // Check for spills and reloads
866 
867  // We assume a single instruction only has a spill or reload, not
868  // both.
870  if ((Size = MI.getRestoreSize(TII))) {
871  CommentOS << *Size << "-byte Reload\n";
872  } else if ((Size = MI.getFoldedRestoreSize(TII))) {
873  if (*Size) {
874  if (*Size == unsigned(MemoryLocation::UnknownSize))
875  CommentOS << "Unknown-size Folded Reload\n";
876  else
877  CommentOS << *Size << "-byte Folded Reload\n";
878  }
879  } else if ((Size = MI.getSpillSize(TII))) {
880  CommentOS << *Size << "-byte Spill\n";
881  } else if ((Size = MI.getFoldedSpillSize(TII))) {
882  if (*Size) {
883  if (*Size == unsigned(MemoryLocation::UnknownSize))
884  CommentOS << "Unknown-size Folded Spill\n";
885  else
886  CommentOS << *Size << "-byte Folded Spill\n";
887  }
888  }
889 
890  // Check for spill-induced copies
891  if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
892  CommentOS << " Reload Reuse\n";
893 }
894 
895 /// emitImplicitDef - This method emits the specified machine instruction
896 /// that is an implicit def.
898  Register RegNo = MI->getOperand(0).getReg();
899 
900  SmallString<128> Str;
901  raw_svector_ostream OS(Str);
902  OS << "implicit-def: "
903  << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
904 
905  OutStreamer->AddComment(OS.str());
906  OutStreamer->AddBlankLine();
907 }
908 
909 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
910  std::string Str;
911  raw_string_ostream OS(Str);
912  OS << "kill:";
913  for (const MachineOperand &Op : MI->operands()) {
914  assert(Op.isReg() && "KILL instruction must have only register operands");
915  OS << ' ' << (Op.isDef() ? "def " : "killed ")
916  << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
917  }
918  AP.OutStreamer->AddComment(OS.str());
919  AP.OutStreamer->AddBlankLine();
920 }
921 
922 /// emitDebugValueComment - This method handles the target-independent form
923 /// of DBG_VALUE, returning true if it was able to do so. A false return
924 /// means the target will need to handle MI in EmitInstruction.
926  // This code handles only the 4-operand target-independent form.
927  if (MI->isNonListDebugValue() && MI->getNumOperands() != 4)
928  return false;
929 
930  SmallString<128> Str;
931  raw_svector_ostream OS(Str);
932  OS << "DEBUG_VALUE: ";
933 
934  const DILocalVariable *V = MI->getDebugVariable();
935  if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
936  StringRef Name = SP->getName();
937  if (!Name.empty())
938  OS << Name << ":";
939  }
940  OS << V->getName();
941  OS << " <- ";
942 
943  const DIExpression *Expr = MI->getDebugExpression();
944  if (Expr->getNumElements()) {
945  OS << '[';
946  ListSeparator LS;
947  for (auto Op : Expr->expr_ops()) {
948  OS << LS << dwarf::OperationEncodingString(Op.getOp());
949  for (unsigned I = 0; I < Op.getNumArgs(); ++I)
950  OS << ' ' << Op.getArg(I);
951  }
952  OS << "] ";
953  }
954 
955  // Register or immediate value. Register 0 means undef.
956  for (const MachineOperand &Op : MI->debug_operands()) {
957  if (&Op != MI->debug_operands().begin())
958  OS << ", ";
959  switch (Op.getType()) {
961  APFloat APF = APFloat(Op.getFPImm()->getValueAPF());
962  Type *ImmTy = Op.getFPImm()->getType();
963  if (ImmTy->isBFloatTy() || ImmTy->isHalfTy() || ImmTy->isFloatTy() ||
964  ImmTy->isDoubleTy()) {
965  OS << APF.convertToDouble();
966  } else {
967  // There is no good way to print long double. Convert a copy to
968  // double. Ah well, it's only a comment.
969  bool ignored;
971  &ignored);
972  OS << "(long double) " << APF.convertToDouble();
973  }
974  break;
975  }
977  OS << Op.getImm();
978  break;
979  }
981  Op.getCImm()->getValue().print(OS, false /*isSigned*/);
982  break;
983  }
985  OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")";
986  // NOTE: Want this comment at start of line, don't emit with AddComment.
987  AP.OutStreamer->emitRawComment(OS.str());
988  break;
989  }
992  Register Reg;
994  if (Op.isReg()) {
995  Reg = Op.getReg();
996  } else {
997  const TargetFrameLowering *TFI =
999  Offset = TFI->getFrameIndexReference(*AP.MF, Op.getIndex(), Reg);
1000  }
1001  if (!Reg) {
1002  // Suppress offset, it is not meaningful here.
1003  OS << "undef";
1004  break;
1005  }
1006  // The second operand is only an offset if it's an immediate.
1007  if (MI->isIndirectDebugValue())
1008  Offset = StackOffset::getFixed(MI->getDebugOffset().getImm());
1009  if (Offset)
1010  OS << '[';
1011  OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
1012  if (Offset)
1013  OS << '+' << Offset->getFixed() << ']';
1014  break;
1015  }
1016  default:
1017  llvm_unreachable("Unknown operand type");
1018  }
1019  }
1020 
1021  // NOTE: Want this comment at start of line, don't emit with AddComment.
1022  AP.OutStreamer->emitRawComment(OS.str());
1023  return true;
1024 }
1025 
1026 /// This method handles the target-independent form of DBG_LABEL, returning
1027 /// true if it was able to do so. A false return means the target will need
1028 /// to handle MI in EmitInstruction.
1030  if (MI->getNumOperands() != 1)
1031  return false;
1032 
1033  SmallString<128> Str;
1034  raw_svector_ostream OS(Str);
1035  OS << "DEBUG_LABEL: ";
1036 
1037  const DILabel *V = MI->getDebugLabel();
1038  if (auto *SP = dyn_cast<DISubprogram>(
1040  StringRef Name = SP->getName();
1041  if (!Name.empty())
1042  OS << Name << ":";
1043  }
1044  OS << V->getName();
1045 
1046  // NOTE: Want this comment at start of line, don't emit with AddComment.
1047  AP.OutStreamer->emitRawComment(OS.str());
1048  return true;
1049 }
1050 
1053  // Ignore functions that won't get emitted.
1054  if (F.isDeclarationForLinker())
1055  return CFISection::None;
1056 
1058  F.needsUnwindTableEntry())
1059  return CFISection::EH;
1060 
1062  return CFISection::Debug;
1063 
1064  return CFISection::None;
1065 }
1066 
1070 }
1071 
1074 }
1075 
1078  MAI->doesUseCFIForDebug() && ModuleCFISection == CFISection::Debug;
1079 }
1080 
1082  ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
1083  if (!needsCFIForDebug() &&
1084  ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
1085  ExceptionHandlingType != ExceptionHandling::ARM)
1086  return;
1087 
1089  return;
1090 
1091  // If there is no "real" instruction following this CFI instruction, skip
1092  // emitting it; it would be beyond the end of the function's FDE range.
1093  auto *MBB = MI.getParent();
1094  auto I = std::next(MI.getIterator());
1095  while (I != MBB->end() && I->isTransient())
1096  ++I;
1097  if (I == MBB->instr_end() &&
1099  return;
1100 
1101  const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
1102  unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
1103  const MCCFIInstruction &CFI = Instrs[CFIIndex];
1104  emitCFIInstruction(CFI);
1105 }
1106 
1108  // The operands are the MCSymbol and the frame offset of the allocation.
1109  MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
1110  int FrameOffset = MI.getOperand(1).getImm();
1111 
1112  // Emit a symbol assignment.
1113  OutStreamer->emitAssignment(FrameAllocSym,
1114  MCConstantExpr::create(FrameOffset, OutContext));
1115 }
1116 
1117 /// Returns the BB metadata to be emitted in the .llvm_bb_addr_map section for a
1118 /// given basic block. This can be used to capture more precise profile
1119 /// information. We use the last 4 bits (LSBs) to encode the following
1120 /// information:
1121 /// * (1): set if return block (ret or tail call).
1122 /// * (2): set if ends with a tail call.
1123 /// * (3): set if exception handling (EH) landing pad.
1124 /// * (4): set if the block can fall through to its next.
1125 /// The remaining bits are zero.
1126 static unsigned getBBAddrMapMetadata(const MachineBasicBlock &MBB) {
1128  return ((unsigned)MBB.isReturnBlock()) |
1129  ((!MBB.empty() && TII->isTailCall(MBB.back())) << 1) |
1130  (MBB.isEHPad() << 2) |
1131  (const_cast<MachineBasicBlock &>(MBB).canFallThrough() << 3);
1132 }
1133 
1135  MCSection *BBAddrMapSection =
1137  assert(BBAddrMapSection && ".llvm_bb_addr_map section is not initialized.");
1138 
1139  const MCSymbol *FunctionSymbol = getFunctionBegin();
1140 
1141  OutStreamer->PushSection();
1142  OutStreamer->SwitchSection(BBAddrMapSection);
1143  OutStreamer->emitSymbolValue(FunctionSymbol, getPointerSize());
1144  // Emit the total number of basic blocks in this function.
1145  OutStreamer->emitULEB128IntValue(MF.size());
1146  // Emit BB Information for each basic block in the funciton.
1147  for (const MachineBasicBlock &MBB : MF) {
1148  const MCSymbol *MBBSymbol =
1149  MBB.isEntryBlock() ? FunctionSymbol : MBB.getSymbol();
1150  // Emit the basic block offset.
1151  emitLabelDifferenceAsULEB128(MBBSymbol, FunctionSymbol);
1152  // Emit the basic block size. When BBs have alignments, their size cannot
1153  // always be computed from their offsets.
1155  OutStreamer->emitULEB128IntValue(getBBAddrMapMetadata(MBB));
1156  }
1157  OutStreamer->PopSection();
1158 }
1159 
1161  auto GUID = MI.getOperand(0).getImm();
1162  auto Index = MI.getOperand(1).getImm();
1163  auto Type = MI.getOperand(2).getImm();
1164  auto Attr = MI.getOperand(3).getImm();
1165  DILocation *DebugLoc = MI.getDebugLoc();
1166  PP->emitPseudoProbe(GUID, Index, Type, Attr, DebugLoc);
1167 }
1168 
1171  return;
1172 
1173  MCSection *StackSizeSection =
1175  if (!StackSizeSection)
1176  return;
1177 
1178  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1179  // Don't emit functions with dynamic stack allocations.
1180  if (FrameInfo.hasVarSizedObjects())
1181  return;
1182 
1183  OutStreamer->PushSection();
1184  OutStreamer->SwitchSection(StackSizeSection);
1185 
1186  const MCSymbol *FunctionSymbol = getFunctionBegin();
1187  uint64_t StackSize = FrameInfo.getStackSize();
1188  OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
1189  OutStreamer->emitULEB128IntValue(StackSize);
1190 
1191  OutStreamer->PopSection();
1192 }
1193 
1195  const std::string &OutputFilename = MF.getTarget().Options.StackUsageOutput;
1196 
1197  // OutputFilename empty implies -fstack-usage is not passed.
1198  if (OutputFilename.empty())
1199  return;
1200 
1201  const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1202  uint64_t StackSize = FrameInfo.getStackSize();
1203 
1204  if (StackUsageStream == nullptr) {
1205  std::error_code EC;
1206  StackUsageStream =
1207  std::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::OF_Text);
1208  if (EC) {
1209  errs() << "Could not open file: " << EC.message();
1210  return;
1211  }
1212  }
1213 
1214  *StackUsageStream << MF.getFunction().getParent()->getName();
1215  if (const DISubprogram *DSP = MF.getFunction().getSubprogram())
1216  *StackUsageStream << ':' << DSP->getLine();
1217 
1218  *StackUsageStream << ':' << MF.getName() << '\t' << StackSize << '\t';
1219  if (FrameInfo.hasVarSizedObjects())
1220  *StackUsageStream << "dynamic\n";
1221  else
1222  *StackUsageStream << "static\n";
1223 }
1224 
1226  MachineModuleInfo &MMI = MF.getMMI();
1227  if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI.hasDebugInfo())
1228  return true;
1229 
1230  // We might emit an EH table that uses function begin and end labels even if
1231  // we don't have any landingpads.
1232  if (!MF.getFunction().hasPersonalityFn())
1233  return false;
1234  return !isNoOpWithoutInvoke(
1236 }
1237 
1238 /// EmitFunctionBody - This method emits the body and trailer for a
1239 /// function.
1241  emitFunctionHeader();
1242 
1243  // Emit target-specific gunk before the function body.
1245 
1246  if (isVerbose()) {
1247  // Get MachineDominatorTree or compute it on the fly if it's unavailable
1248  MDT = getAnalysisIfAvailable<MachineDominatorTree>();
1249  if (!MDT) {
1250  OwnedMDT = std::make_unique<MachineDominatorTree>();
1251  OwnedMDT->getBase().recalculate(*MF);
1252  MDT = OwnedMDT.get();
1253  }
1254 
1255  // Get MachineLoopInfo or compute it on the fly if it's unavailable
1256  MLI = getAnalysisIfAvailable<MachineLoopInfo>();
1257  if (!MLI) {
1258  OwnedMLI = std::make_unique<MachineLoopInfo>();
1259  OwnedMLI->getBase().analyze(MDT->getBase());
1260  MLI = OwnedMLI.get();
1261  }
1262  }
1263 
1264  // Print out code for the function.
1265  bool HasAnyRealCode = false;
1266  int NumInstsInFunction = 0;
1267 
1268  bool CanDoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
1269  for (auto &MBB : *MF) {
1270  // Print a label for the basic block.
1272  DenseMap<StringRef, unsigned> MnemonicCounts;
1273  for (auto &MI : MBB) {
1274  // Print the assembly for the instruction.
1275  if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
1276  !MI.isDebugInstr()) {
1277  HasAnyRealCode = true;
1278  ++NumInstsInFunction;
1279  }
1280 
1281  // If there is a pre-instruction symbol, emit a label for it here.
1282  if (MCSymbol *S = MI.getPreInstrSymbol())
1283  OutStreamer->emitLabel(S);
1284 
1285  for (const HandlerInfo &HI : Handlers) {
1286  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1287  HI.TimerGroupDescription, TimePassesIsEnabled);
1288  HI.Handler->beginInstruction(&MI);
1289  }
1290 
1291  if (isVerbose())
1292  emitComments(MI, OutStreamer->GetCommentOS());
1293 
1294  switch (MI.getOpcode()) {
1295  case TargetOpcode::CFI_INSTRUCTION:
1297  break;
1298  case TargetOpcode::LOCAL_ESCAPE:
1299  emitFrameAlloc(MI);
1300  break;
1303  case TargetOpcode::GC_LABEL:
1304  OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol());
1305  break;
1308  emitInlineAsm(&MI);
1309  break;
1310  case TargetOpcode::DBG_VALUE:
1311  case TargetOpcode::DBG_VALUE_LIST:
1312  if (isVerbose()) {
1313  if (!emitDebugValueComment(&MI, *this))
1314  emitInstruction(&MI);
1315  }
1316  break;
1317  case TargetOpcode::DBG_INSTR_REF:
1318  // This instruction reference will have been resolved to a machine
1319  // location, and a nearby DBG_VALUE created. We can safely ignore
1320  // the instruction reference.
1321  break;
1322  case TargetOpcode::DBG_PHI:
1323  // This instruction is only used to label a program point, it's purely
1324  // meta information.
1325  break;
1326  case TargetOpcode::DBG_LABEL:
1327  if (isVerbose()) {
1328  if (!emitDebugLabelComment(&MI, *this))
1329  emitInstruction(&MI);
1330  }
1331  break;
1332  case TargetOpcode::IMPLICIT_DEF:
1333  if (isVerbose()) emitImplicitDef(&MI);
1334  break;
1335  case TargetOpcode::KILL:
1336  if (isVerbose()) emitKill(&MI, *this);
1337  break;
1340  break;
1342  if (isVerbose())
1343  OutStreamer->emitRawComment("ARITH_FENCE");
1344  break;
1345  default:
1346  emitInstruction(&MI);
1347  if (CanDoExtraAnalysis) {
1348  MCInst MCI;
1349  MCI.setOpcode(MI.getOpcode());
1350  auto Name = OutStreamer->getMnemonic(MCI);
1351  auto I = MnemonicCounts.insert({Name, 0u});
1352  I.first->second++;
1353  }
1354  break;
1355  }
1356 
1357  // If there is a post-instruction symbol, emit a label for it here.
1358  if (MCSymbol *S = MI.getPostInstrSymbol())
1359  OutStreamer->emitLabel(S);
1360 
1361  for (const HandlerInfo &HI : Handlers) {
1362  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1363  HI.TimerGroupDescription, TimePassesIsEnabled);
1364  HI.Handler->endInstruction();
1365  }
1366  }
1367 
1368  // We must emit temporary symbol for the end of this basic block, if either
1369  // we have BBLabels enabled or if this basic blocks marks the end of a
1370  // section.
1371  if (MF->hasBBLabels() ||
1373  OutStreamer->emitLabel(MBB.getEndSymbol());
1374 
1375  if (MBB.isEndSection()) {
1376  // The size directive for the section containing the entry block is
1377  // handled separately by the function section.
1378  if (!MBB.sameSection(&MF->front())) {
1380  // Emit the size directive for the basic block section.
1381  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1383  MCSymbolRefExpr::create(CurrentSectionBeginSym, OutContext),
1384  OutContext);
1385  OutStreamer->emitELFSize(CurrentSectionBeginSym, SizeExp);
1386  }
1388  MBBSectionRange{CurrentSectionBeginSym, MBB.getEndSymbol()};
1389  }
1390  }
1392 
1393  if (CanDoExtraAnalysis) {
1394  // Skip empty blocks.
1395  if (MBB.empty())
1396  continue;
1397 
1398  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionMix",
1399  MBB.begin()->getDebugLoc(), &MBB);
1400 
1401  // Generate instruction mix remark. First, sort counts in descending order
1402  // by count and name.
1404  for (auto &KV : MnemonicCounts)
1405  MnemonicVec.emplace_back(KV.first, KV.second);
1406 
1407  sort(MnemonicVec, [](const std::pair<StringRef, unsigned> &A,
1408  const std::pair<StringRef, unsigned> &B) {
1409  if (A.second > B.second)
1410  return true;
1411  if (A.second == B.second)
1412  return StringRef(A.first) < StringRef(B.first);
1413  return false;
1414  });
1415  R << "BasicBlock: " << ore::NV("BasicBlock", MBB.getName()) << "\n";
1416  for (auto &KV : MnemonicVec) {
1417  auto Name = (Twine("INST_") + getToken(KV.first.trim()).first).str();
1418  R << KV.first << ": " << ore::NV(Name, KV.second) << "\n";
1419  }
1420  ORE->emit(R);
1421  }
1422  }
1423 
1424  EmittedInsts += NumInstsInFunction;
1425  MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
1427  &MF->front());
1428  R << ore::NV("NumInstructions", NumInstsInFunction)
1429  << " instructions in function";
1430  ORE->emit(R);
1431 
1432  // If the function is empty and the object file uses .subsections_via_symbols,
1433  // then we need to emit *something* to the function body to prevent the
1434  // labels from collapsing together. Just emit a noop.
1435  // Similarly, don't emit empty functions on Windows either. It can lead to
1436  // duplicate entries (two functions with the same RVA) in the Guard CF Table
1437  // after linking, causing the kernel not to load the binary:
1438  // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
1439  // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
1440  const Triple &TT = TM.getTargetTriple();
1441  if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
1442  (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
1443  MCInst Noop = MF->getSubtarget().getInstrInfo()->getNop();
1444 
1445  // Targets can opt-out of emitting the noop here by leaving the opcode
1446  // unspecified.
1447  if (Noop.getOpcode()) {
1448  OutStreamer->AddComment("avoids zero-length function");
1449  emitNops(1);
1450  }
1451  }
1452 
1453  // Switch to the original section in case basic block sections was used.
1454  OutStreamer->SwitchSection(MF->getSection());
1455 
1456  const Function &F = MF->getFunction();
1457  for (const auto &BB : F) {
1458  if (!BB.hasAddressTaken())
1459  continue;
1461  if (Sym->isDefined())
1462  continue;
1463  OutStreamer->AddComment("Address of block that was removed by CodeGen");
1464  OutStreamer->emitLabel(Sym);
1465  }
1466 
1467  // Emit target-specific gunk after the function body.
1469 
1472  // Create a symbol for the end of function.
1473  CurrentFnEnd = createTempSymbol("func_end");
1474  OutStreamer->emitLabel(CurrentFnEnd);
1475  }
1476 
1477  // If the target wants a .size directive for the size of the function, emit
1478  // it.
1480  // We can get the size as difference between the function label and the
1481  // temp label.
1482  const MCExpr *SizeExp = MCBinaryExpr::createSub(
1483  MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
1485  OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
1486  }
1487 
1488  for (const HandlerInfo &HI : Handlers) {
1489  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1490  HI.TimerGroupDescription, TimePassesIsEnabled);
1491  HI.Handler->markFunctionEnd();
1492  }
1493 
1495  MBBSectionRange{CurrentFnBegin, CurrentFnEnd};
1496 
1497  // Print out jump tables referenced by the function.
1499 
1500  // Emit post-function debug and/or EH information.
1501  for (const HandlerInfo &HI : Handlers) {
1502  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1503  HI.TimerGroupDescription, TimePassesIsEnabled);
1504  HI.Handler->endFunction(MF);
1505  }
1506 
1507  // Emit section containing BB address offsets and their metadata, when
1508  // BB labels are requested for this function. Skip empty functions.
1509  if (MF->hasBBLabels() && HasAnyRealCode)
1511 
1512  // Emit section containing stack size metadata.
1514 
1515  // Emit .su file containing function stack size information.
1516  emitStackUsage(*MF);
1517 
1519 
1520  if (isVerbose())
1521  OutStreamer->GetCommentOS() << "-- End function\n";
1522 
1523  OutStreamer->AddBlankLine();
1524 }
1525 
1526 /// Compute the number of Global Variables that uses a Constant.
1527 static unsigned getNumGlobalVariableUses(const Constant *C) {
1528  if (!C)
1529  return 0;
1530 
1531  if (isa<GlobalVariable>(C))
1532  return 1;
1533 
1534  unsigned NumUses = 0;
1535  for (auto *CU : C->users())
1536  NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
1537 
1538  return NumUses;
1539 }
1540 
1541 /// Only consider global GOT equivalents if at least one user is a
1542 /// cstexpr inside an initializer of another global variables. Also, don't
1543 /// handle cstexpr inside instructions. During global variable emission,
1544 /// candidates are skipped and are emitted later in case at least one cstexpr
1545 /// isn't replaced by a PC relative GOT entry access.
1547  unsigned &NumGOTEquivUsers) {
1548  // Global GOT equivalents are unnamed private globals with a constant
1549  // pointer initializer to another global symbol. They must point to a
1550  // GlobalVariable or Function, i.e., as GlobalValue.
1551  if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
1552  !GV->isConstant() || !GV->isDiscardableIfUnused() ||
1553  !isa<GlobalValue>(GV->getOperand(0)))
1554  return false;
1555 
1556  // To be a got equivalent, at least one of its users need to be a constant
1557  // expression used by another global variable.
1558  for (auto *U : GV->users())
1559  NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
1560 
1561  return NumGOTEquivUsers > 0;
1562 }
1563 
1564 /// Unnamed constant global variables solely contaning a pointer to
1565 /// another globals variable is equivalent to a GOT table entry; it contains the
1566 /// the address of another symbol. Optimize it and replace accesses to these
1567 /// "GOT equivalents" by using the GOT entry for the final global instead.
1568 /// Compute GOT equivalent candidates among all global variables to avoid
1569 /// emitting them if possible later on, after it use is replaced by a GOT entry
1570 /// access.
1572  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1573  return;
1574 
1575  for (const auto &G : M.globals()) {
1576  unsigned NumGOTEquivUsers = 0;
1577  if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
1578  continue;
1579 
1580  const MCSymbol *GOTEquivSym = getSymbol(&G);
1581  GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
1582  }
1583 }
1584 
1585 /// Constant expressions using GOT equivalent globals may not be eligible
1586 /// for PC relative GOT entry conversion, in such cases we need to emit such
1587 /// globals we previously omitted in EmitGlobalVariable.
1589  if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
1590  return;
1591 
1592  SmallVector<const GlobalVariable *, 8> FailedCandidates;
1593  for (auto &I : GlobalGOTEquivs) {
1594  const GlobalVariable *GV = I.second.first;
1595  unsigned Cnt = I.second.second;
1596  if (Cnt)
1597  FailedCandidates.push_back(GV);
1598  }
1599  GlobalGOTEquivs.clear();
1600 
1601  for (auto *GV : FailedCandidates)
1602  emitGlobalVariable(GV);
1603 }
1604 
1605 void AsmPrinter::emitGlobalAlias(Module &M, const GlobalAlias &GA) {
1606  MCSymbol *Name = getSymbol(&GA);
1607  bool IsFunction = GA.getValueType()->isFunctionTy();
1608  // Treat bitcasts of functions as functions also. This is important at least
1609  // on WebAssembly where object and function addresses can't alias each other.
1610  if (!IsFunction)
1611  if (auto *CE = dyn_cast<ConstantExpr>(GA.getAliasee()))
1612  if (CE->getOpcode() == Instruction::BitCast)
1613  IsFunction =
1614  CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
1615 
1616  // AIX's assembly directive `.set` is not usable for aliasing purpose,
1617  // so AIX has to use the extra-label-at-definition strategy. At this
1618  // point, all the extra label is emitted, we just have to emit linkage for
1619  // those labels.
1622  "Visibility should be handled with emitLinkage() on AIX.");
1623  emitLinkage(&GA, Name);
1624  // If it's a function, also emit linkage for aliases of function entry
1625  // point.
1626  if (IsFunction)
1627  emitLinkage(&GA,
1628  getObjFileLowering().getFunctionEntryPointSymbol(&GA, TM));
1629  return;
1630  }
1631 
1632  if (GA.hasExternalLinkage() || !MAI->getWeakRefDirective())
1633  OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1634  else if (GA.hasWeakLinkage() || GA.hasLinkOnceLinkage())
1635  OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1636  else
1637  assert(GA.hasLocalLinkage() && "Invalid alias linkage");
1638 
1639  // Set the symbol type to function if the alias has a function type.
1640  // This affects codegen when the aliasee is not a function.
1641  if (IsFunction)
1642  OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
1643 
1645 
1646  const MCExpr *Expr = lowerConstant(GA.getAliasee());
1647 
1648  if (MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
1649  OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry);
1650 
1651  // Emit the directives as assignments aka .set:
1652  OutStreamer->emitAssignment(Name, Expr);
1653  MCSymbol *LocalAlias = getSymbolPreferLocal(GA);
1654  if (LocalAlias != Name)
1655  OutStreamer->emitAssignment(LocalAlias, Expr);
1656 
1657  // If the aliasee does not correspond to a symbol in the output, i.e. the
1658  // alias is not of an object or the aliased object is private, then set the
1659  // size of the alias symbol from the type of the alias. We don't do this in
1660  // other situations as the alias and aliasee having differing types but same
1661  // size may be intentional.
1662  const GlobalObject *BaseObject = GA.getAliaseeObject();
1663  if (MAI->hasDotTypeDotSizeDirective() && GA.getValueType()->isSized() &&
1664  (!BaseObject || BaseObject->hasPrivateLinkage())) {
1665  const DataLayout &DL = M.getDataLayout();
1666  uint64_t Size = DL.getTypeAllocSize(GA.getValueType());
1668  }
1669 }
1670 
1671 void AsmPrinter::emitGlobalIFunc(Module &M, const GlobalIFunc &GI) {
1673  "IFunc is not supported on AIX.");
1674 
1675  MCSymbol *Name = getSymbol(&GI);
1676 
1677  if (GI.hasExternalLinkage() || !MAI->getWeakRefDirective())
1678  OutStreamer->emitSymbolAttribute(Name, MCSA_Global);
1679  else if (GI.hasWeakLinkage() || GI.hasLinkOnceLinkage())
1680  OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference);
1681  else
1682  assert(GI.hasLocalLinkage() && "Invalid ifunc linkage");
1683 
1684  OutStreamer->emitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
1686 
1687  // Emit the directives as assignments aka .set:
1688  const MCExpr *Expr = lowerConstant(GI.getResolver());
1689  OutStreamer->emitAssignment(Name, Expr);
1690  MCSymbol *LocalAlias = getSymbolPreferLocal(GI);
1691  if (LocalAlias != Name)
1692  OutStreamer->emitAssignment(LocalAlias, Expr);
1693 }
1694 
1696  if (!RS.needsSection())
1697  return;
1698 
1699  remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer();
1700 
1701  Optional<SmallString<128>> Filename;
1702  if (Optional<StringRef> FilenameRef = RS.getFilename()) {
1703  Filename = *FilenameRef;
1704  sys::fs::make_absolute(*Filename);
1705  assert(!Filename->empty() && "The filename can't be empty.");
1706  }
1707 
1708  std::string Buf;
1709  raw_string_ostream OS(Buf);
1710  std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
1711  Filename ? RemarkSerializer.metaSerializer(OS, Filename->str())
1712  : RemarkSerializer.metaSerializer(OS);
1713  MetaSerializer->emit();
1714 
1715  // Switch to the remarks section.
1716  MCSection *RemarksSection =
1718  OutStreamer->SwitchSection(RemarksSection);
1719 
1720  OutStreamer->emitBinaryData(OS.str());
1721 }
1722 
1724  // Set the MachineFunction to nullptr so that we can catch attempted
1725  // accesses to MF specific features at the module level and so that
1726  // we can conditionalize accesses based on whether or not it is nullptr.
1727  MF = nullptr;
1728 
1729  // Gather all GOT equivalent globals in the module. We really need two
1730  // passes over the globals: one to compute and another to avoid its emission
1731  // in EmitGlobalVariable, otherwise we would not be able to handle cases
1732  // where the got equivalent shows up before its use.
1734 
1735  // Emit global variables.
1736  for (const auto &G : M.globals())
1738 
1739  // Emit remaining GOT equivalent globals.
1741 
1743 
1744  // Emit linkage(XCOFF) and visibility info for declarations
1745  for (const Function &F : M) {
1746  if (!F.isDeclarationForLinker())
1747  continue;
1748 
1749  MCSymbol *Name = getSymbol(&F);
1750  // Function getSymbol gives us the function descriptor symbol for XCOFF.
1751 
1753  GlobalValue::VisibilityTypes V = F.getVisibility();
1755  continue;
1756 
1757  emitVisibility(Name, V, false);
1758  continue;
1759  }
1760 
1761  if (F.isIntrinsic())
1762  continue;
1763 
1764  // Handle the XCOFF case.
1765  // Variable `Name` is the function descriptor symbol (see above). Get the
1766  // function entry point symbol.
1767  MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM);
1768  // Emit linkage for the function entry point.
1769  emitLinkage(&F, FnEntryPointSym);
1770 
1771  // Emit linkage for the function descriptor.
1772  emitLinkage(&F, Name);
1773  }
1774 
1775  // Emit the remarks section contents.
1776  // FIXME: Figure out when is the safest time to emit this section. It should
1777  // not come after debug info.
1778  if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer())
1779  emitRemarksSection(*RS);
1780 
1782 
1785 
1786  // Output stubs for external and common global variables.
1788  if (!Stubs.empty()) {
1789  OutStreamer->SwitchSection(TLOF.getDataSection());
1790  const DataLayout &DL = M.getDataLayout();
1791 
1792  emitAlignment(Align(DL.getPointerSize()));
1793  for (const auto &Stub : Stubs) {
1794  OutStreamer->emitLabel(Stub.first);
1795  OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1796  DL.getPointerSize());
1797  }
1798  }
1799  }
1800 
1802  MachineModuleInfoCOFF &MMICOFF =
1804 
1805  // Output stubs for external and common global variables.
1807  if (!Stubs.empty()) {
1808  const DataLayout &DL = M.getDataLayout();
1809 
1810  for (const auto &Stub : Stubs) {
1811  SmallString<256> SectionName = StringRef(".rdata$");
1812  SectionName += Stub.first->getName();
1813  OutStreamer->SwitchSection(OutContext.getCOFFSection(
1814  SectionName,
1817  SectionKind::getReadOnly(), Stub.first->getName(),
1819  emitAlignment(Align(DL.getPointerSize()));
1820  OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global);
1821  OutStreamer->emitLabel(Stub.first);
1822  OutStreamer->emitSymbolValue(Stub.second.getPointer(),
1823  DL.getPointerSize());
1824  }
1825  }
1826  }
1827 
1828  // This needs to happen before emitting debug information since that can end
1829  // arbitrary sections.
1830  if (auto *TS = OutStreamer->getTargetStreamer())
1831  TS->emitConstantPools();
1832 
1833  // Finalize debug and EH information.
1834  for (const HandlerInfo &HI : Handlers) {
1835  NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
1836  HI.TimerGroupDescription, TimePassesIsEnabled);
1837  HI.Handler->endModule();
1838  }
1839 
1840  // This deletes all the ephemeral handlers that AsmPrinter added, while
1841  // keeping all the user-added handlers alive until the AsmPrinter is
1842  // destroyed.
1843  Handlers.erase(Handlers.begin() + NumUserHandlers, Handlers.end());
1844  DD = nullptr;
1845 
1846  // If the target wants to know about weak references, print them all.
1847  if (MAI->getWeakRefDirective()) {
1848  // FIXME: This is not lazy, it would be nice to only print weak references
1849  // to stuff that is actually used. Note that doing so would require targets
1850  // to notice uses in operands (due to constant exprs etc). This should
1851  // happen with the MC stuff eventually.
1852 
1853  // Print out module-level global objects here.
1854  for (const auto &GO : M.global_objects()) {
1855  if (!GO.hasExternalWeakLinkage())
1856  continue;
1857  OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
1858  }
1859  }
1860 
1861  // Print aliases in topological order, that is, for each alias a = b,
1862  // b must be printed before a.
1863  // This is because on some targets (e.g. PowerPC) linker expects aliases in
1864  // such an order to generate correct TOC information.
1867  for (const auto &Alias : M.aliases()) {
1868  for (const GlobalAlias *Cur = &Alias; Cur;
1869  Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
1870  if (!AliasVisited.insert(Cur).second)
1871  break;
1872  AliasStack.push_back(Cur);
1873  }
1874  for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
1875  emitGlobalAlias(M, *AncestorAlias);
1876  AliasStack.clear();
1877  }
1878  for (const auto &IFunc : M.ifuncs())
1879  emitGlobalIFunc(M, IFunc);
1880 
1881  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1882  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1883  for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1884  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
1885  MP->finishAssembly(M, *MI, *this);
1886 
1887  // Emit llvm.ident metadata in an '.ident' directive.
1888  emitModuleIdents(M);
1889 
1890  // Emit bytes for llvm.commandline metadata.
1891  emitModuleCommandLines(M);
1892 
1893  // Emit __morestack address if needed for indirect calls.
1894  if (MMI->usesMorestackAddr()) {
1895  Align Alignment(1);
1896  MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1898  /*C=*/nullptr, Alignment);
1899  OutStreamer->SwitchSection(ReadOnlySection);
1900 
1901  MCSymbol *AddrSymbol =
1902  OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
1903  OutStreamer->emitLabel(AddrSymbol);
1904 
1905  unsigned PtrSize = MAI->getCodePointerSize();
1906  OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("__morestack"),
1907  PtrSize);
1908  }
1909 
1910  // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
1911  // split-stack is used.
1913  OutStreamer->SwitchSection(
1914  OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
1915  if (MMI->hasNosplitStack())
1916  OutStreamer->SwitchSection(
1917  OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
1918  }
1919 
1920  // If we don't have any trampolines, then we don't require stack memory
1921  // to be executable. Some targets have a directive to declare this.
1922  Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1923  if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1925  OutStreamer->SwitchSection(S);
1926 
1927  if (TM.Options.EmitAddrsig) {
1928  // Emit address-significance attributes for all globals.
1929  OutStreamer->emitAddrsig();
1930  for (const GlobalValue &GV : M.global_values()) {
1931  if (!GV.use_empty() && !GV.isTransitiveUsedByMetadataOnly() &&
1932  !GV.isThreadLocal() && !GV.hasDLLImportStorageClass() &&
1933  !GV.getName().startswith("llvm.") && !GV.hasAtLeastLocalUnnamedAddr())
1934  OutStreamer->emitAddrsigSym(getSymbol(&GV));
1935  }
1936  }
1937 
1938  // Emit symbol partition specifications (ELF only).
1940  unsigned UniqueID = 0;
1941  for (const GlobalValue &GV : M.global_values()) {
1942  if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
1943  GV.getVisibility() != GlobalValue::DefaultVisibility)
1944  continue;
1945 
1946  OutStreamer->SwitchSection(
1947  OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0,
1948  "", false, ++UniqueID, nullptr));
1949  OutStreamer->emitBytes(GV.getPartition());
1950  OutStreamer->emitZeros(1);
1951  OutStreamer->emitValue(
1953  MAI->getCodePointerSize());
1954  }
1955  }
1956 
1957  // Allow the target to emit any magic that it wants at the end of the file,
1958  // after everything else has gone out.
1960 
1961  MMI = nullptr;
1962 
1963  OutStreamer->Finish();
1964  OutStreamer->reset();
1965  OwnedMLI.reset();
1966  OwnedMDT.reset();
1967 
1968  return false;
1969 }
1970 
1972  auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum());
1973  if (Res.second)
1974  Res.first->second = createTempSymbol("exception");
1975  return Res.first->second;
1976 }
1977 
1979  this->MF = &MF;
1980  const Function &F = MF.getFunction();
1981 
1982  // Get the function symbol.
1983  if (!MAI->needsFunctionDescriptors()) {
1985  } else {
1987  "Only AIX uses the function descriptor hooks.");
1988  // AIX is unique here in that the name of the symbol emitted for the
1989  // function body does not have the same name as the source function's
1990  // C-linkage name.
1991  assert(CurrentFnDescSym && "The function descriptor symbol needs to be"
1992  " initalized first.");
1993 
1994  // Get the function entry point symbol.
1996  }
1997 
1999  CurrentFnBegin = nullptr;
2000  CurrentSectionBeginSym = nullptr;
2001  MBBSectionRanges.clear();
2002  MBBSectionExceptionSyms.clear();
2003  bool NeedsLocalForSize = MAI->needsLocalForSize();
2004  if (F.hasFnAttribute("patchable-function-entry") ||
2005  F.hasFnAttribute("function-instrument") ||
2006  F.hasFnAttribute("xray-instruction-threshold") ||
2007  needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize ||
2009  CurrentFnBegin = createTempSymbol("func_begin");
2010  if (NeedsLocalForSize)
2012  }
2013 
2014  ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2015 }
2016 
2017 namespace {
2018 
2019 // Keep track the alignment, constpool entries per Section.
2020  struct SectionCPs {
2021  MCSection *S;
2022  Align Alignment;
2024 
2025  SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {}
2026  };
2027 
2028 } // end anonymous namespace
2029 
2030 /// EmitConstantPool - Print to the current output stream assembly
2031 /// representations of the constants in the constant pool MCP. This is
2032 /// used to print out constants which have been "spilled to memory" by
2033 /// the code generator.
2035  const MachineConstantPool *MCP = MF->getConstantPool();
2036  const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
2037  if (CP.empty()) return;
2038 
2039  // Calculate sections for constant pool entries. We collect entries to go into
2040  // the same section together to reduce amount of section switch statements.
2041  SmallVector<SectionCPs, 4> CPSections;
2042  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
2043  const MachineConstantPoolEntry &CPE = CP[i];
2044  Align Alignment = CPE.getAlign();
2045 
2046  SectionKind Kind = CPE.getSectionKind(&getDataLayout());
2047 
2048  const Constant *C = nullptr;
2049  if (!CPE.isMachineConstantPoolEntry())
2050  C = CPE.Val.ConstVal;
2051 
2053  getDataLayout(), Kind, C, Alignment);
2054 
2055  // The number of sections are small, just do a linear search from the
2056  // last section to the first.
2057  bool Found = false;
2058  unsigned SecIdx = CPSections.size();
2059  while (SecIdx != 0) {
2060  if (CPSections[--SecIdx].S == S) {
2061  Found = true;
2062  break;
2063  }
2064  }
2065  if (!Found) {
2066  SecIdx = CPSections.size();
2067  CPSections.push_back(SectionCPs(S, Alignment));
2068  }
2069 
2070  if (Alignment > CPSections[SecIdx].Alignment)
2071  CPSections[SecIdx].Alignment = Alignment;
2072  CPSections[SecIdx].CPEs.push_back(i);
2073  }
2074 
2075  // Now print stuff into the calculated sections.
2076  const MCSection *CurSection = nullptr;
2077  unsigned Offset = 0;
2078  for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
2079  for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
2080  unsigned CPI = CPSections[i].CPEs[j];
2081  MCSymbol *Sym = GetCPISymbol(CPI);
2082  if (!Sym->isUndefined())
2083  continue;
2084 
2085  if (CurSection != CPSections[i].S) {
2086  OutStreamer->SwitchSection(CPSections[i].S);
2087  emitAlignment(Align(CPSections[i].Alignment));
2088  CurSection = CPSections[i].S;
2089  Offset = 0;
2090  }
2091 
2092  MachineConstantPoolEntry CPE = CP[CPI];
2093 
2094  // Emit inter-object padding for alignment.
2095  unsigned NewOffset = alignTo(Offset, CPE.getAlign());
2096  OutStreamer->emitZeros(NewOffset - Offset);
2097 
2098  Offset = NewOffset + CPE.getSizeInBytes(getDataLayout());
2099 
2100  OutStreamer->emitLabel(Sym);
2101  if (CPE.isMachineConstantPoolEntry())
2103  else
2105  }
2106  }
2107 }
2108 
2109 // Print assembly representations of the jump tables used by the current
2110 // function.
2112  const DataLayout &DL = MF->getDataLayout();
2113  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2114  if (!MJTI) return;
2115  if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
2116  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2117  if (JT.empty()) return;
2118 
2119  // Pick the directive to use to print the jump table entries, and switch to
2120  // the appropriate section.
2121  const Function &F = MF->getFunction();
2123  bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
2125  F);
2126  if (JTInDiffSection) {
2127  // Drop it in the readonly section.
2128  MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
2129  OutStreamer->SwitchSection(ReadOnlySection);
2130  }
2131 
2133 
2134  // Jump tables in code sections are marked with a data_region directive
2135  // where that's supported.
2136  if (!JTInDiffSection)
2137  OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
2138 
2139  for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
2140  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2141 
2142  // If this jump table was deleted, ignore it.
2143  if (JTBBs.empty()) continue;
2144 
2145  // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
2146  /// emit a .set directive for each unique entry.
2150  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2152  for (const MachineBasicBlock *MBB : JTBBs) {
2153  if (!EmittedSets.insert(MBB).second)
2154  continue;
2155 
2156  // .set LJTSet, LBB32-base
2157  const MCExpr *LHS =
2159  OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
2161  OutContext));
2162  }
2163  }
2164 
2165  // On some targets (e.g. Darwin) we want to emit two consecutive labels
2166  // before each jump table. The first label is never referenced, but tells
2167  // the assembler and linker the extents of the jump table object. The
2168  // second label is actually referenced by the code.
2169  if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
2170  // FIXME: This doesn't have to have any specific name, just any randomly
2171  // named and numbered local label started with 'l' would work. Simplify
2172  // GetJTISymbol.
2173  OutStreamer->emitLabel(GetJTISymbol(JTI, true));
2174 
2175  MCSymbol* JTISymbol = GetJTISymbol(JTI);
2176  OutStreamer->emitLabel(JTISymbol);
2177 
2178  for (const MachineBasicBlock *MBB : JTBBs)
2179  emitJumpTableEntry(MJTI, MBB, JTI);
2180  }
2181  if (!JTInDiffSection)
2182  OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
2183 }
2184 
2185 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
2186 /// current stream.
2187 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI,
2188  const MachineBasicBlock *MBB,
2189  unsigned UID) const {
2190  assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
2191  const MCExpr *Value = nullptr;
2192  switch (MJTI->getEntryKind()) {
2194  llvm_unreachable("Cannot emit EK_Inline jump table entry");
2197  MJTI, MBB, UID, OutContext);
2198  break;
2200  // EK_BlockAddress - Each entry is a plain address of block, e.g.:
2201  // .word LBB123
2203  break;
2205  // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
2206  // with a relocation as gp-relative, e.g.:
2207  // .gprel32 LBB123
2208  MCSymbol *MBBSym = MBB->getSymbol();
2209  OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2210  return;
2211  }
2212 
2214  // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
2215  // with a relocation as gp-relative, e.g.:
2216  // .gpdword LBB123
2217  MCSymbol *MBBSym = MBB->getSymbol();
2218  OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
2219  return;
2220  }
2221 
2223  // Each entry is the address of the block minus the address of the jump
2224  // table. This is used for PIC jump tables where gprel32 is not supported.
2225  // e.g.:
2226  // .word LBB123 - LJTI1_2
2227  // If the .set directive avoids relocations, this is emitted as:
2228  // .set L4_5_set_123, LBB123 - LJTI1_2
2229  // .word L4_5_set_123
2232  OutContext);
2233  break;
2234  }
2236  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
2237  const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
2239  break;
2240  }
2241  }
2242 
2243  assert(Value && "Unknown entry kind!");
2244 
2245  unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
2246  OutStreamer->emitValue(Value, EntrySize);
2247 }
2248 
2249 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
2250 /// special global used by LLVM. If so, emit it and return true, otherwise
2251 /// do nothing and return false.
2253  if (GV->getName() == "llvm.used") {
2254  if (MAI->hasNoDeadStrip()) // No need to emit this at all.
2255  emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
2256  return true;
2257  }
2258 
2259  // Ignore debug and non-emitted data. This handles llvm.compiler.used.
2260  if (GV->getSection() == "llvm.metadata" ||
2262  return true;
2263 
2264  if (!GV->hasAppendingLinkage()) return false;
2265 
2266  assert(GV->hasInitializer() && "Not a special LLVM global!");
2267 
2268  if (GV->getName() == "llvm.global_ctors") {
2270  /* isCtor */ true);
2271 
2272  return true;
2273  }
2274 
2275  if (GV->getName() == "llvm.global_dtors") {
2277  /* isCtor */ false);
2278 
2279  return true;
2280  }
2281 
2282  report_fatal_error("unknown special variable");
2283 }
2284 
2285 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
2286 /// global in the specified llvm.used list.
2287 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) {
2288  // Should be an array of 'i8*'.
2289  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
2290  const GlobalValue *GV =
2291  dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
2292  if (GV)
2293  OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
2294  }
2295 }
2296 
2298  const Constant *List,
2299  SmallVector<Structor, 8> &Structors) {
2300  // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is
2301  // the init priority.
2302  if (!isa<ConstantArray>(List))
2303  return;
2304 
2305  // Gather the structors in a form that's convenient for sorting by priority.
2306  for (Value *O : cast<ConstantArray>(List)->operands()) {
2307  auto *CS = cast<ConstantStruct>(O);
2308  if (CS->getOperand(1)->isNullValue())
2309  break; // Found a null terminator, skip the rest.
2310  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
2311  if (!Priority)
2312  continue; // Malformed.
2313  Structors.push_back(Structor());
2314  Structor &S = Structors.back();
2315  S.Priority = Priority->getLimitedValue(65535);
2316  S.Func = CS->getOperand(1);
2317  if (!CS->getOperand(2)->isNullValue()) {
2318  if (TM.getTargetTriple().isOSAIX())
2320  "associated data of XXStructor list is not yet supported on AIX");
2321  S.ComdatKey =
2322  dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
2323  }
2324  }
2325 
2326  // Emit the function pointers in the target-specific order
2327  llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
2328  return L.Priority < R.Priority;
2329  });
2330 }
2331 
2332 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
2333 /// priority.
2335  bool IsCtor) {
2336  SmallVector<Structor, 8> Structors;
2337  preprocessXXStructorList(DL, List, Structors);
2338  if (Structors.empty())
2339  return;
2340 
2341  // Emit the structors in reverse order if we are using the .ctor/.dtor
2342  // initialization scheme.
2343  if (!TM.Options.UseInitArray)
2344  std::reverse(Structors.begin(), Structors.end());
2345 
2346  const Align Align = DL.getPointerPrefAlignment();
2347  for (Structor &S : Structors) {
2349  const MCSymbol *KeySym = nullptr;
2350  if (GlobalValue *GV = S.ComdatKey) {
2351  if (GV->isDeclarationForLinker())
2352  // If the associated variable is not defined in this module
2353  // (it might be available_externally, or have been an
2354  // available_externally definition that was dropped by the
2355  // EliminateAvailableExternally pass), some other TU
2356  // will provide its dynamic initializer.
2357  continue;
2358 
2359  KeySym = getSymbol(GV);
2360  }
2361 
2362  MCSection *OutputSection =
2363  (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
2364  : Obj.getStaticDtorSection(S.Priority, KeySym));
2365  OutStreamer->SwitchSection(OutputSection);
2366  if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
2368  emitXXStructor(DL, S.Func);
2369  }
2370 }
2371 
2372 void AsmPrinter::emitModuleIdents(Module &M) {
2373  if (!MAI->hasIdentDirective())
2374  return;
2375 
2376  if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
2377  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2378  const MDNode *N = NMD->getOperand(i);
2379  assert(N->getNumOperands() == 1 &&
2380  "llvm.ident metadata entry can have only one operand");
2381  const MDString *S = cast<MDString>(N->getOperand(0));
2382  OutStreamer->emitIdent(S->getString());
2383  }
2384  }
2385 }
2386 
2387 void AsmPrinter::emitModuleCommandLines(Module &M) {
2389  if (!CommandLine)
2390  return;
2391 
2392  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
2393  if (!NMD || !NMD->getNumOperands())
2394  return;
2395 
2396  OutStreamer->PushSection();
2397  OutStreamer->SwitchSection(CommandLine);
2398  OutStreamer->emitZeros(1);
2399  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2400  const MDNode *N = NMD->getOperand(i);
2401  assert(N->getNumOperands() == 1 &&
2402  "llvm.commandline metadata entry can have only one operand");
2403  const MDString *S = cast<MDString>(N->getOperand(0));
2404  OutStreamer->emitBytes(S->getString());
2405  OutStreamer->emitZeros(1);
2406  }
2407  OutStreamer->PopSection();
2408 }
2409 
2410 //===--------------------------------------------------------------------===//
2411 // Emission and print routines
2412 //
2413 
2414 /// Emit a byte directive and value.
2415 ///
2416 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); }
2417 
2418 /// Emit a short directive and value.
2419 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); }
2420 
2421 /// Emit a long directive and value.
2422 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); }
2423 
2424 /// Emit a long long directive and value.
2426  OutStreamer->emitInt64(Value);
2427 }
2428 
2429 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
2430 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
2431 /// .set if it avoids relocations.
2433  unsigned Size) const {
2434  OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
2435 }
2436 
2437 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
2438 /// where the size in bytes of the directive is specified by Size and Label
2439 /// specifies the label. This implicitly uses .set if it is available.
2441  unsigned Size,
2442  bool IsSectionRelative) const {
2443  if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
2444  OutStreamer->EmitCOFFSecRel32(Label, Offset);
2445  if (Size > 4)
2446  OutStreamer->emitZeros(Size - 4);
2447  return;
2448  }
2449 
2450  // Emit Label+Offset (or just Label if Offset is zero)
2451  const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
2452  if (Offset)
2453  Expr = MCBinaryExpr::createAdd(
2455 
2456  OutStreamer->emitValue(Expr, Size);
2457 }
2458 
2459 //===----------------------------------------------------------------------===//
2460 
2461 // EmitAlignment - Emit an alignment directive to the specified power of
2462 // two boundary. If a global value is specified, and if that global has
2463 // an explicit alignment requested, it will override the alignment request
2464 // if required for correctness.
2465 void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV) const {
2466  if (GV)
2467  Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment);
2468 
2469  if (Alignment == Align(1))
2470  return; // 1-byte aligned: no need to emit alignment.
2471 
2472  if (getCurrentSection()->getKind().isText()) {
2473  const MCSubtargetInfo *STI = nullptr;
2474  if (this->MF)
2475  STI = &getSubtargetInfo();
2476  else
2477  STI = TM.getMCSubtargetInfo();
2478  OutStreamer->emitCodeAlignment(Alignment.value(), STI);
2479  } else
2480  OutStreamer->emitValueToAlignment(Alignment.value());
2481 }
2482 
2483 //===----------------------------------------------------------------------===//
2484 // Constant emission.
2485 //===----------------------------------------------------------------------===//
2486 
2488  MCContext &Ctx = OutContext;
2489 
2490  if (CV->isNullValue() || isa<UndefValue>(CV))
2491  return MCConstantExpr::create(0, Ctx);
2492 
2493  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2494  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2495 
2496  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
2497  return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2498 
2499  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
2501 
2502  if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV))
2504 
2505  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2506  if (!CE) {
2507  llvm_unreachable("Unknown constant value to lower!");
2508  }
2509 
2510  switch (CE->getOpcode()) {
2511  case Instruction::AddrSpaceCast: {
2512  const Constant *Op = CE->getOperand(0);
2513  unsigned DstAS = CE->getType()->getPointerAddressSpace();
2514  unsigned SrcAS = Op->getType()->getPointerAddressSpace();
2515  if (TM.isNoopAddrSpaceCast(SrcAS, DstAS))
2516  return lowerConstant(Op);
2517 
2518  // Fallthrough to error.
2520  }
2521  default: {
2522  // If the code isn't optimized, there may be outstanding folding
2523  // opportunities. Attempt to fold the expression using DataLayout as a
2524  // last resort before giving up.
2526  if (C != CE)
2527  return lowerConstant(C);
2528 
2529  // Otherwise report the problem to the user.
2530  std::string S;
2531  raw_string_ostream OS(S);
2532  OS << "Unsupported expression in static initializer: ";
2533  CE->printAsOperand(OS, /*PrintType=*/false,
2534  !MF ? nullptr : MF->getFunction().getParent());
2535  report_fatal_error(Twine(OS.str()));
2536  }
2537  case Instruction::GetElementPtr: {
2538  // Generate a symbolic expression for the byte address
2539  APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
2540  cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
2541 
2542  const MCExpr *Base = lowerConstant(CE->getOperand(0));
2543  if (!OffsetAI)
2544  return Base;
2545 
2546  int64_t Offset = OffsetAI.getSExtValue();
2548  Ctx);
2549  }
2550 
2551  case Instruction::Trunc:
2552  // We emit the value and depend on the assembler to truncate the generated
2553  // expression properly. This is important for differences between
2554  // blockaddress labels. Since the two labels are in the same function, it
2555  // is reasonable to treat their delta as a 32-bit value.
2557  case Instruction::BitCast:
2558  return lowerConstant(CE->getOperand(0));
2559 
2560  case Instruction::IntToPtr: {
2561  const DataLayout &DL = getDataLayout();
2562 
2563  // Handle casts to pointers by changing them into casts to the appropriate
2564  // integer type. This promotes constant folding and simplifies this code.
2565  Constant *Op = CE->getOperand(0);
2566  Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2567  false/*ZExt*/);
2568  return lowerConstant(Op);
2569  }
2570 
2571  case Instruction::PtrToInt: {
2572  const DataLayout &DL = getDataLayout();
2573 
2574  // Support only foldable casts to/from pointers that can be eliminated by
2575  // changing the pointer to the appropriately sized integer type.
2576  Constant *Op = CE->getOperand(0);
2577  Type *Ty = CE->getType();
2578 
2579  const MCExpr *OpExpr = lowerConstant(Op);
2580 
2581  // We can emit the pointer value into this slot if the slot is an
2582  // integer slot equal to the size of the pointer.
2583  //
2584  // If the pointer is larger than the resultant integer, then
2585  // as with Trunc just depend on the assembler to truncate it.
2586  if (DL.getTypeAllocSize(Ty).getFixedSize() <=
2587  DL.getTypeAllocSize(Op->getType()).getFixedSize())
2588  return OpExpr;
2589 
2590  // Otherwise the pointer is smaller than the resultant integer, mask off
2591  // the high bits so we are sure to get a proper truncation if the input is
2592  // a constant expr.
2593  unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2594  const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2595  return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2596  }
2597 
2598  case Instruction::Sub: {
2599  GlobalValue *LHSGV;
2600  APInt LHSOffset;
2601  DSOLocalEquivalent *DSOEquiv;
2602  if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
2603  getDataLayout(), &DSOEquiv)) {
2604  GlobalValue *RHSGV;
2605  APInt RHSOffset;
2606  if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
2607  getDataLayout())) {
2608  const MCExpr *RelocExpr =
2609  getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
2610  if (!RelocExpr) {
2611  const MCExpr *LHSExpr =
2612  MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx);
2613  if (DSOEquiv &&
2614  getObjFileLowering().supportDSOLocalEquivalentLowering())
2615  LHSExpr =
2617  RelocExpr = MCBinaryExpr::createSub(
2618  LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
2619  }
2620  int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
2621  if (Addend != 0)
2622  RelocExpr = MCBinaryExpr::createAdd(
2623  RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
2624  return RelocExpr;
2625  }
2626  }
2627  }
2628  // else fallthrough
2630 
2631  // The MC library also has a right-shift operator, but it isn't consistently
2632  // signed or unsigned between different targets.
2633  case Instruction::Add:
2634  case Instruction::Mul:
2635  case Instruction::SDiv:
2636  case Instruction::SRem:
2637  case Instruction::Shl:
2638  case Instruction::And:
2639  case Instruction::Or:
2640  case Instruction::Xor: {
2641  const MCExpr *LHS = lowerConstant(CE->getOperand(0));
2642  const MCExpr *RHS = lowerConstant(CE->getOperand(1));
2643  switch (CE->getOpcode()) {
2644  default: llvm_unreachable("Unknown binary operator constant cast expr");
2645  case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2646  case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
2647  case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
2648  case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
2649  case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
2650  case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
2651  case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
2652  case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
2653  case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
2654  }
2655  }
2656  }
2657 }
2658 
2659 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
2660  AsmPrinter &AP,
2661  const Constant *BaseCV = nullptr,
2662  uint64_t Offset = 0);
2663 
2664 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
2665 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
2666 
2667 /// isRepeatedByteSequence - Determine whether the given value is
2668 /// composed of a repeated sequence of identical bytes and return the
2669 /// byte value. If it is not a repeated sequence, return -1.
2672  assert(!Data.empty() && "Empty aggregates should be CAZ node");
2673  char C = Data[0];
2674  for (unsigned i = 1, e = Data.size(); i != e; ++i)
2675  if (Data[i] != C) return -1;
2676  return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
2677 }
2678 
2679 /// isRepeatedByteSequence - Determine whether the given value is
2680 /// composed of a repeated sequence of identical bytes and return the
2681 /// byte value. If it is not a repeated sequence, return -1.
2682 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
2683  if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2684  uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
2685  assert(Size % 8 == 0);
2686 
2687  // Extend the element to take zero padding into account.
2688  APInt Value = CI->getValue().zextOrSelf(Size);
2689  if (!Value.isSplat(8))
2690  return -1;
2691 
2692  return Value.zextOrTrunc(8).getZExtValue();
2693  }
2694  if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
2695  // Make sure all array elements are sequences of the same repeated
2696  // byte.
2697  assert(CA->getNumOperands() != 0 && "Should be a CAZ");
2698  Constant *Op0 = CA->getOperand(0);
2699  int Byte = isRepeatedByteSequence(Op0, DL);
2700  if (Byte == -1)
2701  return -1;
2702 
2703  // All array elements must be equal.
2704  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
2705  if (CA->getOperand(i) != Op0)
2706  return -1;
2707  return Byte;
2708  }
2709 
2710  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
2711  return isRepeatedByteSequence(CDS);
2712 
2713  return -1;
2714 }
2715 
2717  const ConstantDataSequential *CDS,
2718  AsmPrinter &AP) {
2719  // See if we can aggregate this into a .fill, if so, emit it as such.
2720  int Value = isRepeatedByteSequence(CDS, DL);
2721  if (Value != -1) {
2722  uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
2723  // Don't emit a 1-byte object as a .fill.
2724  if (Bytes > 1)
2725  return AP.OutStreamer->emitFill(Bytes, Value);
2726  }
2727 
2728  // If this can be emitted with .ascii/.asciz, emit it as such.
2729  if (CDS->isString())
2730  return AP.OutStreamer->emitBytes(CDS->getAsString());
2731 
2732  // Otherwise, emit the values in successive locations.
2733  unsigned ElementByteSize = CDS->getElementByteSize();
2734  if (isa<IntegerType>(CDS->getElementType())) {
2735  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
2736  if (AP.isVerbose())
2737  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
2738  CDS->getElementAsInteger(i));
2739  AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i),
2740  ElementByteSize);
2741  }
2742  } else {
2743  Type *ET = CDS->getElementType();
2744  for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
2746  }
2747 
2748  unsigned Size = DL.getTypeAllocSize(CDS->getType());
2749  unsigned EmittedSize =
2750  DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements();
2751  assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
2752  if (unsigned Padding = Size - EmittedSize)
2753  AP.OutStreamer->emitZeros(Padding);
2754 }
2755 
2757  const ConstantArray *CA, AsmPrinter &AP,
2758  const Constant *BaseCV, uint64_t Offset) {
2759  // See if we can aggregate some values. Make sure it can be
2760  // represented as a series of bytes of the constant value.
2761  int Value = isRepeatedByteSequence(CA, DL);
2762 
2763  if (Value != -1) {
2764  uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
2765  AP.OutStreamer->emitFill(Bytes, Value);
2766  }
2767  else {
2768  for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
2769  emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
2770  Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
2771  }
2772  }
2773 }
2774 
2776  const ConstantVector *CV, AsmPrinter &AP) {
2777  for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
2779 
2780  unsigned Size = DL.getTypeAllocSize(CV->getType());
2781  unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
2782  CV->getType()->getNumElements();
2783  if (unsigned Padding = Size - EmittedSize)
2784  AP.OutStreamer->emitZeros(Padding);
2785 }
2786 
2788  const ConstantStruct *CS, AsmPrinter &AP,
2789  const Constant *BaseCV, uint64_t Offset) {
2790  // Print the fields in successive locations. Pad to align if needed!
2791  unsigned Size = DL.getTypeAllocSize(CS->getType());
2792  const StructLayout *Layout = DL.getStructLayout(CS->getType());
2793  uint64_t SizeSoFar = 0;
2794  for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
2795  const Constant *Field = CS->getOperand(i);
2796 
2797  // Print the actual field value.
2798  emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
2799 
2800  // Check if padding is needed and insert one or more 0s.
2801  uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
2802  uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
2803  - Layout->getElementOffset(i)) - FieldSize;
2804  SizeSoFar += FieldSize + PadSize;
2805 
2806  // Insert padding - this may include padding to increase the size of the
2807  // current field up to the ABI size (if the struct is not packed) as well
2808  // as padding to ensure that the next field starts at the right offset.
2809  AP.OutStreamer->emitZeros(PadSize);
2810  }
2811  assert(SizeSoFar == Layout->getSizeInBytes() &&
2812  "Layout of constant struct may be incorrect!");
2813 }
2814 
2815 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
2816  assert(ET && "Unknown float type");
2817  APInt API = APF.bitcastToAPInt();
2818 
2819  // First print a comment with what we think the original floating-point value
2820  // should have been.
2821  if (AP.isVerbose()) {
2823  APF.toString(StrVal);
2824  ET->print(AP.OutStreamer->GetCommentOS());
2825  AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
2826  }
2827 
2828  // Now iterate through the APInt chunks, emitting them in endian-correct
2829  // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
2830  // floats).
2831  unsigned NumBytes = API.getBitWidth() / 8;
2832  unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
2833  const uint64_t *p = API.getRawData();
2834 
2835  // PPC's long double has odd notions of endianness compared to how LLVM
2836  // handles it: p[0] goes first for *big* endian on PPC.
2837  if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
2838  int Chunk = API.getNumWords() - 1;
2839 
2840  if (TrailingBytes)
2841  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes);
2842 
2843  for (; Chunk >= 0; --Chunk)
2844  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2845  } else {
2846  unsigned Chunk;
2847  for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
2848  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t));
2849 
2850  if (TrailingBytes)
2851  AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes);
2852  }
2853 
2854  // Emit the tail padding for the long double.
2855  const DataLayout &DL = AP.getDataLayout();
2856  AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
2857 }
2858 
2859 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
2860  emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
2861 }
2862 
2864  const DataLayout &DL = AP.getDataLayout();
2865  unsigned BitWidth = CI->getBitWidth();
2866 
2867  // Copy the value as we may massage the layout for constants whose bit width
2868  // is not a multiple of 64-bits.
2869  APInt Realigned(CI->getValue());
2870  uint64_t ExtraBits = 0;
2871  unsigned ExtraBitsSize = BitWidth & 63;
2872 
2873  if (ExtraBitsSize) {
2874  // The bit width of the data is not a multiple of 64-bits.
2875  // The extra bits are expected to be at the end of the chunk of the memory.
2876  // Little endian:
2877  // * Nothing to be done, just record the extra bits to emit.
2878  // Big endian:
2879  // * Record the extra bits to emit.
2880  // * Realign the raw data to emit the chunks of 64-bits.
2881  if (DL.isBigEndian()) {
2882  // Basically the structure of the raw data is a chunk of 64-bits cells:
2883  // 0 1 BitWidth / 64
2884  // [chunk1][chunk2] ... [chunkN].
2885  // The most significant chunk is chunkN and it should be emitted first.
2886  // However, due to the alignment issue chunkN contains useless bits.
2887  // Realign the chunks so that they contain only useful information:
2888  // ExtraBits 0 1 (BitWidth / 64) - 1
2889  // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2890  ExtraBitsSize = alignTo(ExtraBitsSize, 8);
2891  ExtraBits = Realigned.getRawData()[0] &
2892  (((uint64_t)-1) >> (64 - ExtraBitsSize));
2893  Realigned.lshrInPlace(ExtraBitsSize);
2894  } else
2895  ExtraBits = Realigned.getRawData()[BitWidth / 64];
2896  }
2897 
2898  // We don't expect assemblers to support integer data directives
2899  // for more than 64 bits, so we emit the data in at most 64-bit
2900  // quantities at a time.
2901  const uint64_t *RawData = Realigned.getRawData();
2902  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2903  uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
2904  AP.OutStreamer->emitIntValue(Val, 8);
2905  }
2906 
2907  if (ExtraBitsSize) {
2908  // Emit the extra bits after the 64-bits chunks.
2909 
2910  // Emit a directive that fills the expected size.
2912  Size -= (BitWidth / 64) * 8;
2913  assert(Size && Size * 8 >= ExtraBitsSize &&
2914  (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2915  == ExtraBits && "Directive too small for extra bits.");
2916  AP.OutStreamer->emitIntValue(ExtraBits, Size);
2917  }
2918 }
2919 
2920 /// Transform a not absolute MCExpr containing a reference to a GOT
2921 /// equivalent global, by a target specific GOT pc relative access to the
2922 /// final symbol.
2923 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
2924  const Constant *BaseCst,
2925  uint64_t Offset) {
2926  // The global @foo below illustrates a global that uses a got equivalent.
2927  //
2928  // @bar = global i32 42
2929  // @gotequiv = private unnamed_addr constant i32* @bar
2930  // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
2931  // i64 ptrtoint (i32* @foo to i64))
2932  // to i32)
2933  //
2934  // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
2935  // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
2936  // form:
2937  //
2938  // foo = cstexpr, where
2939  // cstexpr := <gotequiv> - "." + <cst>
2940  // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
2941  //
2942  // After canonicalization by evaluateAsRelocatable `ME` turns into:
2943  //
2944  // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
2945  // gotpcrelcst := <offset from @foo base> + <cst>
2946  MCValue MV;
2947  if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
2948  return;
2949  const MCSymbolRefExpr *SymA = MV.getSymA();
2950  if (!SymA)
2951  return;
2952 
2953  // Check that GOT equivalent symbol is cached.
2954  const MCSymbol *GOTEquivSym = &SymA->getSymbol();
2955  if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
2956  return;
2957 
2958  const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
2959  if (!BaseGV)
2960  return;
2961 
2962  // Check for a valid base symbol
2963  const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
2964  const MCSymbolRefExpr *SymB = MV.getSymB();
2965 
2966  if (!SymB || BaseSym != &SymB->getSymbol())
2967  return;
2968 
2969  // Make sure to match:
2970  //
2971  // gotpcrelcst := <offset from @foo base> + <cst>
2972  //
2973  // If gotpcrelcst is positive it means that we can safely fold the pc rel
2974  // displacement into the GOTPCREL. We can also can have an extra offset <cst>
2975  // if the target knows how to encode it.
2976  int64_t GOTPCRelCst = Offset + MV.getConstant();
2977  if (GOTPCRelCst < 0)
2978  return;
2979  if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
2980  return;
2981 
2982  // Emit the GOT PC relative to replace the got equivalent global, i.e.:
2983  //
2984  // bar:
2985  // .long 42
2986  // gotequiv:
2987  // .quad bar
2988  // foo:
2989  // .long gotequiv - "." + <cst>
2990  //
2991  // is replaced by the target specific equivalent to:
2992  //
2993  // bar:
2994  // .long 42
2995  // foo:
2996  // .long bar@GOTPCREL+<gotpcrelcst>
2997  AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
2998  const GlobalVariable *GV = Result.first;
2999  int NumUses = (int)Result.second;
3000  const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
3001  const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
3003  FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
3004 
3005  // Update GOT equivalent usage information
3006  --NumUses;
3007  if (NumUses >= 0)
3008  AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
3009 }
3010 
3011 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
3012  AsmPrinter &AP, const Constant *BaseCV,
3013  uint64_t Offset) {
3014  uint64_t Size = DL.getTypeAllocSize(CV->getType());
3015 
3016  // Globals with sub-elements such as combinations of arrays and structs
3017  // are handled recursively by emitGlobalConstantImpl. Keep track of the
3018  // constant symbol base and the current position with BaseCV and Offset.
3019  if (!BaseCV && CV->hasOneUse())
3020  BaseCV = dyn_cast<Constant>(CV->user_back());
3021 
3022  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
3023  return AP.OutStreamer->emitZeros(Size);
3024 
3025  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
3026  const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType());
3027 
3028  if (StoreSize <= 8) {
3029  if (AP.isVerbose())
3030  AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
3031  CI->getZExtValue());
3032  AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize);
3033  } else {
3035  }
3036 
3037  // Emit tail padding if needed
3038  if (Size != StoreSize)
3039  AP.OutStreamer->emitZeros(Size - StoreSize);
3040 
3041  return;
3042  }
3043 
3044  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
3045  return emitGlobalConstantFP(CFP, AP);
3046 
3047  if (isa<ConstantPointerNull>(CV)) {
3048  AP.OutStreamer->emitIntValue(0, Size);
3049  return;
3050  }
3051 
3052  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
3053  return emitGlobalConstantDataSequential(DL, CDS, AP);
3054 
3055  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
3056  return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
3057 
3058  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
3059  return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
3060 
3061  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
3062  // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
3063  // vectors).
3064  if (CE->getOpcode() == Instruction::BitCast)
3065  return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
3066 
3067  if (Size > 8) {
3068  // If the constant expression's size is greater than 64-bits, then we have
3069  // to emit the value in chunks. Try to constant fold the value and emit it
3070  // that way.
3071  Constant *New = ConstantFoldConstant(CE, DL);
3072  if (New != CE)
3073  return emitGlobalConstantImpl(DL, New, AP);
3074  }
3075  }
3076 
3077  if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
3078  return emitGlobalConstantVector(DL, V, AP);
3079 
3080  // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
3081  // thread the streamer with EmitValue.
3082  const MCExpr *ME = AP.lowerConstant(CV);
3083 
3084  // Since lowerConstant already folded and got rid of all IR pointer and
3085  // integer casts, detect GOT equivalent accesses by looking into the MCExpr
3086  // directly.
3088  handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
3089 
3090  AP.OutStreamer->emitValue(ME, Size);
3091 }
3092 
3093 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
3095  uint64_t Size = DL.getTypeAllocSize(CV->getType());
3096  if (Size)
3097  emitGlobalConstantImpl(DL, CV, *this);
3098  else if (MAI->hasSubsectionsViaSymbols()) {
3099  // If the global has zero size, emit a single byte so that two labels don't
3100  // look like they are at the same location.
3101  OutStreamer->emitIntValue(0, 1);
3102  }
3103 }
3104 
3106  // Target doesn't support this yet!
3107  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
3108 }
3109 
3110 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
3111  if (Offset > 0)
3112  OS << '+' << Offset;
3113  else if (Offset < 0)
3114  OS << Offset;
3115 }
3116 
3117 void AsmPrinter::emitNops(unsigned N) {
3119  for (; N; --N)
3121 }
3122 
3123 //===----------------------------------------------------------------------===//
3124 // Symbol Lowering Routines.
3125 //===----------------------------------------------------------------------===//
3126 
3128  return OutContext.createTempSymbol(Name, true);
3129 }
3130 
3132  return MMI->getAddrLabelSymbol(BA->getBasicBlock());
3133 }
3134 
3136  return MMI->getAddrLabelSymbol(BB);
3137 }
3138 
3139 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
3140 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
3141  if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
3142  const MachineConstantPoolEntry &CPE =
3143  MF->getConstantPool()->getConstants()[CPID];
3144  if (!CPE.isMachineConstantPoolEntry()) {
3145  const DataLayout &DL = MF->getDataLayout();
3146  SectionKind Kind = CPE.getSectionKind(&DL);
3147  const Constant *C = CPE.Val.ConstVal;
3148  Align Alignment = CPE.Alignment;
3149  if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
3150  getObjFileLowering().getSectionForConstant(DL, Kind, C,
3151  Alignment))) {
3152  if (MCSymbol *Sym = S->getCOMDATSymbol()) {
3153  if (Sym->isUndefined())
3154  OutStreamer->emitSymbolAttribute(Sym, MCSA_Global);
3155  return Sym;
3156  }
3157  }
3158  }
3159  }
3160 
3161  const DataLayout &DL = getDataLayout();
3162  return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3163  "CPI" + Twine(getFunctionNumber()) + "_" +
3164  Twine(CPID));
3165 }
3166 
3167 /// GetJTISymbol - Return the symbol for the specified jump table entry.
3168 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
3169  return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
3170 }
3171 
3172 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
3173 /// FIXME: privatize to AsmPrinter.
3174 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
3175  const DataLayout &DL = getDataLayout();
3176  return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
3177  Twine(getFunctionNumber()) + "_" +
3178  Twine(UID) + "_set_" + Twine(MBBID));
3179 }
3180 
3182  StringRef Suffix) const {
3183  return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
3184 }
3185 
3186 /// Return the MCSymbol for the specified ExternalSymbol.
3188  SmallString<60> NameStr;
3189  Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
3190  return OutContext.getOrCreateSymbol(NameStr);
3191 }
3192 
3193 /// PrintParentLoopComment - Print comments about parent loops of this one.
3195  unsigned FunctionNumber) {
3196  if (!Loop) return;
3197  PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
3198  OS.indent(Loop->getLoopDepth()*2)
3199  << "Parent Loop BB" << FunctionNumber << "_"
3200  << Loop->getHeader()->getNumber()
3201  << " Depth=" << Loop->getLoopDepth() << '\n';
3202 }
3203 
3204 /// PrintChildLoopComment - Print comments about child loops within
3205 /// the loop for this basic block, with nesting.
3207  unsigned FunctionNumber) {
3208  // Add child loop information
3209  for (const MachineLoop *CL : *Loop) {
3210  OS.indent(CL->getLoopDepth()*2)
3211  << "Child Loop BB" << FunctionNumber << "_"
3212  << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
3213  << '\n';
3214  PrintChildLoopComment(OS, CL, FunctionNumber);
3215  }
3216 }
3217 
3218 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
3220  const MachineLoopInfo *LI,
3221  const AsmPrinter &AP) {
3222  // Add loop depth information
3223  const MachineLoop *Loop = LI->getLoopFor(&MBB);
3224  if (!Loop) return;
3225 
3226  MachineBasicBlock *Header = Loop->getHeader();
3227  assert(Header && "No header for loop");
3228 
3229  // If this block is not a loop header, just print out what is the loop header
3230  // and return.
3231  if (Header != &MBB) {
3232  AP.OutStreamer->AddComment(" in Loop: Header=BB" +
3233  Twine(AP.getFunctionNumber())+"_" +
3234  Twine(Loop->getHeader()->getNumber())+
3235  " Depth="+Twine(Loop->getLoopDepth()));
3236  return;
3237  }
3238 
3239  // Otherwise, it is a loop header. Print out information about child and
3240  // parent loops.
3241  raw_ostream &OS = AP.OutStreamer->GetCommentOS();
3242 
3244 
3245  OS << "=>";
3246  OS.indent(Loop->getLoopDepth()*2-2);
3247 
3248  OS << "This ";
3249  if (Loop->isInnermost())
3250  OS << "Inner ";
3251  OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
3252 
3254 }
3255 
3256 /// emitBasicBlockStart - This method prints the label for the specified
3257 /// MachineBasicBlock, an alignment (if present) and a comment describing
3258 /// it if appropriate.
3260  // End the previous funclet and start a new one.
3261  if (MBB.isEHFuncletEntry()) {
3262  for (const HandlerInfo &HI : Handlers) {
3263  HI.Handler->endFunclet();
3264  HI.Handler->beginFunclet(MBB);
3265  }
3266  }
3267 
3268  // Emit an alignment directive for this block, if needed.
3269  const Align Alignment = MBB.getAlignment();
3270  if (Alignment != Align(1))
3271  emitAlignment(Alignment);
3272 
3273  // Switch to a new section if this basic block must begin a section. The
3274  // entry block is always placed in the function section and is handled
3275  // separately.
3276  if (MBB.isBeginSection() && !MBB.isEntryBlock()) {
3277  OutStreamer->SwitchSection(
3278  getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(),
3279  MBB, TM));
3280  CurrentSectionBeginSym = MBB.getSymbol();
3281  }
3282 
3283  // If the block has its address taken, emit any labels that were used to
3284  // reference the block. It is possible that there is more than one label
3285  // here, because multiple LLVM BB's may have been RAUW'd to this block after
3286  // the references were generated.
3287  const BasicBlock *BB = MBB.getBasicBlock();
3288  if (MBB.hasAddressTaken()) {
3289  if (isVerbose())
3290  OutStreamer->AddComment("Block address taken");
3291 
3292  // MBBs can have their address taken as part of CodeGen without having
3293  // their corresponding BB's address taken in IR
3294  if (BB && BB->hasAddressTaken())
3295  for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
3296  OutStreamer->emitLabel(Sym);
3297  }
3298 
3299  // Print some verbose block comments.
3300  if (isVerbose()) {
3301  if (BB) {
3302  if (BB->hasName()) {
3303  BB->printAsOperand(OutStreamer->GetCommentOS(),
3304  /*PrintType=*/false, BB->getModule());
3305  OutStreamer->GetCommentOS() << '\n';
3306  }
3307  }
3308 
3309  assert(MLI != nullptr && "MachineLoopInfo should has been computed");
3311  }
3312 
3313  // Print the main label for the block.
3314  if (shouldEmitLabelForBasicBlock(MBB)) {
3315  if (isVerbose() && MBB.hasLabelMustBeEmitted())
3316  OutStreamer->AddComment("Label of block must be emitted");
3317  OutStreamer->emitLabel(MBB.getSymbol());
3318  } else {
3319  if (isVerbose()) {
3320  // NOTE: Want this comment at start of line, don't emit with AddComment.
3321  OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
3322  false);
3323  }
3324  }
3325 
3326  if (MBB.isEHCatchretTarget() &&
3328  OutStreamer->emitLabel(MBB.getEHCatchretSymbol());
3329  }
3330 
3331  // With BB sections, each basic block must handle CFI information on its own
3332  // if it begins a section (Entry block is handled separately by
3333  // AsmPrinterHandler::beginFunction).
3334  if (MBB.isBeginSection() && !MBB.isEntryBlock())
3335  for (const HandlerInfo &HI : Handlers)
3336  HI.Handler->beginBasicBlock(MBB);
3337 }
3338 
3340  // Check if CFI information needs to be updated for this MBB with basic block
3341  // sections.
3342  if (MBB.isEndSection())
3343  for (const HandlerInfo &HI : Handlers)
3344  HI.Handler->endBasicBlock(MBB);
3345 }
3346 
3347 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility,
3348  bool IsDefinition) const {
3349  MCSymbolAttr Attr = MCSA_Invalid;
3350 
3351  switch (Visibility) {
3352  default: break;
3354  if (IsDefinition)
3355  Attr = MAI->getHiddenVisibilityAttr();
3356  else
3358  break;
3360  Attr = MAI->getProtectedVisibilityAttr();
3361  break;
3362  }
3363 
3364  if (Attr != MCSA_Invalid)
3365  OutStreamer->emitSymbolAttribute(Sym, Attr);
3366 }
3367 
3368 bool AsmPrinter::shouldEmitLabelForBasicBlock(
3369  const MachineBasicBlock &MBB) const {
3370  // With `-fbasic-block-sections=`, a label is needed for every non-entry block
3371  // in the labels mode (option `=labels`) and every section beginning in the
3372  // sections mode (`=all` and `=list=`).
3373  if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock())
3374  return true;
3375  // A label is needed for any block with at least one predecessor (when that
3376  // predecessor is not the fallthrough predecessor, or if it is an EH funclet
3377  // entry, or if a label is forced).
3378  return !MBB.pred_empty() &&
3381 }
3382 
3383 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
3384 /// exactly one predecessor and the control transfer mechanism between
3385 /// the predecessor and this block is a fall-through.
3386 bool AsmPrinter::
3388  // If this is a landing pad, it isn't a fall through. If it has no preds,
3389  // then nothing falls through to it.
3390  if (MBB->isEHPad() || MBB->pred_empty())
3391  return false;
3392 
3393  // If there isn't exactly one predecessor, it can't be a fall through.
3394  if (MBB->pred_size() > 1)
3395  return false;
3396 
3397  // The predecessor has to be immediately before this block.
3398  MachineBasicBlock *Pred = *MBB->pred_begin();
3399  if (!Pred->isLayoutSuccessor(MBB))
3400  return false;
3401 
3402  // If the block is completely empty, then it definitely does fall through.
3403  if (Pred->empty())
3404  return true;
3405 
3406  // Check the terminators in the previous blocks
3407  for (const auto &MI : Pred->terminators()) {
3408  // If it is not a simple branch, we are in a table somewhere.
3409  if (!MI.isBranch() || MI.isIndirectBranch())
3410  return false;
3411 
3412  // If we are the operands of one of the branches, this is not a fall
3413  // through. Note that targets with delay slots will usually bundle
3414  // terminators with the delay slot instruction.
3415  for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
3416  if (OP->isJTI())
3417  return false;
3418  if (OP->isMBB() && OP->getMBB() == MBB)
3419  return false;
3420  }
3421  }
3422 
3423  return true;
3424 }
3425 
3426 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
3427  if (!S.usesMetadata())
3428  return nullptr;
3429 
3430  gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
3431  gcp_map_type::iterator GCPI = GCMap.find(&S);
3432  if (GCPI != GCMap.end())
3433  return GCPI->second.get();
3434 
3435  auto Name = S.getName();
3436 
3437  for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter :
3439  if (Name == GCMetaPrinter.getName()) {
3440  std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate();
3441  GMP->S = &S;
3442  auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
3443  return IterBool.first->second.get();
3444  }
3445 
3446  report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
3447 }
3448 
3450  GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
3451  assert(MI && "AsmPrinter didn't require GCModuleInfo?");
3452  bool NeedsDefault = false;
3453  if (MI->begin() == MI->end())
3454  // No GC strategy, use the default format.
3455  NeedsDefault = true;
3456  else
3457  for (auto &I : *MI) {
3458  if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
3459  if (MP->emitStackMaps(SM, *this))
3460  continue;
3461  // The strategy doesn't have printer or doesn't emit custom stack maps.
3462  // Use the default format.
3463  NeedsDefault = true;
3464  }
3465 
3466  if (NeedsDefault)
3468 }
3469 
3470 /// Pin vtable to this file.
3472 
3474 
3475 // In the binary's "xray_instr_map" section, an array of these function entries
3476 // describes each instrumentation point. When XRay patches your code, the index
3477 // into this table will be given to your handler as a patch point identifier.
3479  auto Kind8 = static_cast<uint8_t>(Kind);
3480  Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
3481  Out->emitBinaryData(
3482  StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
3483  Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
3484  auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
3485  assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
3486  Out->emitZeros(Padding);
3487 }
3488 
3490  if (Sleds.empty())
3491  return;
3492 
3493  auto PrevSection = OutStreamer->getCurrentSectionOnly();
3494  const Function &F = MF->getFunction();
3495  MCSection *InstMap = nullptr;
3496  MCSection *FnSledIndex = nullptr;
3497  const Triple &TT = TM.getTargetTriple();
3498  // Use PC-relative addresses on all targets.
3499  if (TT.isOSBinFormatELF()) {
3500  auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3501  auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
3502  StringRef GroupName;
3503  if (F.hasComdat()) {
3504  Flags |= ELF::SHF_GROUP;
3505  GroupName = F.getComdat()->getName();
3506  }
3507  InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS,
3508  Flags, 0, GroupName, F.hasComdat(),
3509  MCSection::NonUniqueID, LinkedToSym);
3510 
3512  FnSledIndex = OutContext.getELFSection(
3513  "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0,
3514  GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym);
3515  } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
3516  InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
3519  FnSledIndex = OutContext.getMachOSection(
3520  "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel());
3521  } else {
3522  llvm_unreachable("Unsupported target");
3523  }
3524 
3525  auto WordSizeBytes = MAI->getCodePointerSize();
3526 
3527  // Now we switch to the instrumentation map section. Because this is done
3528  // per-function, we are able to create an index entry that will represent the
3529  // range of sleds associated with a function.
3530  auto &Ctx = OutContext;
3531  MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
3532  OutStreamer->SwitchSection(InstMap);
3533  OutStreamer->emitLabel(SledsStart);
3534  for (const auto &Sled : Sleds) {
3535  MCSymbol *Dot = Ctx.createTempSymbol();
3536  OutStreamer->emitLabel(Dot);
3537  OutStreamer->emitValueImpl(
3539  MCSymbolRefExpr::create(Dot, Ctx), Ctx),
3540  WordSizeBytes);
3541  OutStreamer->emitValueImpl(
3545  MCConstantExpr::create(WordSizeBytes, Ctx),
3546  Ctx),
3547  Ctx),
3548  WordSizeBytes);
3549  Sled.emit(WordSizeBytes, OutStreamer.get());
3550  }
3551  MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
3552  OutStreamer->emitLabel(SledsEnd);
3553 
3554  // We then emit a single entry in the index per function. We use the symbols
3555  // that bound the instrumentation map as the range for a specific function.
3556  // Each entry here will be 2 * word size aligned, as we're writing down two
3557  // pointers. This should work for both 32-bit and 64-bit platforms.
3558  if (FnSledIndex) {
3559  OutStreamer->SwitchSection(FnSledIndex);
3560  OutStreamer->emitCodeAlignment(2 * WordSizeBytes, &getSubtargetInfo());
3561  OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false);
3562  OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false);
3563  OutStreamer->SwitchSection(PrevSection);
3564  }
3565  Sleds.clear();
3566 }
3567 
3569  SledKind Kind, uint8_t Version) {
3570  const Function &F = MI.getMF()->getFunction();
3571  auto Attr = F.getFnAttribute("function-instrument");
3572  bool LogArgs = F.hasFnAttribute("xray-log-args");
3573  bool AlwaysInstrument =
3574  Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
3575  if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
3576  Kind = SledKind::LOG_ARGS_ENTER;
3577  Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
3578  AlwaysInstrument, &F, Version});
3579 }
3580 
3582  const Function &F = MF->getFunction();
3583  unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0;
3584  (void)F.getFnAttribute("patchable-function-prefix")
3585  .getValueAsString()
3586  .getAsInteger(10, PatchableFunctionPrefix);
3587  (void)F.getFnAttribute("patchable-function-entry")
3588  .getValueAsString()
3589  .getAsInteger(10, PatchableFunctionEntry);
3590  if (!PatchableFunctionPrefix && !PatchableFunctionEntry)
3591  return;
3592  const unsigned PointerSize = getPointerSize();
3594  auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC;
3595  const MCSymbolELF *LinkedToSym = nullptr;
3596  StringRef GroupName;
3597 
3598  // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not
3599  // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections.
3600  if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) {
3601  Flags |= ELF::SHF_LINK_ORDER;
3602  if (F.hasComdat()) {
3603  Flags |= ELF::SHF_GROUP;
3604  GroupName = F.getComdat()->getName();
3605  }
3606  LinkedToSym = cast<MCSymbolELF>(CurrentFnSym);
3607  }
3608  OutStreamer->SwitchSection(OutContext.getELFSection(
3609  "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName,
3610  F.hasComdat(), MCSection::NonUniqueID, LinkedToSym));
3613  }
3614 }
3615 
3617  return OutStreamer->getContext().getDwarfVersion();
3618 }
3619 
3621  OutStreamer->getContext().setDwarfVersion(Version);
3622 }
3623 
3625  return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64;
3626 }
3627 
3630  OutStreamer->getContext().getDwarfFormat());
3631 }
3632 
3635  OutStreamer->getContext().getDwarfFormat());
3636 }
llvm::SectionKind::isCommon
bool isCommon() const
Definition: SectionKind.h:167
llvm::Check::Size
@ Size
Definition: FileCheck.h:73
isGOTEquivalentCandidate
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...
Definition: AsmPrinter.cpp:1546
llvm::ELF::SHF_GROUP
@ SHF_GROUP
Definition: ELF.h:1016
i
i
Definition: README.txt:29
llvm::HexagonInstrInfo::isTailCall
bool isTailCall(const MachineInstr &MI) const override
Definition: HexagonInstrInfo.cpp:2608
llvm::MCAsmInfo::hasSingleParameterDotFile
bool hasSingleParameterDotFile() const
Definition: MCAsmInfo.h:735
llvm::TargetOptions::EmitStackSizeSection
unsigned EmitStackSizeSection
Emit section containing metadata on function stack sizes.
Definition: TargetOptions.h:294
llvm::lltok::APFloat
@ APFloat
Definition: LLToken.h:495
llvm::alignTo
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:148
AsmPrinter.h
llvm::TargetOptions::StackUsageOutput
std::string StackUsageOutput
Name of the stack usage file (i.e., .su file) if user passes -fstack-usage.
Definition: TargetOptions.h:348
llvm::TargetLoweringObjectFile::getStaticDtorSection
virtual MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const
Definition: TargetLoweringObjectFile.h:180
llvm::MachineFrameInfo::hasVarSizedObjects
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
Definition: MachineFrameInfo.h:353
llvm::AsmPrinter::emitLabelDifference
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...
Definition: AsmPrinter.cpp:2432
DWARFGroupName
const char DWARFGroupName[]
Definition: AsmPrinter.cpp:143
llvm::MCContext::getObjectFileInfo
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:427
llvm::AsmPrinter::isPositionIndependent
bool isPositionIndependent() const
Definition: AsmPrinter.cpp:214
MachineModuleInfoImpls.h
llvm::AsmPrinter::NumUserHandlers
size_t NumUserHandlers
Definition: AsmPrinter.h:195
llvm::Type::isSized
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:263
llvm::MCBinaryExpr::createDiv
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:535
llvm::AsmPrinter::emitLabelDifferenceAsULEB128
void emitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const
Emit something like ".uleb128 Hi-Lo".
Definition: AsmPrinterDwarf.cpp:56
llvm::SectionKind::isThreadLocal
bool isThreadLocal() const
Definition: SectionKind.h:151
llvm::MachineOptimizationRemarkEmitter::allowExtraAnalysis
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to be more informative.
Definition: MachineOptimizationRemarkEmitter.h:166
llvm::SectionKind::getReadOnlyWithRel
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:207
llvm::MachineBasicBlock::pred_begin
pred_iterator pred_begin()
Definition: MachineBasicBlock.h:316
MCDwarf.h
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:105
llvm::AArch64CC::HI
@ HI
Definition: AArch64BaseInfo.h:263
MachineInstr.h
llvm::MachineOperand::MO_Immediate
@ MO_Immediate
Immediate operand.
Definition: MachineOperand.h:53
MathExtras.h
llvm::AsmPrinter::GlobalGOTEquivs
MapVector< const MCSymbol *, GOTEquivUsePair > GlobalGOTEquivs
Definition: AsmPrinter.h:140
GlobalIFunc.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
Reg
unsigned Reg
Definition: MachineSink.cpp:1558
llvm::ConstantDataSequential::getElementByteSize
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2940
llvm::AsmPrinter::printOffset
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
Definition: AsmPrinter.cpp:3110
GCMetadata.h
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
Comdat.h
llvm::NamedMDNode
A tuple of MDNodes.
Definition: Metadata.h:1421
llvm::MCAsmInfo::doesSetDirectiveSuppressReloc
bool doesSetDirectiveSuppressReloc() const
Definition: MCAsmInfo.h:713
llvm::AsmPrinter::CFISection
CFISection
Definition: AsmPrinter.h:160
TargetFrameLowering.h
llvm::GlobalValue::hasCommonLinkage
bool hasCommonLinkage() const
Definition: GlobalValue.h:455
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:113
llvm::MachineLoopInfo::getLoopFor
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
Definition: MachineLoopInfo.h:127
llvm::AsmPrinter::emitXXStructor
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:515
llvm::AsmPrinter::emitBasicBlockEnd
virtual void emitBasicBlockEnd(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the end of a basic block.
Definition: AsmPrinter.cpp:3339
FileSystem.h
llvm::remarks::RemarkStreamer
Definition: RemarkStreamer.h:42
llvm::TargetMachine::useEmulatedTLS
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
Definition: TargetMachine.cpp:152
MCTargetOptions.h
llvm::TargetFrameLowering
Information about stack frame layout on the target.
Definition: TargetFrameLowering.h:43
llvm::Value::hasOneUse
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
llvm::WebAssembly::Nop
static const unsigned Nop
Instruction opcodes emitted via means other than CodeGen.
Definition: WebAssemblyMCTargetDesc.h:136
llvm::MachineBasicBlock::getBasicBlock
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
Definition: MachineBasicBlock.h:202
llvm::MCObjectFileInfo::getCommDirectiveSupportsAlignment
bool getCommDirectiveSupportsAlignment() const
Definition: MCObjectFileInfo.h:247
llvm::GlobalValue::LinkOnceAnyLinkage
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
PseudoProbePrinter.h
Metadata.h
llvm::NamedMDNode::getNumOperands
unsigned getNumOperands() const
Definition: Metadata.cpp:1120
llvm::AsmPrinter::lowerConstant
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
Definition: AsmPrinter.cpp:2487
llvm::GCStrategy
GCStrategy describes a garbage collector algorithm's code generation requirements,...
Definition: GCStrategy.h:66
llvm::ConstantInt::getType
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:173
llvm::GlobalValue::hasExternalLinkage
bool hasExternalLinkage() const
Definition: GlobalValue.h:434
llvm::AsmPrinter::recordSled
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
Definition: AsmPrinter.cpp:3568
emitGlobalConstantFP
static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2859
llvm::ConstantInt::getBitWidth
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
Definition: Constants.h:136
llvm::MCAsmInfo::useIntegratedAssembler
bool useIntegratedAssembler() const
Return true if assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:814
DebugInfoMetadata.h
llvm::Triple::isOSBinFormatCOFF
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:640
llvm::AsmPrinter::CurrentFnSymForSize
MCSymbol * CurrentFnSymForSize
The symbol used to represent the start of the current function for the purpose of calculating its siz...
Definition: AsmPrinter.h:127
llvm::ExceptionHandling::SjLj
@ SjLj
setjmp/longjmp based exceptions
llvm::GlobalValue::getLinkage
LinkageTypes getLinkage() const
Definition: GlobalValue.h:467
llvm::AsmPrinter::createTempSymbol
MCSymbol * createTempSymbol(const Twine &Name) const
Definition: AsmPrinter.cpp:3127
llvm::GlobalValue::dropLLVMManglingEscape
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:488
llvm::HexagonISD::JT
@ JT
Definition: HexagonISelLowering.h:52
llvm::GlobalValue::HiddenVisibility
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:64
T
llvm::APInt::getNumWords
unsigned getNumWords() const
Get the number of words.
Definition: APInt.h:1417
llvm::MCContext
Context object for machine code objects.
Definition: MCContext.h:72
llvm::Function
Definition: Function.h:62
llvm::EHStreamer
Emits exception handling directives.
Definition: EHStreamer.h:30
emitGlobalConstantLargeInt
static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2863
llvm::Loop
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:530
StringRef.h
P
This currently compiles esp xmm0 movsd esp eax eax esp ret We should use not the dag combiner This is because dagcombine2 needs to be able to see through the X86ISD::Wrapper which DAGCombine can t really do The code for turning x load into a single vector load is target independent and should be moved to the dag combiner The code for turning x load into a vector load can only handle a direct load from a global or a direct load from the stack It should be generalized to handle any load from P
Definition: README-SSE.txt:411
Pass.h
llvm::TargetSubtargetInfo::getInstrInfo
virtual const TargetInstrInfo * getInstrInfo() const
Definition: TargetSubtargetInfo.h:92
llvm::SectionKind::isBSS
bool isBSS() const
Definition: SectionKind.h:163
llvm::AsmPrinter::MBBSectionRange
Map a basic block section ID to the begin and end symbols of that section which determine the section...
Definition: AsmPrinter.h:131
llvm::MCSA_ELF_TypeObject
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
Definition: MCDirectives.h:25
llvm::MachineConstantPoolEntry::MachineCPVal
MachineConstantPoolValue * MachineCPVal
Definition: MachineConstantPool.h:72
llvm::SectionKind::isThreadBSS
bool isThreadBSS() const
Definition: SectionKind.h:155
MCDirectives.h
llvm::MCSA_Invalid
@ MCSA_Invalid
Not a valid directive.
Definition: MCDirectives.h:19
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:625
llvm::TargetLoweringObjectFile::getSymbolWithGlobalValueBase
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...
Definition: TargetLoweringObjectFile.cpp:129
llvm::GlobalObject::getSection
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:112
llvm::AsmPrinter::MAI
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:87
llvm::MachineBasicBlock::isEHFuncletEntry
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
Definition: MachineBasicBlock.h:552
llvm::MCConstantExpr::create
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
llvm::MCAsmInfo
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
llvm::Target
Target - Wrapper for Target specific information.
Definition: TargetRegistry.h:137
llvm::GlobalValue::hasWeakLinkage
bool hasWeakLinkage() const
Definition: GlobalValue.h:445
llvm::ConstantInt::getValue
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:133
MCSectionELF.h
RemarkStringTable.h
llvm::AsmPrinter::emitGlobalConstant
void emitGlobalConstant(const DataLayout &DL, const Constant *CV)
Print a general LLVM constant to the .s file.
Definition: AsmPrinter.cpp:3094
DbgTimerDescription
const char DbgTimerDescription[]
Definition: AsmPrinter.cpp:146
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
Statistic.h
Path.h
emitKill
static void emitKill(const MachineInstr *MI, AsmPrinter &AP)
Definition: AsmPrinter.cpp:909
llvm::AsmPrinter::CFISection::Debug
@ Debug
Emit .debug_frame.
llvm::AsmPrinter::emitPatchableFunctionEntries
void emitPatchableFunctionEntries()
Definition: AsmPrinter.cpp:3581
llvm::APInt::getSExtValue
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1472
llvm::DataLayout::getTypeStoreSize
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition: DataLayout.h:471
llvm::Function::getSubprogram
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1541
llvm::MipsISD::Lo
@ Lo
Definition: MipsISelLowering.h:79
llvm::ConstantDataSequential::getElementAsInteger
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:3190
llvm::AsmPrinter::Structor::Priority
int Priority
Definition: AsmPrinter.h:411
ErrorHandling.h
MCSectionCOFF.h
llvm::TargetLoweringObjectFile::SectionForGlobal
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...
Definition: TargetLoweringObjectFile.cpp:316
llvm::GlobalVariable
Definition: GlobalVariable.h:40
DisableDebugInfoPrinting
static cl::opt< bool > DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden, cl::desc("Disable debug info printing"))
llvm::ISD::EH_LABEL
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:988
llvm::MachineBasicBlock::isEntryBlock
bool isEntryBlock() const
Returns true if this is the entry block of the function.
Definition: MachineBasicBlock.cpp:289
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
llvm::BlockAddress::getBasicBlock
BasicBlock * getBasicBlock() const
Definition: Constants.h:877
llvm::GlobalAlias
Definition: GlobalAlias.h:28
llvm::MCSymbol::isUndefined
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:252
llvm::MCBinaryExpr::createAnd
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:530
llvm::MachineFunction::getFunctionNumber
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
Definition: MachineFunction.h:609
llvm::TargetLoweringObjectFile::lowerRelativeReference
virtual const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.h:189
OptimizationRemarkEmitter.h
llvm::AsmPrinter::getNameWithPrefix
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:480
llvm::MachineBasicBlock::getEHCatchretSymbol
MCSymbol * getEHCatchretSymbol() const
Return the EHCatchret Symbol for this basic block.
Definition: MachineBasicBlock.cpp:91
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
MachineBasicBlock.h
COFF.h
llvm::AsmPrinter::doFinalization
bool doFinalization(Module &M) override
Shut down the asmprinter.
Definition: AsmPrinter.cpp:1723
llvm::MachineBasicBlock::isReturnBlock
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
Definition: MachineBasicBlock.h:805
llvm::AsmPrinter::emitStackMaps
void emitStackMaps(StackMaps &SM)
Emit the stack maps.
Definition: AsmPrinter.cpp:3449
llvm::TargetSubtargetInfo::getRegisterInfo
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Definition: TargetSubtargetInfo.h:124
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:143
llvm::MachineModuleInfoImpl::SymbolListTy
std::vector< std::pair< MCSymbol *, StubValueTy > > SymbolListTy
Definition: MachineModuleInfo.h:63
llvm::MachineModuleInfo::hasDebugInfo
bool hasDebugInfo() const
Returns true if valid debug info is present.
Definition: MachineModuleInfo.h:203
llvm::ConstantInt::getLimitedValue
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:244
llvm::MCAsmInfo::hasAltEntry
bool hasAltEntry() const
Definition: MCAsmInfo.h:739
APInt.h
llvm::WinEH::EncodingType::X86
@ X86
Windows x64, Windows Itanium (IA-64)
llvm::MachineConstantPoolValue
Abstract base class for all machine specific constantpool value subclasses.
Definition: MachineConstantPool.h:35
llvm::DILocation
Debug location.
Definition: DebugInfoMetadata.h:1580
llvm::DenseMapIterator
Definition: DenseMap.h:56
llvm::WasmException
Definition: WasmException.h:22
llvm::StackOffset::getFixed
ScalarTy getFixed() const
Definition: TypeSize.h:149
MachineJumpTableInfo.h
llvm::DILabel::getName
StringRef getName() const
Definition: DebugInfoMetadata.h:3239
llvm::TargetMachine::getRelocationModel
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
Definition: TargetMachine.cpp:70
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
CodeViewLineTablesGroupDescription
const char CodeViewLineTablesGroupDescription[]
Definition: AsmPrinter.cpp:152
DenseMap.h
llvm::APInt::getBitWidth
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1410
llvm::TimePassesIsEnabled
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: PassTimingInfo.cpp:37
Module.h
llvm::AsmPrinter::getFunctionCFISectionType
CFISection getFunctionCFISectionType(const Function &F) const
Get the CFISection type for a function.
Definition: AsmPrinter.cpp:1052
llvm::reverse
auto reverse(ContainerTy &&C, std::enable_if_t< has_rbegin< ContainerTy >::value > *=nullptr)
Definition: STLExtras.h:359
llvm::MCSymbol::isDefined
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:243
llvm::ilist_node_impl::getReverseIterator
reverse_self_iterator getReverseIterator()
Definition: ilist_node.h:84
TargetInstrInfo.h
llvm::AsmPrinter::getDwarfOffsetByteSize
unsigned int getDwarfOffsetByteSize() const
Returns 4 for DWARF32 and 8 for DWARF64.
Definition: AsmPrinter.cpp:3628
llvm::AsmPrinter::setDwarfVersion
void setDwarfVersion(uint16_t Version)
Definition: AsmPrinter.cpp:3620
isRepeatedByteSequence
static int isRepeatedByteSequence(const ConstantDataSequential *V)
isRepeatedByteSequence - Determine whether the given value is composed of a repeated sequence of iden...
Definition: AsmPrinter.cpp:2670
llvm::TargetLoweringObjectFile::getStaticCtorSection
virtual MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const
Definition: TargetLoweringObjectFile.h:175
llvm::ARMException
Definition: DwarfException.h:71
EHPersonalities.h
llvm::AsmPrinter::SledKind
SledKind
Definition: AsmPrinter.h:288
llvm::Triple::isOSBinFormatXCOFF
bool isOSBinFormatXCOFF() const
Tests whether the OS uses the XCOFF binary format.
Definition: Triple.h:658
llvm::WinEH::EncodingType::Itanium
@ Itanium
Windows CE ARM, PowerPC, SH3, SH4.
llvm::ConstantFP::getValueAPF
const APFloat & getValueAPF() const
Definition: Constants.h:297
llvm::MachineJumpTableInfo::EK_BlockAddress
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.
Definition: MachineJumpTableInfo.h:49
llvm::MachineModuleInfo::hasNosplitStack
bool hasNosplitStack() const
Definition: MachineModuleInfo.h:226
llvm::ExceptionHandling::ARM
@ ARM
ARM EHABI.
llvm::MCAsmInfo::getCodePointerSize
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Definition: MCAsmInfo.h:536
llvm::Optional< unsigned >
llvm::TargetInstrInfo::getNop
virtual MCInst getNop() const
Return the noop instruction to use for a noop.
Definition: TargetInstrInfo.cpp:475
llvm::AsmPrinter::Structor
llvm.global_ctors and llvm.global_dtors are arrays of Structor structs.
Definition: AsmPrinter.h:410
llvm::GlobalValue::DefaultVisibility
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:63
GlobalObject.h
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:449
llvm::ore::NV
DiagnosticInfoOptimizationBase::Argument NV
Definition: OptimizationRemarkEmitter.h:136
Operator.h
llvm::VectorType::getElementType
Type * getElementType() const
Definition: DerivedTypes.h:422
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:893
STLExtras.h
llvm::MachineBasicBlock::back
MachineInstr & back()
Definition: MachineBasicBlock.h:248
llvm::MCInst
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2596
llvm::MachineFunction::getJTISymbol
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
Definition: MachineFunction.cpp:679
llvm::GlobalValue::LinkageTypes
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
llvm::GCMetadataPrinter
GCMetadataPrinter - Emits GC metadata as assembly code.
Definition: GCMetadataPrinter.h:39
llvm::MachineBasicBlock::terminators
iterator_range< iterator > terminators()
Definition: MachineBasicBlock.h:288
llvm::MCAsmInfo::hasFunctionAlignment
bool hasFunctionAlignment() const
Definition: MCAsmInfo.h:733
llvm::AsmPrinter::ORE
MachineOptimizationRemarkEmitter * ORE
Optimization remark emitter.
Definition: AsmPrinter.h:111
llvm::MCAsmInfo::getWinEHEncodingType
WinEH::EncodingType getWinEHEncodingType() const
Definition: MCAsmInfo.h:763
llvm::Registry::entries
static iterator_range< iterator > entries()
Definition: Registry.h:101
Format.h
llvm::AsmPrinter::CurrentFnDescSym
MCSymbol * CurrentFnDescSym
The symbol for the current function descriptor on AIX.
Definition: AsmPrinter.h:122
llvm::MachineJumpTableInfo::EK_Custom32
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
Definition: MachineJumpTableInfo.h:76
llvm::ConstantDataSequential::isString
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:3283
ConstantFolding.h
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
p
the resulting code requires compare and branches when and if * p
Definition: README.txt:396
llvm::StackMaps
Definition: StackMaps.h:251
emitGlobalConstantDataSequential
static void emitGlobalConstantDataSequential(const DataLayout &DL, const ConstantDataSequential *CDS, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2716
llvm::MachineFunctionPass::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition: MachineFunctionPass.cpp:102
llvm::AsmPrinter::emitBBAddrMapSection
void emitBBAddrMapSection(const MachineFunction &MF)
Definition: AsmPrinter.cpp:1134
llvm::AsmPrinter::emitGlobalVariable
virtual void emitGlobalVariable(const GlobalVariable *GV)
Emit the specified global variable to the .s file.
Definition: AsmPrinter.cpp:507
llvm::MachineOperand::MO_Register
@ MO_Register
Register operand.
Definition: MachineOperand.h:52
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::GlobalVariable::hasInitializer
bool hasInitializer() const
Definitions have initializers, declarations don't.
Definition: GlobalVariable.h:92
llvm::MachineLoopInfo
Definition: MachineLoopInfo.h:90
llvm::AsmPrinter::EmitToStreamer
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:242
llvm::MCSymbolAttr
MCSymbolAttr
Definition: MCDirectives.h:18
llvm::MachineFunction::getFrameInstructions
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
Definition: MachineFunction.h:1015
llvm::MCSA_Cold
@ MCSA_Cold
.cold (MachO)
Definition: MCDirectives.h:22
llvm::ISD::ARITH_FENCE
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
Definition: ISDOpcodes.h:1105
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
llvm::MCContext::getMachOSection
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:420
llvm::MipsISD::Hi
@ Hi
Definition: MipsISelLowering.h:75
llvm::ISD::INLINEASM
@ INLINEASM
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:980
llvm::ExceptionHandling::AIX
@ AIX
AIX Exception Handling.
a
=0.0 ? 0.0 :(a > 0.0 ? 1.0 :-1.0) a
Definition: README.txt:489
llvm::MCSA_Local
@ MCSA_Local
.local (ELF)
Definition: MCDirectives.h:37
llvm::ISD::PSEUDO_PROBE
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
Definition: ISDOpcodes.h:1197
llvm::IsConstantOffsetFromGlobal
bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
Definition: ConstantFolding.cpp:298
llvm::MachineBasicBlock::isBeginSection
bool isBeginSection() const
Returns true if this block begins any section.
Definition: MachineBasicBlock.h:564
llvm::MachineJumpTableInfo::getEntrySize
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
Definition: MachineFunction.cpp:1255
llvm::MCInst::setOpcode
void setOpcode(unsigned Op)
Definition: MCInst.h:197
llvm::MCSymbolELF
Definition: MCSymbolELF.h:14
llvm::TargetLoweringObjectFile
Definition: TargetLoweringObjectFile.h:44
llvm::MachineJumpTableInfo::getEntryKind
JTEntryKind getEntryKind() const
Definition: MachineJumpTableInfo.h:84
WasmException.h
llvm::MCSA_NoDeadStrip
@ MCSA_NoDeadStrip
.no_dead_strip (MachO)
Definition: MCDirectives.h:38
llvm::classifyEHPersonality
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Definition: EHPersonalities.cpp:21
llvm::ConstantDataSequential::getElementAsAPFloat
APFloat getElementAsAPFloat(unsigned i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
Definition: Constants.cpp:3238
llvm::AsmPrinter::GOTEquivUsePair
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:139
llvm::SectionKind::getReadOnly
static SectionKind getReadOnly()
Definition: SectionKind.h:185
Instruction.h
llvm::MachineBasicBlock::getSymbol
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
Definition: MachineBasicBlock.cpp:60
CommandLine.h
llvm::FixedVectorType::getNumElements
unsigned getNumElements() const
Definition: DerivedTypes.h:568
llvm::MCStreamer
Streaming machine code generation interface.
Definition: MCStreamer.h:199
llvm::MachineBasicBlock::pred_size
unsigned pred_size() const
Definition: MachineBasicBlock.h:328
llvm::TargetLoweringObjectFile::lowerDSOLocalEquivalent
virtual const MCExpr * lowerDSOLocalEquivalent(const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.h:201
TargetLowering.h
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::LoopBase::getParentLoop
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Definition: LoopInfo.h:113
llvm::remarks::RemarkStreamer::getSerializer
remarks::RemarkSerializer & getSerializer()
Return the serializer used for this stream.
Definition: RemarkStreamer.h:61
llvm::MachineFunction::front
const MachineBasicBlock & front() const
Definition: MachineFunction.h:828
llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:289
llvm::MCContext::getOrCreateSymbol
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:191
llvm::GCModuleInfo::iterator
SmallVector< std::unique_ptr< GCStrategy >, 1 >::const_iterator iterator
Definition: GCMetadata.h:181
llvm::MCAsmInfo::hasFourStringsDotFile
bool hasFourStringsDotFile() const
Definition: MCAsmInfo.h:736
llvm::Triple::isOSBinFormatELF
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:635
llvm::TargetLoweringObjectFile::getSectionForCommandLines
virtual MCSection * getSectionForCommandLines() const
If supported, return the section to use for the llvm.commandline metadata.
Definition: TargetLoweringObjectFile.h:243
llvm::MachineFunction::setSection
void setSection(MCSection *S)
Indicates the Section this function belongs to.
Definition: MachineFunction.h:592
llvm::TargetInstrInfo
TargetInstrInfo - Interface to description of machine instruction set.
Definition: TargetInstrInfo.h:97
GlobalValue.h
llvm::MCObjectFileInfo::getDataSection
MCSection * getDataSection() const
Definition: MCObjectFileInfo.h:259
MachineLoopInfo.h
ELF.h
llvm::ConstantDataSequential
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:569
TargetMachine.h
llvm::GlobalValue::isDeclaration
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:228
llvm::TargetMachine::getProgramPointerSize
unsigned getProgramPointerSize() const
Definition: TargetMachine.h:194
llvm::APInt::lshrInPlace
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:822
llvm::AsmPrinter::emitLinkage
virtual void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const
This emits linkage information about GVSym based on GV, if this is supported by the target.
Definition: AsmPrinter.cpp:440
llvm::GlobalValue::VisibilityTypes
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:62
llvm::SMLoc
Represents a location in source code.
Definition: SMLoc.h:23
llvm::GlobalValue::hasAppendingLinkage
bool hasAppendingLinkage() const
Definition: GlobalValue.h:448
Constants.h
llvm::MCObjectFileInfo::getTLSExtraDataSection
MCSection * getTLSExtraDataSection() const
Definition: MCObjectFileInfo.h:341
llvm::Constant::isNullValue
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:74
llvm::DILocalScope::getNonLexicalBlockFileScope
DILocalScope * getNonLexicalBlockFileScope() const
Get the first non DILexicalBlockFile scope of this scope.
Definition: DebugInfoMetadata.cpp:834
llvm::AsmPrinter::XRayFunctionEntry::Version
uint8_t Version
Definition: AsmPrinter.h:307
SmallString.h
llvm::DILocalVariable
Local variable.
Definition: DebugInfoMetadata.h:3104
emitGlobalConstantStruct
static void emitGlobalConstantStruct(const DataLayout &DL, const ConstantStruct *CS, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
Definition: AsmPrinter.cpp:2787
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::ExceptionHandling
ExceptionHandling
Definition: MCTargetOptions.h:18
llvm::TargetOptions::UseInitArray
unsigned UseInitArray
UseInitArray - Use .init_array instead of .ctors for static constructors.
Definition: TargetOptions.h:246
llvm::MCBinaryExpr::createMul
static const MCBinaryExpr * createMul(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:580
EHTimerDescription
const char EHTimerDescription[]
Definition: AsmPrinter.cpp:148
llvm::AsmPrinter::OutStreamer
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:96
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::TargetOptions::ForceDwarfFrameSection
unsigned ForceDwarfFrameSection
Emit DWARF debug frame section.
Definition: TargetOptions.h:336
llvm::MCSA_AltEntry
@ MCSA_AltEntry
.alt_entry (MachO)
Definition: MCDirectives.h:40
Twine.h
canBeHidden
static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI)
Definition: AsmPrinter.cpp:433
int
Clang compiles this i1 i64 store i64 i64 store i64 i64 store i64 i64 store i64 align Which gets codegen d xmm0 movaps rbp movaps rbp movaps rbp movaps rbp rbp rbp rbp rbp It would be better to have movq s of instead of the movaps s LLVM produces ret int
Definition: README.txt:536
llvm::GlobalObject
Definition: GlobalObject.h:28
llvm::TargetLowering
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Definition: TargetLowering.h:3254
llvm::MCSubtargetInfo::getTargetTriple
const Triple & getTargetTriple() const
Definition: MCSubtargetInfo.h:107
MCSymbolELF.h
MCContext.h
llvm::Type::print
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4543
llvm::MachineOperand::MO_FrameIndex
@ MO_FrameIndex
Abstract Stack Frame Index.
Definition: MachineOperand.h:57
llvm::COFF::IMAGE_SCN_MEM_READ
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:321
MCSectionMachO.h
llvm::Registry::entry
SimpleRegistryEntry< T > entry
Definition: Registry.h:47
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
llvm::AsmPrinter::SetupMachineFunction
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
Definition: AsmPrinter.cpp:1978
llvm::AsmPrinter::emitFunctionEntryLabel
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
Definition: AsmPrinter.cpp:842
MCSymbol.h
gcp_map_type
DenseMap< GCStrategy *, std::unique_ptr< GCMetadataPrinter > > gcp_map_type
Definition: AsmPrinter.cpp:162
llvm::MCValue::isAbsolute
bool isAbsolute() const
Is this an absolute (as opposed to relocatable) value.
Definition: MCValue.h:50
llvm::GlobalValue::hasPrivateLinkage
bool hasPrivateLinkage() const
Definition: GlobalValue.h:450
llvm::MachineFunction::hasBBLabels
bool hasBBLabels() const
Returns true if basic block labels are to be generated for this function.
Definition: MachineFunction.h:619
llvm::AsmPrinter::emitStartOfAsmFile
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:474
CFGuardDescription
const char CFGuardDescription[]
Definition: AsmPrinter.cpp:150
llvm::MCContext::getELFSection
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:540
llvm::PseudoProbeDescMetadataName
constexpr const char * PseudoProbeDescMetadataName
Definition: PseudoProbe.h:26
emitDebugValueComment
static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP)
emitDebugValueComment - This method handles the target-independent form of DBG_VALUE,...
Definition: AsmPrinter.cpp:925
MCInst.h
llvm::AsmPrinter::isBlockOnlyReachableByFallthrough
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
Definition: AsmPrinter.cpp:3387
Remark.h
llvm::TargetOptions::MCOptions
MCTargetOptions MCOptions
Machine level options.
Definition: TargetOptions.h:420
TargetOpcodes.h
llvm::AsmPrinterHandler::markFunctionEnd
virtual void markFunctionEnd()
Definition: AsmPrinter.cpp:3473
TII
const HexagonInstrInfo * TII
Definition: HexagonCopyToCombine.cpp:129
llvm::WinEH::EncodingType::Invalid
@ Invalid
llvm::MachineFunction::size
unsigned size() const
Definition: MachineFunction.h:826
llvm::MachineConstantPoolEntry::getSectionKind
SectionKind getSectionKind(const DataLayout *DL) const
Definition: MachineFunction.cpp:1386
llvm::Mangler::getNameWithPrefix
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:119
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:109
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::MachineOperand
MachineOperand class - Representation of each machine instruction operand.
Definition: MachineOperand.h:49
llvm::MCSA_ELF_TypeIndFunction
@ MCSA_ELF_TypeIndFunction
.type _foo, STT_GNU_IFUNC
Definition: MCDirectives.h:24
llvm::MachineConstantPoolEntry::getAlign
Align getAlign() const
Definition: MachineConstantPool.h:95
MCSubtargetInfo.h
llvm::MachineFunction::rbegin
reverse_iterator rbegin()
Definition: MachineFunction.h:821
llvm::ConstantArray
ConstantArray - Constant Array Declarations.
Definition: Constants.h:409
llvm::WinException
Definition: WinException.h:26
llvm::APFloat::convertToDouble
double convertToDouble() const
Converts this APFloat to host double value.
Definition: APFloat.cpp:4895
llvm::Triple::isOSBinFormatMachO
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:648
llvm::MCObjectFileInfo::getStackSizesSection
MCSection * getStackSizesSection(const MCSection &TextSec) const
Definition: MCObjectFileInfo.cpp:1053
llvm::MachineModuleInfo
This class contains meta information specific to a module.
Definition: MachineModuleInfo.h:78
llvm::MCAsmInfo::needsDwarfSectionOffsetDirective
bool needsDwarfSectionOffsetDirective() const
Definition: MCAsmInfo.h:611
llvm::AsmPrinter::emitInstruction
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition: AsmPrinter.h:498
MachineInstrBundle.h
llvm::AsmPrinter::MLI
MachineLoopInfo * MLI
This is a pointer to the current MachineLoopInfo.
Definition: AsmPrinter.h:108
llvm::MCAsmInfo::useAssignmentForEHBegin
bool useAssignmentForEHBegin() const
Definition: MCAsmInfo.h:652
llvm::isNoOpWithoutInvoke
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
Definition: EHPersonalities.h:96
llvm::AsmPrinter::CurrentFnSym
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:118
llvm::MachineOptimizationRemarkAnalysis
Diagnostic information for optimization analysis remarks.
Definition: MachineOptimizationRemarkEmitter.h:108
llvm::AsmPrinter::emitAlignment
void emitAlignment(Align Alignment, const GlobalObject *GV=nullptr) const
Emit an alignment directive to the specified power of two boundary.
Definition: AsmPrinter.cpp:2465
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:143
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
llvm::ExceptionHandling::Wasm
@ Wasm
WebAssembly Exception Handling.
llvm::MachineBasicBlock::isEHCatchretTarget
bool isEHCatchretTarget() const
Returns true if this is a target block of a catchret.
Definition: MachineBasicBlock.h:546
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::ConstantFP
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:257
llvm::AsmPrinter::emitEndOfAsmFile
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:478
DWARFGroupDescription
const char DWARFGroupDescription[]
Definition: AsmPrinter.cpp:144
llvm::Function::hasPersonalityFn
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:775
APFloat.h
This file declares a class to represent arbitrary precision floating point values and provide a varie...
llvm::MCSymbolRefExpr::getSymbol
const MCSymbol & getSymbol() const
Definition: MCExpr.h:399
llvm::MCValue::getConstant
int64_t getConstant() const
Definition: MCValue.h:44
llvm::MachineFrameInfo::getStackSize
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
Definition: MachineFrameInfo.h:553
llvm::MemoryLocation::UnknownSize
@ UnknownSize
Definition: MemoryLocation.h:214
SmallPtrSet.h
llvm::AsmPrinter::XRayFunctionEntry::AlwaysInstrument
bool AlwaysInstrument
Definition: AsmPrinter.h:305
llvm::AsmPrinter::emitFunctionBodyStart
virtual void emitFunctionBodyStart()
Targets can override this to emit stuff before the first basic block in the function.
Definition: AsmPrinter.h:482
llvm::MCSymbol::getName
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:198
llvm::MCValue::getSymA
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:45
llvm::TargetMachine::getSymbol
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: TargetMachine.cpp:209
DwarfDebug.h
llvm::remarks::RemarkStreamer::needsSection
bool needsSection() const
Check if the remarks also need to have associated metadata in a section.
Definition: RemarkStreamer.cpp:49
llvm::GlobalValue::hasGlobalUnnamedAddr
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:196
llvm::AsmPrinter::CurrentPatchableFunctionEntrySym
MCSymbol * CurrentPatchableFunctionEntrySym
The symbol for the entry in __patchable_function_entires.
Definition: AsmPrinter.h:114
Align
uint64_t Align
Definition: ELFObjHandler.cpp:83
llvm::ConstantStruct::getType
StructType * getType() const
Specialization - reduce amount of casting.
Definition: Constants.h:480
llvm::APFloat::bitcastToAPInt
APInt bitcastToAPInt() const
Definition: APFloat.h:1130
llvm::AsmPrinter::emitInt8
void emitInt8(int Value) const
Emit a byte directive and value.
Definition: AsmPrinter.cpp:2416
llvm::MCAsmInfo::doesUseCFIForDebug
bool doesUseCFIForDebug() const
Definition: MCAsmInfo.h:769
llvm::GlobalValue::InternalLinkage
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
llvm::MCAsmInfo::hasNoDeadStrip
bool hasNoDeadStrip() const
Definition: MCAsmInfo.h:738
llvm::Align
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
llvm::Triple::isOSAIX
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:630
llvm::Type::isFunctionTy
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:208
MCSectionXCOFF.h
llvm::TargetLoweringObjectFile::getSectionForJumpTable
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
Definition: TargetLoweringObjectFile.cpp:350
llvm::MachineModuleInfo::setDebugInfoAvailability
void setDebugInfoAvailability(bool avail)
Definition: MachineModuleInfo.h:204
llvm::TargetLoweringObjectFile::getKindForGlobal
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
Definition: TargetLoweringObjectFile.cpp:202
llvm::Value::use_empty
bool use_empty() const
Definition: Value.h:344
llvm::AsmPrinter::getFunctionBegin
MCSymbol * getFunctionBegin() const
Definition: AsmPrinter.h:246
llvm::AsmPrinter::emitBasicBlockStart
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
Definition: AsmPrinter.cpp:3259
llvm::MCCFIInstruction
Definition: MCDwarf.h:470
llvm::remarks::RemarkSerializer
This is the base class for a remark serializer.
Definition: RemarkSerializer.h:38
llvm::MCAsmInfo::getProtectedVisibilityAttr
MCSymbolAttr getProtectedVisibilityAttr() const
Definition: MCAsmInfo.h:756
Type.h
RemarkFormat.h
llvm::AsmPrinter::getPointerSize
unsigned getPointerSize() const
Return the pointer size from the TargetMachine.
Definition: AsmPrinter.cpp:233
llvm::MachineBasicBlock
Definition: MachineBasicBlock.h:95
llvm::TargetLoweringObjectFile::getFunctionEntryPointSymbol
virtual MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const
If supported, return the function entry point symbol.
Definition: TargetLoweringObjectFile.h:281
llvm::MCBinaryExpr::createShl
static const MCBinaryExpr * createShl(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:595
llvm::AsmPrinter::XRayFunctionEntry::Kind
SledKind Kind
Definition: AsmPrinter.h:304
llvm::SmallString< 128 >
llvm::MachineJumpTableInfo::EK_LabelDifference32
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
Definition: MachineJumpTableInfo.h:68
llvm::TargetMachine::isPositionIndependent
bool isPositionIndependent() const
Definition: TargetMachine.cpp:44
llvm::MCAsmInfo::hasWeakDefCanBeHiddenDirective
bool hasWeakDefCanBeHiddenDirective() const
Definition: MCAsmInfo.h:744
llvm::MCStreamer::emitBinaryData
virtual void emitBinaryData(StringRef Data)
Functionally identical to EmitBytes.
Definition: MCStreamer.cpp:1190
llvm::MachineBasicBlock::getSectionIDNum
unsigned getSectionIDNum() const
Returns the unique section ID number of this basic block.
Definition: MachineBasicBlock.h:577
MachineOptimizationRemarkEmitter.h
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
llvm::MCDR_DataRegionJT32
@ MCDR_DataRegionJT32
.data_region jt32
Definition: MCDirectives.h:62
llvm::MachineModuleInfoCOFF
MachineModuleInfoCOFF - This is a MachineModuleInfoImpl implementation for COFF targets.
Definition: MachineModuleInfoImpls.h:85
llvm::DILocalVariable::getScope
DILocalScope * getScope() const
Get the local scope for this variable.
Definition: DebugInfoMetadata.h:3162
llvm::Value::user_back
User * user_back()
Definition: Value.h:407
llvm::AsmPrinter::Handlers
std::vector< HandlerInfo > Handlers
A vector of all debug/EH info emitters we should use.
Definition: AsmPrinter.h:194
EHTimerName
const char EHTimerName[]
Definition: AsmPrinter.cpp:147
llvm::AsmPrinter::CFISection::None
@ None
Do not emit either .eh_frame or .debug_frame.
llvm::AsmPrinter::AsmPrinter
AsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
Definition: AsmPrinter.cpp:196
llvm::MachineFunction::getMMI
MachineModuleInfo & getMMI() const
Definition: MachineFunction.h:585
handleIndirectSymViaGOTPCRel
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,...
Definition: AsmPrinter.cpp:2923
llvm::ConstantArray::getType
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition: Constants.h:428
llvm::TargetLowering::getPICJumpTableRelocBaseExpr
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,...
Definition: TargetLowering.cpp:464
llvm::AsmPrinter::emitMachineConstantPoolValue
virtual void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV)
Definition: AsmPrinter.cpp:3105
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
llvm::MachineFunction::getSubtarget
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Definition: MachineFunction.h:634
llvm::MCSA_WeakDefAutoPrivate
@ MCSA_WeakDefAutoPrivate
.weak_def_can_be_hidden (MachO)
Definition: MCDirectives.h:47
llvm::PseudoProbeHandler
Definition: PseudoProbePrinter.h:26
llvm::AsmPrinter::emitFrameAlloc
void emitFrameAlloc(const MachineInstr &MI)
Definition: AsmPrinter.cpp:1107
llvm::DataLayout::isBigEndian
bool isBigEndian() const
Definition: DataLayout.h:244
llvm::AsmPrinter::GetJTSetSymbol
MCSymbol * GetJTSetSymbol(unsigned UID, unsigned MBBID) const
Return the symbol for the specified jump table .set FIXME: privatize to AsmPrinter.
Definition: AsmPrinter.cpp:3174
Timer.h
BasicBlock.h
llvm::ConstantDataSequential::getRawDataValues
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2913
llvm::cl::opt< bool >
llvm::GlobalObject::hasSection
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:104
llvm::APFloat
Definition: APFloat.h:701
llvm::GlobalValue::hasAvailableExternallyLinkage
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:435
llvm::remarks::RemarkStreamer::getFilename
Optional< StringRef > getFilename() const
Return the filename that the remark diagnostics are emitted to.
Definition: RemarkStreamer.h:55
llvm::AsmPrinterHandler::~AsmPrinterHandler
virtual ~AsmPrinterHandler()
Pin vtable to this file.
needFuncLabelsForEHOrDebugInfo
static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF)
Definition: AsmPrinter.cpp:1225
llvm::ConstantVector::getType
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition: Constants.h:516
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:206
llvm::AsmPrinter::emitInt64
void emitInt64(uint64_t Value) const
Emit a long long directive and value.
Definition: AsmPrinter.cpp:2425
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::MachineJumpTableInfo::getJumpTables
const std::vector< MachineJumpTableEntry > & getJumpTables() const
Definition: MachineJumpTableInfo.h:99
llvm::MachineLoop
Definition: MachineLoopInfo.h:45
llvm::Module::getName
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:244
llvm::GlobalValue::canBenefitFromLocalAlias
bool canBenefitFromLocalAlias() const
Definition: Globals.cpp:105
llvm::GlobalVariable::getInitializer
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Definition: GlobalVariable.h:136
llvm::MachineJumpTableInfo::EK_GPRel64BlockAddress
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
Definition: MachineJumpTableInfo.h:54
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
emitComments
static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS)
emitComments - Pretty-print comments for instructions.
Definition: AsmPrinter.cpp:861
llvm::TargetMachine::isNoopAddrSpaceCast
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
Definition: TargetMachine.h:308
llvm::TargetLoweringObjectFile::supportGOTPCRelWithOffset
bool supportGOTPCRelWithOffset() const
Target GOT "PC"-relative relocation supports encoding an additional binary expression with an offset?
Definition: TargetLoweringObjectFile.h:214
llvm::MachineOptimizationRemarkEmitter::emit
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
Definition: MachineOptimizationRemarkEmitter.cpp:49
llvm::AsmPrinter::GetCPISymbol
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
Definition: AsmPrinter.cpp:3140
Index
uint32_t Index
Definition: ELFObjHandler.cpp:84
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:64
llvm::DwarfDebug
Collects and handles dwarf debug information.
Definition: DwarfDebug.h:296
llvm::AsmPrinter::emitLabelPlusOffset
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...
Definition: AsmPrinter.cpp:2440
emitGlobalConstantVector
static void emitGlobalConstantVector(const DataLayout &DL, const ConstantVector *CV, AsmPrinter &AP)
Definition: AsmPrinter.cpp:2775
llvm::StructLayout
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:613
uint64_t
PPTimerName
const char PPTimerName[]
Definition: AsmPrinter.cpp:153
llvm::sys::fs::OF_Text
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:761
llvm::AsmPrinter::needsCFIForDebug
bool needsCFIForDebug() const
Since emitting CFI unwind information is entangled with supporting the exceptions,...
Definition: AsmPrinter.cpp:1076
llvm::APInt::getRawData
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
Definition: APInt.h:533
llvm::MachineInstr::ReloadReuse
@ ReloadReuse
Definition: MachineInstr.h:75
llvm::GlobalValue::getVisibility
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:229
llvm::MachineBasicBlock::hasAddressTaken
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
Definition: MachineBasicBlock.h:211
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:578
llvm::MCBinaryExpr::createOr
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:590
llvm::DwarfCFIException
Definition: DwarfException.h:37
llvm::ELF::SHT_PROGBITS
@ SHT_PROGBITS
Definition: ELF.h:916
llvm::TargetMachine::getMCSubtargetInfo
const MCSubtargetInfo * getMCSubtargetInfo() const
Definition: TargetMachine.h:212
llvm::TargetLoweringObjectFile::supportIndirectSymViaGOTPCRel
bool supportIndirectSymViaGOTPCRel() const
Target supports replacing a data "PC"-relative access to a symbol through another symbol,...
Definition: TargetLoweringObjectFile.h:208
s
multiplies can be turned into SHL s
Definition: README.txt:370
llvm::MCSA_WeakReference
@ MCSA_WeakReference
.weak_reference (MachO)
Definition: MCDirectives.h:46
llvm::StackMaps::serializeToStackMapSection
void serializeToStackMapSection()
If there is any stack map data, create a stack map section and serialize the map info into it.
Definition: StackMaps.cpp:708
llvm::GlobalValue::WeakAnyLinkage
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
llvm::AsmPrinter::GetBlockAddressSymbol
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
Definition: AsmPrinter.cpp:3131
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::ELF::SHF_ALLOC
@ SHF_ALLOC
Definition: ELF.h:994
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
llvm::AsmPrinter::getSymbolPreferLocal
MCSymbol * getSymbolPreferLocal(const GlobalValue &GV) const
Similar to getSymbol() but preferred for references.
Definition: AsmPrinter.cpp:489
MemoryLocation.h
llvm::DenseMap
Definition: DenseMap.h:714
MCSymbolXCOFF.h
llvm::MachineConstantPool
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
Definition: MachineConstantPool.h:117
llvm::TargetOptions::EmitAddrsig
unsigned EmitAddrsig
Emit address-significance table.
Definition: TargetOptions.h:306
llvm::MCAsmInfo::hasVisibilityOnlyWithLinkage
bool hasVisibilityOnlyWithLinkage() const
Definition: MCAsmInfo.h:621
llvm::GlobalValue::hasComdat
bool hasComdat() const
Definition: GlobalValue.h:222
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::MCContext::createLinkerPrivateTempSymbol
MCSymbol * createLinkerPrivateTempSymbol()
Create and return a new linker temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:297
llvm::dwarf::getUnitLengthFieldByteSize
uint8_t getUnitLengthFieldByteSize(DwarfFormat Format)
Get the byte size of the unit length field depending on the DWARF format.
Definition: Dwarf.h:671
llvm::AsmPrinter::needsSEHMoves
bool needsSEHMoves()
Definition: AsmPrinter.cpp:1072
MachineConstantPool.h
llvm::ConstantDataSequential::getElementType
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2907
llvm::MachineModuleInfo::getAddrLabelSymbol
MCSymbol * getAddrLabelSymbol(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
Definition: MachineModuleInfo.h:237
PPGroupName
const char PPGroupName[]
Definition: AsmPrinter.cpp:155
llvm::GlobalIFunc::getResolver
const Constant * getResolver() const
Definition: GlobalIFunc.h:70
llvm::DwarfDebug::emitInitialLocDirective
DebugLoc emitInitialLocDirective(const MachineFunction &MF, unsigned CUID)
Emits inital debug location directive.
Definition: DwarfDebug.cpp:2162
llvm::MachineBasicBlock::getAlignment
Align getAlignment() const
Return alignment of the basic block.
Definition: MachineBasicBlock.h:519
MachineFunctionPass.h
emitGlobalConstantArray
static void emitGlobalConstantArray(const DataLayout &DL, const ConstantArray *CA, AsmPrinter &AP, const Constant *BaseCV, uint64_t Offset)
Definition: AsmPrinter.cpp:2756
llvm::Type::isHalfTy
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:141
llvm::MCSymbol::isVariable
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:293
llvm::GlobalValue::isDiscardableIfUnused
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:372
llvm::AsmPrinter::emitJumpTableInfo
virtual void emitJumpTableInfo()
Print assembly representations of the jump tables used by the current function to the current output ...
Definition: AsmPrinter.cpp:2111
llvm::DenseMapBase::find
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
llvm::MCSection::NonUniqueID
static constexpr unsigned NonUniqueID
Definition: MCSection.h:41
llvm::ConstantVector
Constant Vector Declarations.
Definition: Constants.h:493
llvm::MachineFunction::getName
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Definition: MachineFunction.cpp:542
llvm::NamedMDNode::getOperand
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1124
llvm::TargetMachine::Options
TargetOptions Options
Definition: TargetMachine.h:121
llvm::MachineFunction::getConstantPool
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
Definition: MachineFunction.h:666
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::MachineBasicBlock::canFallThrough
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
Definition: MachineBasicBlock.cpp:965
llvm::TargetLoweringObjectFile::getIndirectSymViaGOTPCRel
virtual const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Get the target specific PC relative GOT entry relocation.
Definition: TargetLoweringObjectFile.h:232
llvm::MachineConstantPoolEntry::isMachineConstantPoolEntry
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
Definition: MachineConstantPool.h:93
llvm::AsmPrinter::getSymbol
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:485
llvm::TargetMachine
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:80