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