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