LLVM  16.0.0git
AsmWriter.cpp
Go to the documentation of this file.
1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
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 library implements `print` family of functions in classes like
10 // Module, Function, Value, etc. In-memory representation of those classes is
11 // converted to IR strings.
12 //
13 // Note that these routines must be extremely tolerant of various errors in the
14 // LLVM code, because it can be used for debugging transformations.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Config/llvm-config.h"
34 #include "llvm/IR/Argument.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Comdat.h"
41 #include "llvm/IR/Constant.h"
42 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalIFunc.h"
48 #include "llvm/IR/GlobalObject.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/GlobalVariable.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/InstrTypes.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/Metadata.h"
59 #include "llvm/IR/Module.h"
62 #include "llvm/IR/Operator.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/TypeFinder.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/User.h"
68 #include "llvm/IR/Value.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/Format.h"
78 #include <algorithm>
79 #include <cassert>
80 #include <cctype>
81 #include <cstddef>
82 #include <cstdint>
83 #include <iterator>
84 #include <memory>
85 #include <optional>
86 #include <string>
87 #include <tuple>
88 #include <utility>
89 #include <vector>
90 
91 using namespace llvm;
92 
93 // Make virtual table appear in this compilation unit.
95 
96 //===----------------------------------------------------------------------===//
97 // Helper Functions
98 //===----------------------------------------------------------------------===//
99 
101 
102 using UseListOrderMap =
104 
105 /// Look for a value that might be wrapped as metadata, e.g. a value in a
106 /// metadata operand. Returns the input value as-is if it is not wrapped.
107 static const Value *skipMetadataWrapper(const Value *V) {
108  if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
109  if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
110  return VAM->getValue();
111  return V;
112 }
113 
114 static void orderValue(const Value *V, OrderMap &OM) {
115  if (OM.lookup(V))
116  return;
117 
118  if (const Constant *C = dyn_cast<Constant>(V))
119  if (C->getNumOperands() && !isa<GlobalValue>(C))
120  for (const Value *Op : C->operands())
121  if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
122  orderValue(Op, OM);
123 
124  // Note: we cannot cache this lookup above, since inserting into the map
125  // changes the map's size, and thus affects the other IDs.
126  unsigned ID = OM.size() + 1;
127  OM[V] = ID;
128 }
129 
130 static OrderMap orderModule(const Module *M) {
131  OrderMap OM;
132 
133  for (const GlobalVariable &G : M->globals()) {
134  if (G.hasInitializer())
135  if (!isa<GlobalValue>(G.getInitializer()))
136  orderValue(G.getInitializer(), OM);
137  orderValue(&G, OM);
138  }
139  for (const GlobalAlias &A : M->aliases()) {
140  if (!isa<GlobalValue>(A.getAliasee()))
141  orderValue(A.getAliasee(), OM);
142  orderValue(&A, OM);
143  }
144  for (const GlobalIFunc &I : M->ifuncs()) {
145  if (!isa<GlobalValue>(I.getResolver()))
146  orderValue(I.getResolver(), OM);
147  orderValue(&I, OM);
148  }
149  for (const Function &F : *M) {
150  for (const Use &U : F.operands())
151  if (!isa<GlobalValue>(U.get()))
152  orderValue(U.get(), OM);
153 
154  orderValue(&F, OM);
155 
156  if (F.isDeclaration())
157  continue;
158 
159  for (const Argument &A : F.args())
160  orderValue(&A, OM);
161  for (const BasicBlock &BB : F) {
162  orderValue(&BB, OM);
163  for (const Instruction &I : BB) {
164  for (const Value *Op : I.operands()) {
166  if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
167  isa<InlineAsm>(*Op))
168  orderValue(Op, OM);
169  }
170  orderValue(&I, OM);
171  }
172  }
173  }
174  return OM;
175 }
176 
177 static std::vector<unsigned>
178 predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
179  // Predict use-list order for this one.
180  using Entry = std::pair<const Use *, unsigned>;
182  for (const Use &U : V->uses())
183  // Check if this user will be serialized.
184  if (OM.lookup(U.getUser()))
185  List.push_back(std::make_pair(&U, List.size()));
186 
187  if (List.size() < 2)
188  // We may have lost some users.
189  return {};
190 
191  // When referencing a value before its declaration, a temporary value is
192  // created, which will later be RAUWed with the actual value. This reverses
193  // the use list. This happens for all values apart from basic blocks.
194  bool GetsReversed = !isa<BasicBlock>(V);
195  if (auto *BA = dyn_cast<BlockAddress>(V))
196  ID = OM.lookup(BA->getBasicBlock());
197  llvm::sort(List, [&](const Entry &L, const Entry &R) {
198  const Use *LU = L.first;
199  const Use *RU = R.first;
200  if (LU == RU)
201  return false;
202 
203  auto LID = OM.lookup(LU->getUser());
204  auto RID = OM.lookup(RU->getUser());
205 
206  // If ID is 4, then expect: 7 6 5 1 2 3.
207  if (LID < RID) {
208  if (GetsReversed)
209  if (RID <= ID)
210  return true;
211  return false;
212  }
213  if (RID < LID) {
214  if (GetsReversed)
215  if (LID <= ID)
216  return false;
217  return true;
218  }
219 
220  // LID and RID are equal, so we have different operands of the same user.
221  // Assume operands are added in order for all instructions.
222  if (GetsReversed)
223  if (LID <= ID)
224  return LU->getOperandNo() < RU->getOperandNo();
225  return LU->getOperandNo() > RU->getOperandNo();
226  });
227 
229  // Order is already correct.
230  return {};
231 
232  // Store the shuffle.
233  std::vector<unsigned> Shuffle(List.size());
234  for (size_t I = 0, E = List.size(); I != E; ++I)
235  Shuffle[I] = List[I].second;
236  return Shuffle;
237 }
238 
240  OrderMap OM = orderModule(M);
241  UseListOrderMap ULOM;
242  for (const auto &Pair : OM) {
243  const Value *V = Pair.first;
244  if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
245  continue;
246 
247  std::vector<unsigned> Shuffle =
248  predictValueUseListOrder(V, Pair.second, OM);
249  if (Shuffle.empty())
250  continue;
251 
252  const Function *F = nullptr;
253  if (auto *I = dyn_cast<Instruction>(V))
254  F = I->getFunction();
255  if (auto *A = dyn_cast<Argument>(V))
256  F = A->getParent();
257  if (auto *BB = dyn_cast<BasicBlock>(V))
258  F = BB->getParent();
259  ULOM[F][V] = std::move(Shuffle);
260  }
261  return ULOM;
262 }
263 
264 static const Module *getModuleFromVal(const Value *V) {
265  if (const Argument *MA = dyn_cast<Argument>(V))
266  return MA->getParent() ? MA->getParent()->getParent() : nullptr;
267 
268  if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
269  return BB->getParent() ? BB->getParent()->getParent() : nullptr;
270 
271  if (const Instruction *I = dyn_cast<Instruction>(V)) {
272  const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
273  return M ? M->getParent() : nullptr;
274  }
275 
276  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
277  return GV->getParent();
278 
279  if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
280  for (const User *U : MAV->users())
281  if (isa<Instruction>(U))
282  if (const Module *M = getModuleFromVal(U))
283  return M;
284  return nullptr;
285  }
286 
287  return nullptr;
288 }
289 
290 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
291  switch (cc) {
292  default: Out << "cc" << cc; break;
293  case CallingConv::Fast: Out << "fastcc"; break;
294  case CallingConv::Cold: Out << "coldcc"; break;
295  case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
296  case CallingConv::AnyReg: Out << "anyregcc"; break;
297  case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
298  case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
299  case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
300  case CallingConv::GHC: Out << "ghccc"; break;
301  case CallingConv::Tail: Out << "tailcc"; break;
302  case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
303  case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
304  case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
305  case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
306  case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
307  case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
308  case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
309  case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
310  case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
311  case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
312  case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
314  Out << "aarch64_sve_vector_pcs";
315  break;
317  Out << "aarch64_sme_preservemost_from_x0";
318  break;
320  Out << "aarch64_sme_preservemost_from_x2";
321  break;
322  case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
323  case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
324  case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
325  case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
326  case CallingConv::PTX_Device: Out << "ptx_device"; break;
327  case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
328  case CallingConv::Win64: Out << "win64cc"; break;
329  case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
330  case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
331  case CallingConv::Swift: Out << "swiftcc"; break;
332  case CallingConv::SwiftTail: Out << "swifttailcc"; break;
333  case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
334  case CallingConv::HHVM: Out << "hhvmcc"; break;
335  case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
336  case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
337  case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
338  case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
339  case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
340  case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
341  case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
342  case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
343  case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
344  case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break;
345  }
346 }
347 
354 };
355 
357  assert(!Name.empty() && "Cannot get empty name!");
358 
359  // Scan the name to see if it needs quotes first.
360  bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
361  if (!NeedsQuotes) {
362  for (unsigned char C : Name) {
363  // By making this unsigned, the value passed in to isalnum will always be
364  // in the range 0-255. This is important when building with MSVC because
365  // its implementation will assert. This situation can arise when dealing
366  // with UTF-8 multibyte characters.
367  if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
368  C != '_') {
369  NeedsQuotes = true;
370  break;
371  }
372  }
373  }
374 
375  // If we didn't need any quotes, just write out the name in one blast.
376  if (!NeedsQuotes) {
377  OS << Name;
378  return;
379  }
380 
381  // Okay, we need quotes. Output the quotes and escape any scary characters as
382  // needed.
383  OS << '"';
384  printEscapedString(Name, OS);
385  OS << '"';
386 }
387 
388 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
389 /// (if the string only contains simple characters) or is surrounded with ""'s
390 /// (if it has special chars in it). Print it out.
392  switch (Prefix) {
393  case NoPrefix:
394  break;
395  case GlobalPrefix:
396  OS << '@';
397  break;
398  case ComdatPrefix:
399  OS << '$';
400  break;
401  case LabelPrefix:
402  break;
403  case LocalPrefix:
404  OS << '%';
405  break;
406  }
407  printLLVMNameWithoutPrefix(OS, Name);
408 }
409 
410 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
411 /// (if the string only contains simple characters) or is surrounded with ""'s
412 /// (if it has special chars in it). Print it out.
413 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
414  PrintLLVMName(OS, V->getName(),
415  isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
416 }
417 
419  Out << ", <";
420  if (isa<ScalableVectorType>(Ty))
421  Out << "vscale x ";
422  Out << Mask.size() << " x i32> ";
423  bool FirstElt = true;
424  if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
425  Out << "zeroinitializer";
426  } else if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
427  Out << "undef";
428  } else {
429  Out << "<";
430  for (int Elt : Mask) {
431  if (FirstElt)
432  FirstElt = false;
433  else
434  Out << ", ";
435  Out << "i32 ";
436  if (Elt == UndefMaskElem)
437  Out << "undef";
438  else
439  Out << Elt;
440  }
441  Out << ">";
442  }
443 }
444 
445 namespace {
446 
447 class TypePrinting {
448 public:
449  TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
450 
451  TypePrinting(const TypePrinting &) = delete;
452  TypePrinting &operator=(const TypePrinting &) = delete;
453 
454  /// The named types that are used by the current module.
455  TypeFinder &getNamedTypes();
456 
457  /// The numbered types, number to type mapping.
458  std::vector<StructType *> &getNumberedTypes();
459 
460  bool empty();
461 
462  void print(Type *Ty, raw_ostream &OS);
463 
464  void printStructBody(StructType *Ty, raw_ostream &OS);
465 
466 private:
467  void incorporateTypes();
468 
469  /// A module to process lazily when needed. Set to nullptr as soon as used.
470  const Module *DeferredM;
471 
472  TypeFinder NamedTypes;
473 
474  // The numbered types, along with their value.
476 
477  std::vector<StructType *> NumberedTypes;
478 };
479 
480 } // end anonymous namespace
481 
482 TypeFinder &TypePrinting::getNamedTypes() {
483  incorporateTypes();
484  return NamedTypes;
485 }
486 
487 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
488  incorporateTypes();
489 
490  // We know all the numbers that each type is used and we know that it is a
491  // dense assignment. Convert the map to an index table, if it's not done
492  // already (judging from the sizes):
493  if (NumberedTypes.size() == Type2Number.size())
494  return NumberedTypes;
495 
496  NumberedTypes.resize(Type2Number.size());
497  for (const auto &P : Type2Number) {
498  assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
499  assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
500  NumberedTypes[P.second] = P.first;
501  }
502  return NumberedTypes;
503 }
504 
505 bool TypePrinting::empty() {
506  incorporateTypes();
507  return NamedTypes.empty() && Type2Number.empty();
508 }
509 
510 void TypePrinting::incorporateTypes() {
511  if (!DeferredM)
512  return;
513 
514  NamedTypes.run(*DeferredM, false);
515  DeferredM = nullptr;
516 
517  // The list of struct types we got back includes all the struct types, split
518  // the unnamed ones out to a numbering and remove the anonymous structs.
519  unsigned NextNumber = 0;
520 
521  std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
522  for (StructType *STy : NamedTypes) {
523  // Ignore anonymous types.
524  if (STy->isLiteral())
525  continue;
526 
527  if (STy->getName().empty())
528  Type2Number[STy] = NextNumber++;
529  else
530  *NextToUse++ = STy;
531  }
532 
533  NamedTypes.erase(NextToUse, NamedTypes.end());
534 }
535 
536 /// Write the specified type to the specified raw_ostream, making use of type
537 /// names or up references to shorten the type name where possible.
538 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
539  switch (Ty->getTypeID()) {
540  case Type::VoidTyID: OS << "void"; return;
541  case Type::HalfTyID: OS << "half"; return;
542  case Type::BFloatTyID: OS << "bfloat"; return;
543  case Type::FloatTyID: OS << "float"; return;
544  case Type::DoubleTyID: OS << "double"; return;
545  case Type::X86_FP80TyID: OS << "x86_fp80"; return;
546  case Type::FP128TyID: OS << "fp128"; return;
547  case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
548  case Type::LabelTyID: OS << "label"; return;
549  case Type::MetadataTyID: OS << "metadata"; return;
550  case Type::X86_MMXTyID: OS << "x86_mmx"; return;
551  case Type::X86_AMXTyID: OS << "x86_amx"; return;
552  case Type::TokenTyID: OS << "token"; return;
553  case Type::IntegerTyID:
554  OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
555  return;
556 
557  case Type::FunctionTyID: {
558  FunctionType *FTy = cast<FunctionType>(Ty);
559  print(FTy->getReturnType(), OS);
560  OS << " (";
561  ListSeparator LS;
562  for (Type *Ty : FTy->params()) {
563  OS << LS;
564  print(Ty, OS);
565  }
566  if (FTy->isVarArg())
567  OS << LS << "...";
568  OS << ')';
569  return;
570  }
571  case Type::StructTyID: {
572  StructType *STy = cast<StructType>(Ty);
573 
574  if (STy->isLiteral())
575  return printStructBody(STy, OS);
576 
577  if (!STy->getName().empty())
578  return PrintLLVMName(OS, STy->getName(), LocalPrefix);
579 
580  incorporateTypes();
581  const auto I = Type2Number.find(STy);
582  if (I != Type2Number.end())
583  OS << '%' << I->second;
584  else // Not enumerated, print the hex address.
585  OS << "%\"type " << STy << '\"';
586  return;
587  }
588  case Type::PointerTyID: {
589  PointerType *PTy = cast<PointerType>(Ty);
590  if (PTy->isOpaque()) {
591  OS << "ptr";
592  if (unsigned AddressSpace = PTy->getAddressSpace())
593  OS << " addrspace(" << AddressSpace << ')';
594  return;
595  }
597  if (unsigned AddressSpace = PTy->getAddressSpace())
598  OS << " addrspace(" << AddressSpace << ')';
599  OS << '*';
600  return;
601  }
602  case Type::ArrayTyID: {
603  ArrayType *ATy = cast<ArrayType>(Ty);
604  OS << '[' << ATy->getNumElements() << " x ";
605  print(ATy->getElementType(), OS);
606  OS << ']';
607  return;
608  }
611  VectorType *PTy = cast<VectorType>(Ty);
613  OS << "<";
614  if (EC.isScalable())
615  OS << "vscale x ";
616  OS << EC.getKnownMinValue() << " x ";
617  print(PTy->getElementType(), OS);
618  OS << '>';
619  return;
620  }
621  case Type::TypedPointerTyID: {
622  TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
623  OS << "typedptr(" << *TPTy->getElementType() << ", "
624  << TPTy->getAddressSpace() << ")";
625  return;
626  }
627  }
628  llvm_unreachable("Invalid TypeID");
629 }
630 
631 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
632  if (STy->isOpaque()) {
633  OS << "opaque";
634  return;
635  }
636 
637  if (STy->isPacked())
638  OS << '<';
639 
640  if (STy->getNumElements() == 0) {
641  OS << "{}";
642  } else {
643  OS << "{ ";
644  ListSeparator LS;
645  for (Type *Ty : STy->elements()) {
646  OS << LS;
647  print(Ty, OS);
648  }
649 
650  OS << " }";
651  }
652  if (STy->isPacked())
653  OS << '>';
654 }
655 
656 AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
657 
658 namespace llvm {
659 
660 //===----------------------------------------------------------------------===//
661 // SlotTracker Class: Enumerate slot numbers for unnamed values
662 //===----------------------------------------------------------------------===//
663 /// This class provides computation of slot numbers for LLVM Assembly writing.
664 ///
665 class SlotTracker : public AbstractSlotTrackerStorage {
666 public:
667  /// ValueMap - A mapping of Values to slot numbers.
668  using ValueMap = DenseMap<const Value *, unsigned>;
669 
670 private:
671  /// TheModule - The module for which we are holding slot numbers.
672  const Module* TheModule;
673 
674  /// TheFunction - The function for which we are holding slot numbers.
675  const Function* TheFunction = nullptr;
676  bool FunctionProcessed = false;
677  bool ShouldInitializeAllMetadata;
678 
679  std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
680  ProcessModuleHookFn;
681  std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
682  ProcessFunctionHookFn;
683 
684  /// The summary index for which we are holding slot numbers.
685  const ModuleSummaryIndex *TheIndex = nullptr;
686 
687  /// mMap - The slot map for the module level data.
688  ValueMap mMap;
689  unsigned mNext = 0;
690 
691  /// fMap - The slot map for the function level data.
692  ValueMap fMap;
693  unsigned fNext = 0;
694 
695  /// mdnMap - Map for MDNodes.
696  DenseMap<const MDNode*, unsigned> mdnMap;
697  unsigned mdnNext = 0;
698 
699  /// asMap - The slot map for attribute sets.
700  DenseMap<AttributeSet, unsigned> asMap;
701  unsigned asNext = 0;
702 
703  /// ModulePathMap - The slot map for Module paths used in the summary index.
704  StringMap<unsigned> ModulePathMap;
705  unsigned ModulePathNext = 0;
706 
707  /// GUIDMap - The slot map for GUIDs used in the summary index.
708  DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
709  unsigned GUIDNext = 0;
710 
711  /// TypeIdMap - The slot map for type ids used in the summary index.
712  StringMap<unsigned> TypeIdMap;
713  unsigned TypeIdNext = 0;
714 
715 public:
716  /// Construct from a module.
717  ///
718  /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
719  /// functions, giving correct numbering for metadata referenced only from
720  /// within a function (even if no functions have been initialized).
721  explicit SlotTracker(const Module *M,
722  bool ShouldInitializeAllMetadata = false);
723 
724  /// Construct from a function, starting out in incorp state.
725  ///
726  /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
727  /// functions, giving correct numbering for metadata referenced only from
728  /// within a function (even if no functions have been initialized).
729  explicit SlotTracker(const Function *F,
730  bool ShouldInitializeAllMetadata = false);
731 
732  /// Construct from a module summary index.
733  explicit SlotTracker(const ModuleSummaryIndex *Index);
734 
735  SlotTracker(const SlotTracker &) = delete;
736  SlotTracker &operator=(const SlotTracker &) = delete;
737 
738  ~SlotTracker() = default;
739 
740  void setProcessHook(
741  std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
742  void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
743  const Function *, bool)>);
744 
745  unsigned getNextMetadataSlot() override { return mdnNext; }
746 
747  void createMetadataSlot(const MDNode *N) override;
748 
749  /// Return the slot number of the specified value in it's type
750  /// plane. If something is not in the SlotTracker, return -1.
751  int getLocalSlot(const Value *V);
752  int getGlobalSlot(const GlobalValue *V);
753  int getMetadataSlot(const MDNode *N) override;
754  int getAttributeGroupSlot(AttributeSet AS);
755  int getModulePathSlot(StringRef Path);
756  int getGUIDSlot(GlobalValue::GUID GUID);
757  int getTypeIdSlot(StringRef Id);
758 
759  /// If you'd like to deal with a function instead of just a module, use
760  /// this method to get its data into the SlotTracker.
761  void incorporateFunction(const Function *F) {
762  TheFunction = F;
763  FunctionProcessed = false;
764  }
765 
766  const Function *getFunction() const { return TheFunction; }
767 
768  /// After calling incorporateFunction, use this method to remove the
769  /// most recently incorporated function from the SlotTracker. This
770  /// will reset the state of the machine back to just the module contents.
771  void purgeFunction();
772 
773  /// MDNode map iterators.
774  using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
775 
776  mdn_iterator mdn_begin() { return mdnMap.begin(); }
777  mdn_iterator mdn_end() { return mdnMap.end(); }
778  unsigned mdn_size() const { return mdnMap.size(); }
779  bool mdn_empty() const { return mdnMap.empty(); }
780 
781  /// AttributeSet map iterators.
782  using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
783 
784  as_iterator as_begin() { return asMap.begin(); }
785  as_iterator as_end() { return asMap.end(); }
786  unsigned as_size() const { return asMap.size(); }
787  bool as_empty() const { return asMap.empty(); }
788 
789  /// GUID map iterators.
790  using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
791 
792  /// These functions do the actual initialization.
793  inline void initializeIfNeeded();
794  int initializeIndexIfNeeded();
795 
796  // Implementation Details
797 private:
798  /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
799  void CreateModuleSlot(const GlobalValue *V);
800 
801  /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
802  void CreateMetadataSlot(const MDNode *N);
803 
804  /// CreateFunctionSlot - Insert the specified Value* into the slot table.
805  void CreateFunctionSlot(const Value *V);
806 
807  /// Insert the specified AttributeSet into the slot table.
808  void CreateAttributeSetSlot(AttributeSet AS);
809 
810  inline void CreateModulePathSlot(StringRef Path);
811  void CreateGUIDSlot(GlobalValue::GUID GUID);
812  void CreateTypeIdSlot(StringRef Id);
813 
814  /// Add all of the module level global variables (and their initializers)
815  /// and function declarations, but not the contents of those functions.
816  void processModule();
817  // Returns number of allocated slots
818  int processIndex();
819 
820  /// Add all of the functions arguments, basic blocks, and instructions.
821  void processFunction();
822 
823  /// Add the metadata directly attached to a GlobalObject.
824  void processGlobalObjectMetadata(const GlobalObject &GO);
825 
826  /// Add all of the metadata from a function.
827  void processFunctionMetadata(const Function &F);
828 
829  /// Add all of the metadata from an instruction.
830  void processInstructionMetadata(const Instruction &I);
831 };
832 
833 } // end namespace llvm
834 
835 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
836  const Function *F)
837  : M(M), F(F), Machine(&Machine) {}
838 
839 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
840  bool ShouldInitializeAllMetadata)
841  : ShouldCreateStorage(M),
842  ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
843 
844 ModuleSlotTracker::~ModuleSlotTracker() = default;
845 
846 SlotTracker *ModuleSlotTracker::getMachine() {
847  if (!ShouldCreateStorage)
848  return Machine;
849 
850  ShouldCreateStorage = false;
851  MachineStorage =
852  std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
853  Machine = MachineStorage.get();
854  if (ProcessModuleHookFn)
855  Machine->setProcessHook(ProcessModuleHookFn);
856  if (ProcessFunctionHookFn)
857  Machine->setProcessHook(ProcessFunctionHookFn);
858  return Machine;
859 }
860 
861 void ModuleSlotTracker::incorporateFunction(const Function &F) {
862  // Using getMachine() may lazily create the slot tracker.
863  if (!getMachine())
864  return;
865 
866  // Nothing to do if this is the right function already.
867  if (this->F == &F)
868  return;
869  if (this->F)
870  Machine->purgeFunction();
871  Machine->incorporateFunction(&F);
872  this->F = &F;
873 }
874 
875 int ModuleSlotTracker::getLocalSlot(const Value *V) {
876  assert(F && "No function incorporated");
877  return Machine->getLocalSlot(V);
878 }
879 
880 void ModuleSlotTracker::setProcessHook(
881  std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
882  Fn) {
883  ProcessModuleHookFn = Fn;
884 }
885 
886 void ModuleSlotTracker::setProcessHook(
887  std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
888  Fn) {
889  ProcessFunctionHookFn = Fn;
890 }
891 
892 static SlotTracker *createSlotTracker(const Value *V) {
893  if (const Argument *FA = dyn_cast<Argument>(V))
894  return new SlotTracker(FA->getParent());
895 
896  if (const Instruction *I = dyn_cast<Instruction>(V))
897  if (I->getParent())
898  return new SlotTracker(I->getParent()->getParent());
899 
900  if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
901  return new SlotTracker(BB->getParent());
902 
903  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
904  return new SlotTracker(GV->getParent());
905 
906  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
907  return new SlotTracker(GA->getParent());
908 
909  if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
910  return new SlotTracker(GIF->getParent());
911 
912  if (const Function *Func = dyn_cast<Function>(V))
913  return new SlotTracker(Func);
914 
915  return nullptr;
916 }
917 
918 #if 0
919 #define ST_DEBUG(X) dbgs() << X
920 #else
921 #define ST_DEBUG(X)
922 #endif
923 
924 // Module level constructor. Causes the contents of the Module (sans functions)
925 // to be added to the slot table.
926 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
927  : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
928 
929 // Function level constructor. Causes the contents of the Module and the one
930 // function provided to be added to the slot table.
931 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
932  : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
933  ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
934 
935 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
936  : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
937 
938 inline void SlotTracker::initializeIfNeeded() {
939  if (TheModule) {
940  processModule();
941  TheModule = nullptr; ///< Prevent re-processing next time we're called.
942  }
943 
944  if (TheFunction && !FunctionProcessed)
945  processFunction();
946 }
947 
949  if (!TheIndex)
950  return 0;
951  int NumSlots = processIndex();
952  TheIndex = nullptr; ///< Prevent re-processing next time we're called.
953  return NumSlots;
954 }
955 
956 // Iterate through all the global variables, functions, and global
957 // variable initializers and create slots for them.
958 void SlotTracker::processModule() {
959  ST_DEBUG("begin processModule!\n");
960 
961  // Add all of the unnamed global variables to the value table.
962  for (const GlobalVariable &Var : TheModule->globals()) {
963  if (!Var.hasName())
964  CreateModuleSlot(&Var);
965  processGlobalObjectMetadata(Var);
966  auto Attrs = Var.getAttributes();
967  if (Attrs.hasAttributes())
968  CreateAttributeSetSlot(Attrs);
969  }
970 
971  for (const GlobalAlias &A : TheModule->aliases()) {
972  if (!A.hasName())
973  CreateModuleSlot(&A);
974  }
975 
976  for (const GlobalIFunc &I : TheModule->ifuncs()) {
977  if (!I.hasName())
978  CreateModuleSlot(&I);
979  }
980 
981  // Add metadata used by named metadata.
982  for (const NamedMDNode &NMD : TheModule->named_metadata()) {
983  for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
984  CreateMetadataSlot(NMD.getOperand(i));
985  }
986 
987  for (const Function &F : *TheModule) {
988  if (!F.hasName())
989  // Add all the unnamed functions to the table.
990  CreateModuleSlot(&F);
991 
992  if (ShouldInitializeAllMetadata)
993  processFunctionMetadata(F);
994 
995  // Add all the function attributes to the table.
996  // FIXME: Add attributes of other objects?
997  AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
998  if (FnAttrs.hasAttributes())
999  CreateAttributeSetSlot(FnAttrs);
1000  }
1001 
1002  if (ProcessModuleHookFn)
1003  ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
1004 
1005  ST_DEBUG("end processModule!\n");
1006 }
1007 
1008 // Process the arguments, basic blocks, and instructions of a function.
1009 void SlotTracker::processFunction() {
1010  ST_DEBUG("begin processFunction!\n");
1011  fNext = 0;
1012 
1013  // Process function metadata if it wasn't hit at the module-level.
1014  if (!ShouldInitializeAllMetadata)
1015  processFunctionMetadata(*TheFunction);
1016 
1017  // Add all the function arguments with no names.
1018  for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1019  AE = TheFunction->arg_end(); AI != AE; ++AI)
1020  if (!AI->hasName())
1021  CreateFunctionSlot(&*AI);
1022 
1023  ST_DEBUG("Inserting Instructions:\n");
1024 
1025  // Add all of the basic blocks and instructions with no names.
1026  for (auto &BB : *TheFunction) {
1027  if (!BB.hasName())
1028  CreateFunctionSlot(&BB);
1029 
1030  for (auto &I : BB) {
1031  if (!I.getType()->isVoidTy() && !I.hasName())
1032  CreateFunctionSlot(&I);
1033 
1034  // We allow direct calls to any llvm.foo function here, because the
1035  // target may not be linked into the optimizer.
1036  if (const auto *Call = dyn_cast<CallBase>(&I)) {
1037  // Add all the call attributes to the table.
1038  AttributeSet Attrs = Call->getAttributes().getFnAttrs();
1039  if (Attrs.hasAttributes())
1040  CreateAttributeSetSlot(Attrs);
1041  }
1042  }
1043  }
1044 
1045  if (ProcessFunctionHookFn)
1046  ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
1047 
1048  FunctionProcessed = true;
1049 
1050  ST_DEBUG("end processFunction!\n");
1051 }
1052 
1053 // Iterate through all the GUID in the index and create slots for them.
1054 int SlotTracker::processIndex() {
1055  ST_DEBUG("begin processIndex!\n");
1056  assert(TheIndex);
1057 
1058  // The first block of slots are just the module ids, which start at 0 and are
1059  // assigned consecutively. Since the StringMap iteration order isn't
1060  // guaranteed, use a std::map to order by module ID before assigning slots.
1061  std::map<uint64_t, StringRef> ModuleIdToPathMap;
1062  for (auto &ModPath : TheIndex->modulePaths())
1063  ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1064  for (auto &ModPair : ModuleIdToPathMap)
1065  CreateModulePathSlot(ModPair.second);
1066 
1067  // Start numbering the GUIDs after the module ids.
1068  GUIDNext = ModulePathNext;
1069 
1070  for (auto &GlobalList : *TheIndex)
1071  CreateGUIDSlot(GlobalList.first);
1072 
1073  for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1074  CreateGUIDSlot(GlobalValue::getGUID(TId.first));
1075 
1076  // Start numbering the TypeIds after the GUIDs.
1077  TypeIdNext = GUIDNext;
1078  for (const auto &TID : TheIndex->typeIds())
1079  CreateTypeIdSlot(TID.second.first);
1080 
1081  ST_DEBUG("end processIndex!\n");
1082  return TypeIdNext;
1083 }
1084 
1085 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1087  GO.getAllMetadata(MDs);
1088  for (auto &MD : MDs)
1089  CreateMetadataSlot(MD.second);
1090 }
1091 
1092 void SlotTracker::processFunctionMetadata(const Function &F) {
1093  processGlobalObjectMetadata(F);
1094  for (auto &BB : F) {
1095  for (auto &I : BB)
1096  processInstructionMetadata(I);
1097  }
1098 }
1099 
1100 void SlotTracker::processInstructionMetadata(const Instruction &I) {
1101  // Process metadata used directly by intrinsics.
1102  if (const CallInst *CI = dyn_cast<CallInst>(&I))
1103  if (Function *F = CI->getCalledFunction())
1104  if (F->isIntrinsic())
1105  for (auto &Op : I.operands())
1106  if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1107  if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1108  CreateMetadataSlot(N);
1109 
1110  // Process metadata attached to this instruction.
1112  I.getAllMetadata(MDs);
1113  for (auto &MD : MDs)
1114  CreateMetadataSlot(MD.second);
1115 }
1116 
1117 /// Clean up after incorporating a function. This is the only way to get out of
1118 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1119 /// incorporation state is indicated by TheFunction != 0.
1121  ST_DEBUG("begin purgeFunction!\n");
1122  fMap.clear(); // Simply discard the function level map
1123  TheFunction = nullptr;
1124  FunctionProcessed = false;
1125  ST_DEBUG("end purgeFunction!\n");
1126 }
1127 
1128 /// getGlobalSlot - Get the slot number of a global value.
1130  // Check for uninitialized state and do lazy initialization.
1132 
1133  // Find the value in the module map
1134  ValueMap::iterator MI = mMap.find(V);
1135  return MI == mMap.end() ? -1 : (int)MI->second;
1136 }
1137 
1139  std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
1140  Fn) {
1141  ProcessModuleHookFn = Fn;
1142 }
1143 
1145  std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
1146  Fn) {
1147  ProcessFunctionHookFn = Fn;
1148 }
1149 
1150 /// getMetadataSlot - Get the slot number of a MDNode.
1151 void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
1152 
1153 /// getMetadataSlot - Get the slot number of a MDNode.
1155  // Check for uninitialized state and do lazy initialization.
1157 
1158  // Find the MDNode in the module map
1159  mdn_iterator MI = mdnMap.find(N);
1160  return MI == mdnMap.end() ? -1 : (int)MI->second;
1161 }
1162 
1163 /// getLocalSlot - Get the slot number for a value that is local to a function.
1165  assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1166 
1167  // Check for uninitialized state and do lazy initialization.
1169 
1170  ValueMap::iterator FI = fMap.find(V);
1171  return FI == fMap.end() ? -1 : (int)FI->second;
1172 }
1173 
1175  // Check for uninitialized state and do lazy initialization.
1177 
1178  // Find the AttributeSet in the module map.
1179  as_iterator AI = asMap.find(AS);
1180  return AI == asMap.end() ? -1 : (int)AI->second;
1181 }
1182 
1184  // Check for uninitialized state and do lazy initialization.
1186 
1187  // Find the Module path in the map
1188  auto I = ModulePathMap.find(Path);
1189  return I == ModulePathMap.end() ? -1 : (int)I->second;
1190 }
1191 
1193  // Check for uninitialized state and do lazy initialization.
1195 
1196  // Find the GUID in the map
1197  guid_iterator I = GUIDMap.find(GUID);
1198  return I == GUIDMap.end() ? -1 : (int)I->second;
1199 }
1200 
1202  // Check for uninitialized state and do lazy initialization.
1204 
1205  // Find the TypeId string in the map
1206  auto I = TypeIdMap.find(Id);
1207  return I == TypeIdMap.end() ? -1 : (int)I->second;
1208 }
1209 
1210 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1211 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1212  assert(V && "Can't insert a null Value into SlotTracker!");
1213  assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1214  assert(!V->hasName() && "Doesn't need a slot!");
1215 
1216  unsigned DestSlot = mNext++;
1217  mMap[V] = DestSlot;
1218 
1219  ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1220  DestSlot << " [");
1221  // G = Global, F = Function, A = Alias, I = IFunc, o = other
1222  ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1223  (isa<Function>(V) ? 'F' :
1224  (isa<GlobalAlias>(V) ? 'A' :
1225  (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1226 }
1227 
1228 /// CreateSlot - Create a new slot for the specified value if it has no name.
1229 void SlotTracker::CreateFunctionSlot(const Value *V) {
1230  assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1231 
1232  unsigned DestSlot = fNext++;
1233  fMap[V] = DestSlot;
1234 
1235  // G = Global, F = Function, o = other
1236  ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1237  DestSlot << " [o]\n");
1238 }
1239 
1240 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1241 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1242  assert(N && "Can't insert a null Value into SlotTracker!");
1243 
1244  // Don't make slots for DIExpressions or DIArgLists. We just print them inline
1245  // everywhere.
1246  if (isa<DIExpression>(N) || isa<DIArgList>(N))
1247  return;
1248 
1249  unsigned DestSlot = mdnNext;
1250  if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1251  return;
1252  ++mdnNext;
1253 
1254  // Recursively add any MDNodes referenced by operands.
1255  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1256  if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1257  CreateMetadataSlot(Op);
1258 }
1259 
1260 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1261  assert(AS.hasAttributes() && "Doesn't need a slot!");
1262 
1263  as_iterator I = asMap.find(AS);
1264  if (I != asMap.end())
1265  return;
1266 
1267  unsigned DestSlot = asNext++;
1268  asMap[AS] = DestSlot;
1269 }
1270 
1271 /// Create a new slot for the specified Module
1272 void SlotTracker::CreateModulePathSlot(StringRef Path) {
1273  ModulePathMap[Path] = ModulePathNext++;
1274 }
1275 
1276 /// Create a new slot for the specified GUID
1277 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1278  GUIDMap[GUID] = GUIDNext++;
1279 }
1280 
1281 /// Create a new slot for the specified Id
1282 void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1283  TypeIdMap[Id] = TypeIdNext++;
1284 }
1285 
1286 namespace {
1287 /// Common instances used by most of the printer functions.
1288 struct AsmWriterContext {
1289  TypePrinting *TypePrinter = nullptr;
1290  SlotTracker *Machine = nullptr;
1291  const Module *Context = nullptr;
1292 
1293  AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
1294  : TypePrinter(TP), Machine(ST), Context(M) {}
1295 
1296  static AsmWriterContext &getEmpty() {
1297  static AsmWriterContext EmptyCtx(nullptr, nullptr);
1298  return EmptyCtx;
1299  }
1300 
1301  /// A callback that will be triggered when the underlying printer
1302  /// prints a Metadata as operand.
1303  virtual void onWriteMetadataAsOperand(const Metadata *) {}
1304 
1305  virtual ~AsmWriterContext() = default;
1306 };
1307 } // end anonymous namespace
1308 
1309 //===----------------------------------------------------------------------===//
1310 // AsmWriter Implementation
1311 //===----------------------------------------------------------------------===//
1312 
1313 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1314  AsmWriterContext &WriterCtx);
1315 
1316 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1317  AsmWriterContext &WriterCtx,
1318  bool FromValue = false);
1319 
1320 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1321  if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
1322  Out << FPO->getFastMathFlags();
1323 
1324  if (const OverflowingBinaryOperator *OBO =
1325  dyn_cast<OverflowingBinaryOperator>(U)) {
1326  if (OBO->hasNoUnsignedWrap())
1327  Out << " nuw";
1328  if (OBO->hasNoSignedWrap())
1329  Out << " nsw";
1330  } else if (const PossiblyExactOperator *Div =
1331  dyn_cast<PossiblyExactOperator>(U)) {
1332  if (Div->isExact())
1333  Out << " exact";
1334  } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1335  if (GEP->isInBounds())
1336  Out << " inbounds";
1337  }
1338 }
1339 
1340 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1341  AsmWriterContext &WriterCtx) {
1342  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1343  if (CI->getType()->isIntegerTy(1)) {
1344  Out << (CI->getZExtValue() ? "true" : "false");
1345  return;
1346  }
1347  Out << CI->getValue();
1348  return;
1349  }
1350 
1351  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1352  const APFloat &APF = CFP->getValueAPF();
1353  if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1354  &APF.getSemantics() == &APFloat::IEEEdouble()) {
1355  // We would like to output the FP constant value in exponential notation,
1356  // but we cannot do this if doing so will lose precision. Check here to
1357  // make sure that we only output it in exponential format if we can parse
1358  // the value back and get the same value.
1359  //
1360  bool ignored;
1361  bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1362  bool isInf = APF.isInfinity();
1363  bool isNaN = APF.isNaN();
1364  if (!isInf && !isNaN) {
1365  double Val = APF.convertToDouble();
1367  APF.toString(StrVal, 6, 0, false);
1368  // Check to make sure that the stringized number is not some string like
1369  // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1370  // that the string matches the "[-+]?[0-9]" regex.
1371  //
1372  assert((isDigit(StrVal[0]) || ((StrVal[0] == '-' || StrVal[0] == '+') &&
1373  isDigit(StrVal[1]))) &&
1374  "[-+]?[0-9] regex does not match!");
1375  // Reparse stringized version!
1376  if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1377  Out << StrVal;
1378  return;
1379  }
1380  }
1381  // Otherwise we could not reparse it to exactly the same value, so we must
1382  // output the string in hexadecimal format! Note that loading and storing
1383  // floating point types changes the bits of NaNs on some hosts, notably
1384  // x86, so we must not use these types.
1385  static_assert(sizeof(double) == sizeof(uint64_t),
1386  "assuming that double is 64 bits!");
1387  APFloat apf = APF;
1388  // Floats are represented in ASCII IR as double, convert.
1389  // FIXME: We should allow 32-bit hex float and remove this.
1390  if (!isDouble) {
1391  // A signaling NaN is quieted on conversion, so we need to recreate the
1392  // expected value after convert (quiet bit of the payload is clear).
1393  bool IsSNAN = apf.isSignaling();
1395  &ignored);
1396  if (IsSNAN) {
1397  APInt Payload = apf.bitcastToAPInt();
1399  &Payload);
1400  }
1401  }
1402  Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1403  return;
1404  }
1405 
1406  // Either half, bfloat or some form of long double.
1407  // These appear as a magic letter identifying the type, then a
1408  // fixed number of hex digits.
1409  Out << "0x";
1410  APInt API = APF.bitcastToAPInt();
1411  if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1412  Out << 'K';
1413  Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1414  /*Upper=*/true);
1415  Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1416  /*Upper=*/true);
1417  return;
1418  } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1419  Out << 'L';
1420  Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1421  /*Upper=*/true);
1422  Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1423  /*Upper=*/true);
1424  } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1425  Out << 'M';
1426  Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1427  /*Upper=*/true);
1428  Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1429  /*Upper=*/true);
1430  } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1431  Out << 'H';
1432  Out << format_hex_no_prefix(API.getZExtValue(), 4,
1433  /*Upper=*/true);
1434  } else if (&APF.getSemantics() == &APFloat::BFloat()) {
1435  Out << 'R';
1436  Out << format_hex_no_prefix(API.getZExtValue(), 4,
1437  /*Upper=*/true);
1438  } else
1439  llvm_unreachable("Unsupported floating point type");
1440  return;
1441  }
1442 
1443  if (isa<ConstantAggregateZero>(CV)) {
1444  Out << "zeroinitializer";
1445  return;
1446  }
1447 
1448  if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1449  Out << "blockaddress(";
1450  WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
1451  Out << ", ";
1452  WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
1453  Out << ")";
1454  return;
1455  }
1456 
1457  if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1458  Out << "dso_local_equivalent ";
1459  WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
1460  return;
1461  }
1462 
1463  if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
1464  Out << "no_cfi ";
1465  WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
1466  return;
1467  }
1468 
1469  if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1470  Type *ETy = CA->getType()->getElementType();
1471  Out << '[';
1472  WriterCtx.TypePrinter->print(ETy, Out);
1473  Out << ' ';
1474  WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
1475  for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1476  Out << ", ";
1477  WriterCtx.TypePrinter->print(ETy, Out);
1478  Out << ' ';
1479  WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
1480  }
1481  Out << ']';
1482  return;
1483  }
1484 
1485  if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1486  // As a special case, print the array as a string if it is an array of
1487  // i8 with ConstantInt values.
1488  if (CA->isString()) {
1489  Out << "c\"";
1490  printEscapedString(CA->getAsString(), Out);
1491  Out << '"';
1492  return;
1493  }
1494 
1495  Type *ETy = CA->getType()->getElementType();
1496  Out << '[';
1497  WriterCtx.TypePrinter->print(ETy, Out);
1498  Out << ' ';
1499  WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
1500  for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1501  Out << ", ";
1502  WriterCtx.TypePrinter->print(ETy, Out);
1503  Out << ' ';
1504  WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
1505  }
1506  Out << ']';
1507  return;
1508  }
1509 
1510  if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1511  if (CS->getType()->isPacked())
1512  Out << '<';
1513  Out << '{';
1514  unsigned N = CS->getNumOperands();
1515  if (N) {
1516  Out << ' ';
1517  WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
1518  Out << ' ';
1519 
1520  WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
1521 
1522  for (unsigned i = 1; i < N; i++) {
1523  Out << ", ";
1524  WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
1525  Out << ' ';
1526 
1527  WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
1528  }
1529  Out << ' ';
1530  }
1531 
1532  Out << '}';
1533  if (CS->getType()->isPacked())
1534  Out << '>';
1535  return;
1536  }
1537 
1538  if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1539  auto *CVVTy = cast<FixedVectorType>(CV->getType());
1540  Type *ETy = CVVTy->getElementType();
1541  Out << '<';
1542  WriterCtx.TypePrinter->print(ETy, Out);
1543  Out << ' ';
1544  WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
1545  for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1546  Out << ", ";
1547  WriterCtx.TypePrinter->print(ETy, Out);
1548  Out << ' ';
1549  WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
1550  }
1551  Out << '>';
1552  return;
1553  }
1554 
1555  if (isa<ConstantPointerNull>(CV)) {
1556  Out << "null";
1557  return;
1558  }
1559 
1560  if (isa<ConstantTokenNone>(CV)) {
1561  Out << "none";
1562  return;
1563  }
1564 
1565  if (isa<PoisonValue>(CV)) {
1566  Out << "poison";
1567  return;
1568  }
1569 
1570  if (isa<UndefValue>(CV)) {
1571  Out << "undef";
1572  return;
1573  }
1574 
1575  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1576  Out << CE->getOpcodeName();
1577  WriteOptimizationInfo(Out, CE);
1578  if (CE->isCompare())
1579  Out << ' ' << CmpInst::getPredicateName(
1580  static_cast<CmpInst::Predicate>(CE->getPredicate()));
1581  Out << " (";
1582 
1583  Optional<unsigned> InRangeOp;
1584  if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1585  WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
1586  Out << ", ";
1587  InRangeOp = GEP->getInRangeIndex();
1588  if (InRangeOp)
1589  ++*InRangeOp;
1590  }
1591 
1592  for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1593  if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1594  Out << "inrange ";
1595  WriterCtx.TypePrinter->print((*OI)->getType(), Out);
1596  Out << ' ';
1597  WriteAsOperandInternal(Out, *OI, WriterCtx);
1598  if (OI+1 != CE->op_end())
1599  Out << ", ";
1600  }
1601 
1602  if (CE->isCast()) {
1603  Out << " to ";
1604  WriterCtx.TypePrinter->print(CE->getType(), Out);
1605  }
1606 
1607  if (CE->getOpcode() == Instruction::ShuffleVector)
1608  PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1609 
1610  Out << ')';
1611  return;
1612  }
1613 
1614  Out << "<placeholder or erroneous Constant>";
1615 }
1616 
1617 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1618  AsmWriterContext &WriterCtx) {
1619  Out << "!{";
1620  for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1621  const Metadata *MD = Node->getOperand(mi);
1622  if (!MD)
1623  Out << "null";
1624  else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1625  Value *V = MDV->getValue();
1626  WriterCtx.TypePrinter->print(V->getType(), Out);
1627  Out << ' ';
1628  WriteAsOperandInternal(Out, V, WriterCtx);
1629  } else {
1630  WriteAsOperandInternal(Out, MD, WriterCtx);
1631  WriterCtx.onWriteMetadataAsOperand(MD);
1632  }
1633  if (mi + 1 != me)
1634  Out << ", ";
1635  }
1636 
1637  Out << "}";
1638 }
1639 
1640 namespace {
1641 
1642 struct FieldSeparator {
1643  bool Skip = true;
1644  const char *Sep;
1645 
1646  FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1647 };
1648 
1649 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1650  if (FS.Skip) {
1651  FS.Skip = false;
1652  return OS;
1653  }
1654  return OS << FS.Sep;
1655 }
1656 
1657 struct MDFieldPrinter {
1658  raw_ostream &Out;
1659  FieldSeparator FS;
1660  AsmWriterContext &WriterCtx;
1661 
1662  explicit MDFieldPrinter(raw_ostream &Out)
1663  : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
1664  MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1665  : Out(Out), WriterCtx(Ctx) {}
1666 
1667  void printTag(const DINode *N);
1668  void printMacinfoType(const DIMacroNode *N);
1669  void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1670  void printString(StringRef Name, StringRef Value,
1671  bool ShouldSkipEmpty = true);
1672  void printMetadata(StringRef Name, const Metadata *MD,
1673  bool ShouldSkipNull = true);
1674  template <class IntTy>
1675  void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1676  void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1677  bool ShouldSkipZero);
1678  void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1679  void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1680  void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1681  template <class IntTy, class Stringifier>
1682  void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1683  bool ShouldSkipZero = true);
1684  void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1685  void printNameTableKind(StringRef Name,
1686  DICompileUnit::DebugNameTableKind NTK);
1687 };
1688 
1689 } // end anonymous namespace
1690 
1691 void MDFieldPrinter::printTag(const DINode *N) {
1692  Out << FS << "tag: ";
1693  auto Tag = dwarf::TagString(N->getTag());
1694  if (!Tag.empty())
1695  Out << Tag;
1696  else
1697  Out << N->getTag();
1698 }
1699 
1700 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1701  Out << FS << "type: ";
1702  auto Type = dwarf::MacinfoString(N->getMacinfoType());
1703  if (!Type.empty())
1704  Out << Type;
1705  else
1706  Out << N->getMacinfoType();
1707 }
1708 
1709 void MDFieldPrinter::printChecksum(
1710  const DIFile::ChecksumInfo<StringRef> &Checksum) {
1711  Out << FS << "checksumkind: " << Checksum.getKindAsString();
1712  printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1713 }
1714 
1715 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1716  bool ShouldSkipEmpty) {
1717  if (ShouldSkipEmpty && Value.empty())
1718  return;
1719 
1720  Out << FS << Name << ": \"";
1721  printEscapedString(Value, Out);
1722  Out << "\"";
1723 }
1724 
1725 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1726  AsmWriterContext &WriterCtx) {
1727  if (!MD) {
1728  Out << "null";
1729  return;
1730  }
1731  WriteAsOperandInternal(Out, MD, WriterCtx);
1732  WriterCtx.onWriteMetadataAsOperand(MD);
1733 }
1734 
1735 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1736  bool ShouldSkipNull) {
1737  if (ShouldSkipNull && !MD)
1738  return;
1739 
1740  Out << FS << Name << ": ";
1741  writeMetadataAsOperand(Out, MD, WriterCtx);
1742 }
1743 
1744 template <class IntTy>
1745 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1746  if (ShouldSkipZero && !Int)
1747  return;
1748 
1749  Out << FS << Name << ": " << Int;
1750 }
1751 
1752 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1753  bool IsUnsigned, bool ShouldSkipZero) {
1754  if (ShouldSkipZero && Int.isZero())
1755  return;
1756 
1757  Out << FS << Name << ": ";
1758  Int.print(Out, !IsUnsigned);
1759 }
1760 
1761 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1762  Optional<bool> Default) {
1763  if (Default && Value == *Default)
1764  return;
1765  Out << FS << Name << ": " << (Value ? "true" : "false");
1766 }
1767 
1768 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1769  if (!Flags)
1770  return;
1771 
1772  Out << FS << Name << ": ";
1773 
1774  SmallVector<DINode::DIFlags, 8> SplitFlags;
1775  auto Extra = DINode::splitFlags(Flags, SplitFlags);
1776 
1777  FieldSeparator FlagsFS(" | ");
1778  for (auto F : SplitFlags) {
1779  auto StringF = DINode::getFlagString(F);
1780  assert(!StringF.empty() && "Expected valid flag");
1781  Out << FlagsFS << StringF;
1782  }
1783  if (Extra || SplitFlags.empty())
1784  Out << FlagsFS << Extra;
1785 }
1786 
1787 void MDFieldPrinter::printDISPFlags(StringRef Name,
1788  DISubprogram::DISPFlags Flags) {
1789  // Always print this field, because no flags in the IR at all will be
1790  // interpreted as old-style isDefinition: true.
1791  Out << FS << Name << ": ";
1792 
1793  if (!Flags) {
1794  Out << 0;
1795  return;
1796  }
1797 
1798  SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1799  auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1800 
1801  FieldSeparator FlagsFS(" | ");
1802  for (auto F : SplitFlags) {
1803  auto StringF = DISubprogram::getFlagString(F);
1804  assert(!StringF.empty() && "Expected valid flag");
1805  Out << FlagsFS << StringF;
1806  }
1807  if (Extra || SplitFlags.empty())
1808  Out << FlagsFS << Extra;
1809 }
1810 
1811 void MDFieldPrinter::printEmissionKind(StringRef Name,
1812  DICompileUnit::DebugEmissionKind EK) {
1813  Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1814 }
1815 
1816 void MDFieldPrinter::printNameTableKind(StringRef Name,
1817  DICompileUnit::DebugNameTableKind NTK) {
1818  if (NTK == DICompileUnit::DebugNameTableKind::Default)
1819  return;
1820  Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1821 }
1822 
1823 template <class IntTy, class Stringifier>
1824 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1825  Stringifier toString, bool ShouldSkipZero) {
1826  if (!Value)
1827  return;
1828 
1829  Out << FS << Name << ": ";
1830  auto S = toString(Value);
1831  if (!S.empty())
1832  Out << S;
1833  else
1834  Out << Value;
1835 }
1836 
1837 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1838  AsmWriterContext &WriterCtx) {
1839  Out << "!GenericDINode(";
1840  MDFieldPrinter Printer(Out, WriterCtx);
1841  Printer.printTag(N);
1842  Printer.printString("header", N->getHeader());
1843  if (N->getNumDwarfOperands()) {
1844  Out << Printer.FS << "operands: {";
1845  FieldSeparator IFS;
1846  for (auto &I : N->dwarf_operands()) {
1847  Out << IFS;
1848  writeMetadataAsOperand(Out, I, WriterCtx);
1849  }
1850  Out << "}";
1851  }
1852  Out << ")";
1853 }
1854 
1855 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1856  AsmWriterContext &WriterCtx) {
1857  Out << "!DILocation(";
1858  MDFieldPrinter Printer(Out, WriterCtx);
1859  // Always output the line, since 0 is a relevant and important value for it.
1860  Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1861  Printer.printInt("column", DL->getColumn());
1862  Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1863  Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1864  Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1865  /* Default */ false);
1866  Out << ")";
1867 }
1868 
1869 static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
1870  AsmWriterContext &WriterCtx) {
1871  Out << "!DIAssignID()";
1872  MDFieldPrinter Printer(Out, WriterCtx);
1873 }
1874 
1875 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1876  AsmWriterContext &WriterCtx) {
1877  Out << "!DISubrange(";
1878  MDFieldPrinter Printer(Out, WriterCtx);
1879 
1880  auto *Count = N->getRawCountNode();
1881  if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
1882  auto *CV = cast<ConstantInt>(CE->getValue());
1883  Printer.printInt("count", CV->getSExtValue(),
1884  /* ShouldSkipZero */ false);
1885  } else
1886  Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1887 
1888  // A lowerBound of constant 0 should not be skipped, since it is different
1889  // from an unspecified lower bound (= nullptr).
1890  auto *LBound = N->getRawLowerBound();
1891  if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
1892  auto *LV = cast<ConstantInt>(LE->getValue());
1893  Printer.printInt("lowerBound", LV->getSExtValue(),
1894  /* ShouldSkipZero */ false);
1895  } else
1896  Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1897 
1898  auto *UBound = N->getRawUpperBound();
1899  if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
1900  auto *UV = cast<ConstantInt>(UE->getValue());
1901  Printer.printInt("upperBound", UV->getSExtValue(),
1902  /* ShouldSkipZero */ false);
1903  } else
1904  Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1905 
1906  auto *Stride = N->getRawStride();
1907  if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
1908  auto *SV = cast<ConstantInt>(SE->getValue());
1909  Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
1910  } else
1911  Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1912 
1913  Out << ")";
1914 }
1915 
1916 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1917  AsmWriterContext &WriterCtx) {
1918  Out << "!DIGenericSubrange(";
1919  MDFieldPrinter Printer(Out, WriterCtx);
1920 
1921  auto IsConstant = [&](Metadata *Bound) -> bool {
1922  if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1923  return BE->isConstant() &&
1924  DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1925  *BE->isConstant();
1926  }
1927  return false;
1928  };
1929 
1930  auto GetConstant = [&](Metadata *Bound) -> int64_t {
1931  assert(IsConstant(Bound) && "Expected constant");
1932  auto *BE = dyn_cast_or_null<DIExpression>(Bound);
1933  return static_cast<int64_t>(BE->getElement(1));
1934  };
1935 
1936  auto *Count = N->getRawCountNode();
1937  if (IsConstant(Count))
1938  Printer.printInt("count", GetConstant(Count),
1939  /* ShouldSkipZero */ false);
1940  else
1941  Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1942 
1943  auto *LBound = N->getRawLowerBound();
1944  if (IsConstant(LBound))
1945  Printer.printInt("lowerBound", GetConstant(LBound),
1946  /* ShouldSkipZero */ false);
1947  else
1948  Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1949 
1950  auto *UBound = N->getRawUpperBound();
1951  if (IsConstant(UBound))
1952  Printer.printInt("upperBound", GetConstant(UBound),
1953  /* ShouldSkipZero */ false);
1954  else
1955  Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1956 
1957  auto *Stride = N->getRawStride();
1958  if (IsConstant(Stride))
1959  Printer.printInt("stride", GetConstant(Stride),
1960  /* ShouldSkipZero */ false);
1961  else
1962  Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1963 
1964  Out << ")";
1965 }
1966 
1967 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1968  AsmWriterContext &) {
1969  Out << "!DIEnumerator(";
1970  MDFieldPrinter Printer(Out);
1971  Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1972  Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
1973  /*ShouldSkipZero=*/false);
1974  if (N->isUnsigned())
1975  Printer.printBool("isUnsigned", true);
1976  Out << ")";
1977 }
1978 
1979 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1980  AsmWriterContext &) {
1981  Out << "!DIBasicType(";
1982  MDFieldPrinter Printer(Out);
1983  if (N->getTag() != dwarf::DW_TAG_base_type)
1984  Printer.printTag(N);
1985  Printer.printString("name", N->getName());
1986  Printer.printInt("size", N->getSizeInBits());
1987  Printer.printInt("align", N->getAlignInBits());
1988  Printer.printDwarfEnum("encoding", N->getEncoding(),
1989  dwarf::AttributeEncodingString);
1990  Printer.printDIFlags("flags", N->getFlags());
1991  Out << ")";
1992 }
1993 
1994 static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
1995  AsmWriterContext &WriterCtx) {
1996  Out << "!DIStringType(";
1997  MDFieldPrinter Printer(Out, WriterCtx);
1998  if (N->getTag() != dwarf::DW_TAG_string_type)
1999  Printer.printTag(N);
2000  Printer.printString("name", N->getName());
2001  Printer.printMetadata("stringLength", N->getRawStringLength());
2002  Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2003  Printer.printMetadata("stringLocationExpression",
2004  N->getRawStringLocationExp());
2005  Printer.printInt("size", N->getSizeInBits());
2006  Printer.printInt("align", N->getAlignInBits());
2007  Printer.printDwarfEnum("encoding", N->getEncoding(),
2008  dwarf::AttributeEncodingString);
2009  Out << ")";
2010 }
2011 
2012 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2013  AsmWriterContext &WriterCtx) {
2014  Out << "!DIDerivedType(";
2015  MDFieldPrinter Printer(Out, WriterCtx);
2016  Printer.printTag(N);
2017  Printer.printString("name", N->getName());
2018  Printer.printMetadata("scope", N->getRawScope());
2019  Printer.printMetadata("file", N->getRawFile());
2020  Printer.printInt("line", N->getLine());
2021  Printer.printMetadata("baseType", N->getRawBaseType(),
2022  /* ShouldSkipNull */ false);
2023  Printer.printInt("size", N->getSizeInBits());
2024  Printer.printInt("align", N->getAlignInBits());
2025  Printer.printInt("offset", N->getOffsetInBits());
2026  Printer.printDIFlags("flags", N->getFlags());
2027  Printer.printMetadata("extraData", N->getRawExtraData());
2028  if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2029  Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2030  /* ShouldSkipZero */ false);
2031  Printer.printMetadata("annotations", N->getRawAnnotations());
2032  Out << ")";
2033 }
2034 
2035 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2036  AsmWriterContext &WriterCtx) {
2037  Out << "!DICompositeType(";
2038  MDFieldPrinter Printer(Out, WriterCtx);
2039  Printer.printTag(N);
2040  Printer.printString("name", N->getName());
2041  Printer.printMetadata("scope", N->getRawScope());
2042  Printer.printMetadata("file", N->getRawFile());
2043  Printer.printInt("line", N->getLine());
2044  Printer.printMetadata("baseType", N->getRawBaseType());
2045  Printer.printInt("size", N->getSizeInBits());
2046  Printer.printInt("align", N->getAlignInBits());
2047  Printer.printInt("offset", N->getOffsetInBits());
2048  Printer.printDIFlags("flags", N->getFlags());
2049  Printer.printMetadata("elements", N->getRawElements());
2050  Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2051  dwarf::LanguageString);
2052  Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2053  Printer.printMetadata("templateParams", N->getRawTemplateParams());
2054  Printer.printString("identifier", N->getIdentifier());
2055  Printer.printMetadata("discriminator", N->getRawDiscriminator());
2056  Printer.printMetadata("dataLocation", N->getRawDataLocation());
2057  Printer.printMetadata("associated", N->getRawAssociated());
2058  Printer.printMetadata("allocated", N->getRawAllocated());
2059  if (auto *RankConst = N->getRankConst())
2060  Printer.printInt("rank", RankConst->getSExtValue(),
2061  /* ShouldSkipZero */ false);
2062  else
2063  Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2064  Printer.printMetadata("annotations", N->getRawAnnotations());
2065  Out << ")";
2066 }
2067 
2068 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2069  AsmWriterContext &WriterCtx) {
2070  Out << "!DISubroutineType(";
2071  MDFieldPrinter Printer(Out, WriterCtx);
2072  Printer.printDIFlags("flags", N->getFlags());
2073  Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2074  Printer.printMetadata("types", N->getRawTypeArray(),
2075  /* ShouldSkipNull */ false);
2076  Out << ")";
2077 }
2078 
2079 static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
2080  Out << "!DIFile(";
2081  MDFieldPrinter Printer(Out);
2082  Printer.printString("filename", N->getFilename(),
2083  /* ShouldSkipEmpty */ false);
2084  Printer.printString("directory", N->getDirectory(),
2085  /* ShouldSkipEmpty */ false);
2086  // Print all values for checksum together, or not at all.
2087  if (N->getChecksum())
2088  Printer.printChecksum(*N->getChecksum());
2089  Printer.printString("source", N->getSource().value_or(StringRef()),
2090  /* ShouldSkipEmpty */ true);
2091  Out << ")";
2092 }
2093 
2094 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2095  AsmWriterContext &WriterCtx) {
2096  Out << "!DICompileUnit(";
2097  MDFieldPrinter Printer(Out, WriterCtx);
2098  Printer.printDwarfEnum("language", N->getSourceLanguage(),
2099  dwarf::LanguageString, /* ShouldSkipZero */ false);
2100  Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2101  Printer.printString("producer", N->getProducer());
2102  Printer.printBool("isOptimized", N->isOptimized());
2103  Printer.printString("flags", N->getFlags());
2104  Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2105  /* ShouldSkipZero */ false);
2106  Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2107  Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2108  Printer.printMetadata("enums", N->getRawEnumTypes());
2109  Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2110  Printer.printMetadata("globals", N->getRawGlobalVariables());
2111  Printer.printMetadata("imports", N->getRawImportedEntities());
2112  Printer.printMetadata("macros", N->getRawMacros());
2113  Printer.printInt("dwoId", N->getDWOId());
2114  Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2115  Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2116  false);
2117  Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2118  Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2119  Printer.printString("sysroot", N->getSysRoot());
2120  Printer.printString("sdk", N->getSDK());
2121  Out << ")";
2122 }
2123 
2124 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2125  AsmWriterContext &WriterCtx) {
2126  Out << "!DISubprogram(";
2127  MDFieldPrinter Printer(Out, WriterCtx);
2128  Printer.printString("name", N->getName());
2129  Printer.printString("linkageName", N->getLinkageName());
2130  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2131  Printer.printMetadata("file", N->getRawFile());
2132  Printer.printInt("line", N->getLine());
2133  Printer.printMetadata("type", N->getRawType());
2134  Printer.printInt("scopeLine", N->getScopeLine());
2135  Printer.printMetadata("containingType", N->getRawContainingType());
2136  if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2137  N->getVirtualIndex() != 0)
2138  Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2139  Printer.printInt("thisAdjustment", N->getThisAdjustment());
2140  Printer.printDIFlags("flags", N->getFlags());
2141  Printer.printDISPFlags("spFlags", N->getSPFlags());
2142  Printer.printMetadata("unit", N->getRawUnit());
2143  Printer.printMetadata("templateParams", N->getRawTemplateParams());
2144  Printer.printMetadata("declaration", N->getRawDeclaration());
2145  Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2146  Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2147  Printer.printMetadata("annotations", N->getRawAnnotations());
2148  Printer.printString("targetFuncName", N->getTargetFuncName());
2149  Out << ")";
2150 }
2151 
2152 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2153  AsmWriterContext &WriterCtx) {
2154  Out << "!DILexicalBlock(";
2155  MDFieldPrinter Printer(Out, WriterCtx);
2156  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2157  Printer.printMetadata("file", N->getRawFile());
2158  Printer.printInt("line", N->getLine());
2159  Printer.printInt("column", N->getColumn());
2160  Out << ")";
2161 }
2162 
2163 static void writeDILexicalBlockFile(raw_ostream &Out,
2164  const DILexicalBlockFile *N,
2165  AsmWriterContext &WriterCtx) {
2166  Out << "!DILexicalBlockFile(";
2167  MDFieldPrinter Printer(Out, WriterCtx);
2168  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2169  Printer.printMetadata("file", N->getRawFile());
2170  Printer.printInt("discriminator", N->getDiscriminator(),
2171  /* ShouldSkipZero */ false);
2172  Out << ")";
2173 }
2174 
2175 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2176  AsmWriterContext &WriterCtx) {
2177  Out << "!DINamespace(";
2178  MDFieldPrinter Printer(Out, WriterCtx);
2179  Printer.printString("name", N->getName());
2180  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2181  Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2182  Out << ")";
2183 }
2184 
2185 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2186  AsmWriterContext &WriterCtx) {
2187  Out << "!DICommonBlock(";
2188  MDFieldPrinter Printer(Out, WriterCtx);
2189  Printer.printMetadata("scope", N->getRawScope(), false);
2190  Printer.printMetadata("declaration", N->getRawDecl(), false);
2191  Printer.printString("name", N->getName());
2192  Printer.printMetadata("file", N->getRawFile());
2193  Printer.printInt("line", N->getLineNo());
2194  Out << ")";
2195 }
2196 
2197 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2198  AsmWriterContext &WriterCtx) {
2199  Out << "!DIMacro(";
2200  MDFieldPrinter Printer(Out, WriterCtx);
2201  Printer.printMacinfoType(N);
2202  Printer.printInt("line", N->getLine());
2203  Printer.printString("name", N->getName());
2204  Printer.printString("value", N->getValue());
2205  Out << ")";
2206 }
2207 
2208 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2209  AsmWriterContext &WriterCtx) {
2210  Out << "!DIMacroFile(";
2211  MDFieldPrinter Printer(Out, WriterCtx);
2212  Printer.printInt("line", N->getLine());
2213  Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2214  Printer.printMetadata("nodes", N->getRawElements());
2215  Out << ")";
2216 }
2217 
2218 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2219  AsmWriterContext &WriterCtx) {
2220  Out << "!DIModule(";
2221  MDFieldPrinter Printer(Out, WriterCtx);
2222  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2223  Printer.printString("name", N->getName());
2224  Printer.printString("configMacros", N->getConfigurationMacros());
2225  Printer.printString("includePath", N->getIncludePath());
2226  Printer.printString("apinotes", N->getAPINotesFile());
2227  Printer.printMetadata("file", N->getRawFile());
2228  Printer.printInt("line", N->getLineNo());
2229  Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
2230  Out << ")";
2231 }
2232 
2233 static void writeDITemplateTypeParameter(raw_ostream &Out,
2234  const DITemplateTypeParameter *N,
2235  AsmWriterContext &WriterCtx) {
2236  Out << "!DITemplateTypeParameter(";
2237  MDFieldPrinter Printer(Out, WriterCtx);
2238  Printer.printString("name", N->getName());
2239  Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2240  Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2241  Out << ")";
2242 }
2243 
2244 static void writeDITemplateValueParameter(raw_ostream &Out,
2245  const DITemplateValueParameter *N,
2246  AsmWriterContext &WriterCtx) {
2247  Out << "!DITemplateValueParameter(";
2248  MDFieldPrinter Printer(Out, WriterCtx);
2249  if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2250  Printer.printTag(N);
2251  Printer.printString("name", N->getName());
2252  Printer.printMetadata("type", N->getRawType());
2253  Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2254  Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2255  Out << ")";
2256 }
2257 
2258 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2259  AsmWriterContext &WriterCtx) {
2260  Out << "!DIGlobalVariable(";
2261  MDFieldPrinter Printer(Out, WriterCtx);
2262  Printer.printString("name", N->getName());
2263  Printer.printString("linkageName", N->getLinkageName());
2264  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2265  Printer.printMetadata("file", N->getRawFile());
2266  Printer.printInt("line", N->getLine());
2267  Printer.printMetadata("type", N->getRawType());
2268  Printer.printBool("isLocal", N->isLocalToUnit());
2269  Printer.printBool("isDefinition", N->isDefinition());
2270  Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2271  Printer.printMetadata("templateParams", N->getRawTemplateParams());
2272  Printer.printInt("align", N->getAlignInBits());
2273  Printer.printMetadata("annotations", N->getRawAnnotations());
2274  Out << ")";
2275 }
2276 
2277 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2278  AsmWriterContext &WriterCtx) {
2279  Out << "!DILocalVariable(";
2280  MDFieldPrinter Printer(Out, WriterCtx);
2281  Printer.printString("name", N->getName());
2282  Printer.printInt("arg", N->getArg());
2283  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2284  Printer.printMetadata("file", N->getRawFile());
2285  Printer.printInt("line", N->getLine());
2286  Printer.printMetadata("type", N->getRawType());
2287  Printer.printDIFlags("flags", N->getFlags());
2288  Printer.printInt("align", N->getAlignInBits());
2289  Printer.printMetadata("annotations", N->getRawAnnotations());
2290  Out << ")";
2291 }
2292 
2293 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2294  AsmWriterContext &WriterCtx) {
2295  Out << "!DILabel(";
2296  MDFieldPrinter Printer(Out, WriterCtx);
2297  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2298  Printer.printString("name", N->getName());
2299  Printer.printMetadata("file", N->getRawFile());
2300  Printer.printInt("line", N->getLine());
2301  Out << ")";
2302 }
2303 
2304 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2305  AsmWriterContext &WriterCtx) {
2306  Out << "!DIExpression(";
2307  FieldSeparator FS;
2308  if (N->isValid()) {
2309  for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2310  auto OpStr = dwarf::OperationEncodingString(Op.getOp());
2311  assert(!OpStr.empty() && "Expected valid opcode");
2312 
2313  Out << FS << OpStr;
2314  if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2315  Out << FS << Op.getArg(0);
2316  Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
2317  } else {
2318  for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2319  Out << FS << Op.getArg(A);
2320  }
2321  }
2322  } else {
2323  for (const auto &I : N->getElements())
2324  Out << FS << I;
2325  }
2326  Out << ")";
2327 }
2328 
2329 static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2330  AsmWriterContext &WriterCtx,
2331  bool FromValue = false) {
2332  assert(FromValue &&
2333  "Unexpected DIArgList metadata outside of value argument");
2334  Out << "!DIArgList(";
2335  FieldSeparator FS;
2336  MDFieldPrinter Printer(Out, WriterCtx);
2337  for (Metadata *Arg : N->getArgs()) {
2338  Out << FS;
2339  WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2340  }
2341  Out << ")";
2342 }
2343 
2344 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2345  const DIGlobalVariableExpression *N,
2346  AsmWriterContext &WriterCtx) {
2347  Out << "!DIGlobalVariableExpression(";
2348  MDFieldPrinter Printer(Out, WriterCtx);
2349  Printer.printMetadata("var", N->getVariable());
2350  Printer.printMetadata("expr", N->getExpression());
2351  Out << ")";
2352 }
2353 
2354 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2355  AsmWriterContext &WriterCtx) {
2356  Out << "!DIObjCProperty(";
2357  MDFieldPrinter Printer(Out, WriterCtx);
2358  Printer.printString("name", N->getName());
2359  Printer.printMetadata("file", N->getRawFile());
2360  Printer.printInt("line", N->getLine());
2361  Printer.printString("setter", N->getSetterName());
2362  Printer.printString("getter", N->getGetterName());
2363  Printer.printInt("attributes", N->getAttributes());
2364  Printer.printMetadata("type", N->getRawType());
2365  Out << ")";
2366 }
2367 
2368 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2369  AsmWriterContext &WriterCtx) {
2370  Out << "!DIImportedEntity(";
2371  MDFieldPrinter Printer(Out, WriterCtx);
2372  Printer.printTag(N);
2373  Printer.printString("name", N->getName());
2374  Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2375  Printer.printMetadata("entity", N->getRawEntity());
2376  Printer.printMetadata("file", N->getRawFile());
2377  Printer.printInt("line", N->getLine());
2378  Printer.printMetadata("elements", N->getRawElements());
2379  Out << ")";
2380 }
2381 
2382 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2383  AsmWriterContext &Ctx) {
2384  if (Node->isDistinct())
2385  Out << "distinct ";
2386  else if (Node->isTemporary())
2387  Out << "<temporary!> "; // Handle broken code.
2388 
2389  switch (Node->getMetadataID()) {
2390  default:
2391  llvm_unreachable("Expected uniquable MDNode");
2392 #define HANDLE_MDNODE_LEAF(CLASS) \
2393  case Metadata::CLASS##Kind: \
2394  write##CLASS(Out, cast<CLASS>(Node), Ctx); \
2395  break;
2396 #include "llvm/IR/Metadata.def"
2397  }
2398 }
2399 
2400 // Full implementation of printing a Value as an operand with support for
2401 // TypePrinting, etc.
2402 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2403  AsmWriterContext &WriterCtx) {
2404  if (V->hasName()) {
2405  PrintLLVMName(Out, V);
2406  return;
2407  }
2408 
2409  const Constant *CV = dyn_cast<Constant>(V);
2410  if (CV && !isa<GlobalValue>(CV)) {
2411  assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2412  WriteConstantInternal(Out, CV, WriterCtx);
2413  return;
2414  }
2415 
2416  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2417  Out << "asm ";
2418  if (IA->hasSideEffects())
2419  Out << "sideeffect ";
2420  if (IA->isAlignStack())
2421  Out << "alignstack ";
2422  // We don't emit the AD_ATT dialect as it's the assumed default.
2423  if (IA->getDialect() == InlineAsm::AD_Intel)
2424  Out << "inteldialect ";
2425  if (IA->canThrow())
2426  Out << "unwind ";
2427  Out << '"';
2428  printEscapedString(IA->getAsmString(), Out);
2429  Out << "\", \"";
2430  printEscapedString(IA->getConstraintString(), Out);
2431  Out << '"';
2432  return;
2433  }
2434 
2435  if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2436  WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
2437  /* FromValue */ true);
2438  return;
2439  }
2440 
2441  char Prefix = '%';
2442  int Slot;
2443  auto *Machine = WriterCtx.Machine;
2444  // If we have a SlotTracker, use it.
2445  if (Machine) {
2446  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2447  Slot = Machine->getGlobalSlot(GV);
2448  Prefix = '@';
2449  } else {
2450  Slot = Machine->getLocalSlot(V);
2451 
2452  // If the local value didn't succeed, then we may be referring to a value
2453  // from a different function. Translate it, as this can happen when using
2454  // address of blocks.
2455  if (Slot == -1)
2456  if ((Machine = createSlotTracker(V))) {
2457  Slot = Machine->getLocalSlot(V);
2458  delete Machine;
2459  }
2460  }
2461  } else if ((Machine = createSlotTracker(V))) {
2462  // Otherwise, create one to get the # and then destroy it.
2463  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2464  Slot = Machine->getGlobalSlot(GV);
2465  Prefix = '@';
2466  } else {
2467  Slot = Machine->getLocalSlot(V);
2468  }
2469  delete Machine;
2470  Machine = nullptr;
2471  } else {
2472  Slot = -1;
2473  }
2474 
2475  if (Slot != -1)
2476  Out << Prefix << Slot;
2477  else
2478  Out << "<badref>";
2479 }
2480 
2481 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2482  AsmWriterContext &WriterCtx,
2483  bool FromValue) {
2484  // Write DIExpressions and DIArgLists inline when used as a value. Improves
2485  // readability of debug info intrinsics.
2486  if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2487  writeDIExpression(Out, Expr, WriterCtx);
2488  return;
2489  }
2490  if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2491  writeDIArgList(Out, ArgList, WriterCtx, FromValue);
2492  return;
2493  }
2494 
2495  if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2496  std::unique_ptr<SlotTracker> MachineStorage;
2497  SaveAndRestore<SlotTracker *> SARMachine(WriterCtx.Machine);
2498  if (!WriterCtx.Machine) {
2499  MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2500  WriterCtx.Machine = MachineStorage.get();
2501  }
2502  int Slot = WriterCtx.Machine->getMetadataSlot(N);
2503  if (Slot == -1) {
2504  if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2505  writeDILocation(Out, Loc, WriterCtx);
2506  return;
2507  }
2508  // Give the pointer value instead of "badref", since this comes up all
2509  // the time when debugging.
2510  Out << "<" << N << ">";
2511  } else
2512  Out << '!' << Slot;
2513  return;
2514  }
2515 
2516  if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2517  Out << "!\"";
2518  printEscapedString(MDS->getString(), Out);
2519  Out << '"';
2520  return;
2521  }
2522 
2523  auto *V = cast<ValueAsMetadata>(MD);
2524  assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
2525  assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2526  "Unexpected function-local metadata outside of value argument");
2527 
2528  WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
2529  Out << ' ';
2530  WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
2531 }
2532 
2533 namespace {
2534 
2535 class AssemblyWriter {
2536  formatted_raw_ostream &Out;
2537  const Module *TheModule = nullptr;
2538  const ModuleSummaryIndex *TheIndex = nullptr;
2539  std::unique_ptr<SlotTracker> SlotTrackerStorage;
2541  TypePrinting TypePrinter;
2542  AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2543  SetVector<const Comdat *> Comdats;
2544  bool IsForDebug;
2545  bool ShouldPreserveUseListOrder;
2546  UseListOrderMap UseListOrders;
2547  SmallVector<StringRef, 8> MDNames;
2548  /// Synchronization scope names registered with LLVMContext.
2551 
2552 public:
2553  /// Construct an AssemblyWriter with an external SlotTracker
2554  AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2555  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2556  bool ShouldPreserveUseListOrder = false);
2557 
2558  AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2559  const ModuleSummaryIndex *Index, bool IsForDebug);
2560 
2561  AsmWriterContext getContext() {
2562  return AsmWriterContext(&TypePrinter, &Machine, TheModule);
2563  }
2564 
2565  void printMDNodeBody(const MDNode *MD);
2566  void printNamedMDNode(const NamedMDNode *NMD);
2567 
2568  void printModule(const Module *M);
2569 
2570  void writeOperand(const Value *Op, bool PrintType);
2571  void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2572  void writeOperandBundles(const CallBase *Call);
2573  void writeSyncScope(const LLVMContext &Context,
2574  SyncScope::ID SSID);
2575  void writeAtomic(const LLVMContext &Context,
2576  AtomicOrdering Ordering,
2577  SyncScope::ID SSID);
2578  void writeAtomicCmpXchg(const LLVMContext &Context,
2579  AtomicOrdering SuccessOrdering,
2580  AtomicOrdering FailureOrdering,
2581  SyncScope::ID SSID);
2582 
2583  void writeAllMDNodes();
2584  void writeMDNode(unsigned Slot, const MDNode *Node);
2585  void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2586  void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
2587  void writeAllAttributeGroups();
2588 
2589  void printTypeIdentities();
2590  void printGlobal(const GlobalVariable *GV);
2591  void printAlias(const GlobalAlias *GA);
2592  void printIFunc(const GlobalIFunc *GI);
2593  void printComdat(const Comdat *C);
2594  void printFunction(const Function *F);
2595  void printArgument(const Argument *FA, AttributeSet Attrs);
2596  void printBasicBlock(const BasicBlock *BB);
2597  void printInstructionLine(const Instruction &I);
2598  void printInstruction(const Instruction &I);
2599 
2600  void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
2601  void printUseLists(const Function *F);
2602 
2603  void printModuleSummaryIndex();
2604  void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2605  void printSummary(const GlobalValueSummary &Summary);
2606  void printAliasSummary(const AliasSummary *AS);
2607  void printGlobalVarSummary(const GlobalVarSummary *GS);
2608  void printFunctionSummary(const FunctionSummary *FS);
2609  void printTypeIdSummary(const TypeIdSummary &TIS);
2610  void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
2611  void printTypeTestResolution(const TypeTestResolution &TTRes);
2612  void printArgs(const std::vector<uint64_t> &Args);
2613  void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2614  void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2615  void printVFuncId(const FunctionSummary::VFuncId VFId);
2616  void
2617  printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
2618  const char *Tag);
2619  void
2620  printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
2621  const char *Tag);
2622 
2623 private:
2624  /// Print out metadata attachments.
2625  void printMetadataAttachments(
2626  const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2627  StringRef Separator);
2628 
2629  // printInfoComment - Print a little comment after the instruction indicating
2630  // which slot it occupies.
2631  void printInfoComment(const Value &V);
2632 
2633  // printGCRelocateComment - print comment after call to the gc.relocate
2634  // intrinsic indicating base and derived pointer names.
2635  void printGCRelocateComment(const GCRelocateInst &Relocate);
2636 };
2637 
2638 } // end anonymous namespace
2639 
2640 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2641  const Module *M, AssemblyAnnotationWriter *AAW,
2642  bool IsForDebug, bool ShouldPreserveUseListOrder)
2643  : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2644  IsForDebug(IsForDebug),
2645  ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2646  if (!TheModule)
2647  return;
2648  for (const GlobalObject &GO : TheModule->global_objects())
2649  if (const Comdat *C = GO.getComdat())
2650  Comdats.insert(C);
2651 }
2652 
2653 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2654  const ModuleSummaryIndex *Index, bool IsForDebug)
2655  : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2656  IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2657 
2658 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2659  if (!Operand) {
2660  Out << "<null operand!>";
2661  return;
2662  }
2663  if (PrintType) {
2664  TypePrinter.print(Operand->getType(), Out);
2665  Out << ' ';
2666  }
2667  auto WriterCtx = getContext();
2668  WriteAsOperandInternal(Out, Operand, WriterCtx);
2669 }
2670 
2671 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2672  SyncScope::ID SSID) {
2673  switch (SSID) {
2674  case SyncScope::System: {
2675  break;
2676  }
2677  default: {
2678  if (SSNs.empty())
2679  Context.getSyncScopeNames(SSNs);
2680 
2681  Out << " syncscope(\"";
2682  printEscapedString(SSNs[SSID], Out);
2683  Out << "\")";
2684  break;
2685  }
2686  }
2687 }
2688 
2689 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2690  AtomicOrdering Ordering,
2691  SyncScope::ID SSID) {
2692  if (Ordering == AtomicOrdering::NotAtomic)
2693  return;
2694 
2695  writeSyncScope(Context, SSID);
2696  Out << " " << toIRString(Ordering);
2697 }
2698 
2699 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2700  AtomicOrdering SuccessOrdering,
2701  AtomicOrdering FailureOrdering,
2702  SyncScope::ID SSID) {
2703  assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2704  FailureOrdering != AtomicOrdering::NotAtomic);
2705 
2706  writeSyncScope(Context, SSID);
2707  Out << " " << toIRString(SuccessOrdering);
2708  Out << " " << toIRString(FailureOrdering);
2709 }
2710 
2711 void AssemblyWriter::writeParamOperand(const Value *Operand,
2712  AttributeSet Attrs) {
2713  if (!Operand) {
2714  Out << "<null operand!>";
2715  return;
2716  }
2717 
2718  // Print the type
2719  TypePrinter.print(Operand->getType(), Out);
2720  // Print parameter attributes list
2721  if (Attrs.hasAttributes()) {
2722  Out << ' ';
2723  writeAttributeSet(Attrs);
2724  }
2725  Out << ' ';
2726  // Print the operand
2727  auto WriterCtx = getContext();
2728  WriteAsOperandInternal(Out, Operand, WriterCtx);
2729 }
2730 
2731 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2732  if (!Call->hasOperandBundles())
2733  return;
2734 
2735  Out << " [ ";
2736 
2737  bool FirstBundle = true;
2738  for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2739  OperandBundleUse BU = Call->getOperandBundleAt(i);
2740 
2741  if (!FirstBundle)
2742  Out << ", ";
2743  FirstBundle = false;
2744 
2745  Out << '"';
2746  printEscapedString(BU.getTagName(), Out);
2747  Out << '"';
2748 
2749  Out << '(';
2750 
2751  bool FirstInput = true;
2752  auto WriterCtx = getContext();
2753  for (const auto &Input : BU.Inputs) {
2754  if (!FirstInput)
2755  Out << ", ";
2756  FirstInput = false;
2757 
2758  TypePrinter.print(Input->getType(), Out);
2759  Out << " ";
2760  WriteAsOperandInternal(Out, Input, WriterCtx);
2761  }
2762 
2763  Out << ')';
2764  }
2765 
2766  Out << " ]";
2767 }
2768 
2769 void AssemblyWriter::printModule(const Module *M) {
2770  Machine.initializeIfNeeded();
2771 
2772  if (ShouldPreserveUseListOrder)
2773  UseListOrders = predictUseListOrder(M);
2774 
2775  if (!M->getModuleIdentifier().empty() &&
2776  // Don't print the ID if it will start a new line (which would
2777  // require a comment char before it).
2778  M->getModuleIdentifier().find('\n') == std::string::npos)
2779  Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2780 
2781  if (!M->getSourceFileName().empty()) {
2782  Out << "source_filename = \"";
2783  printEscapedString(M->getSourceFileName(), Out);
2784  Out << "\"\n";
2785  }
2786 
2787  const std::string &DL = M->getDataLayoutStr();
2788  if (!DL.empty())
2789  Out << "target datalayout = \"" << DL << "\"\n";
2790  if (!M->getTargetTriple().empty())
2791  Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2792 
2793  if (!M->getModuleInlineAsm().empty()) {
2794  Out << '\n';
2795 
2796  // Split the string into lines, to make it easier to read the .ll file.
2797  StringRef Asm = M->getModuleInlineAsm();
2798  do {
2799  StringRef Front;
2800  std::tie(Front, Asm) = Asm.split('\n');
2801 
2802  // We found a newline, print the portion of the asm string from the
2803  // last newline up to this newline.
2804  Out << "module asm \"";
2805  printEscapedString(Front, Out);
2806  Out << "\"\n";
2807  } while (!Asm.empty());
2808  }
2809 
2810  printTypeIdentities();
2811 
2812  // Output all comdats.
2813  if (!Comdats.empty())
2814  Out << '\n';
2815  for (const Comdat *C : Comdats) {
2816  printComdat(C);
2817  if (C != Comdats.back())
2818  Out << '\n';
2819  }
2820 
2821  // Output all globals.
2822  if (!M->global_empty()) Out << '\n';
2823  for (const GlobalVariable &GV : M->globals()) {
2824  printGlobal(&GV); Out << '\n';
2825  }
2826 
2827  // Output all aliases.
2828  if (!M->alias_empty()) Out << "\n";
2829  for (const GlobalAlias &GA : M->aliases())
2830  printAlias(&GA);
2831 
2832  // Output all ifuncs.
2833  if (!M->ifunc_empty()) Out << "\n";
2834  for (const GlobalIFunc &GI : M->ifuncs())
2835  printIFunc(&GI);
2836 
2837  // Output all of the functions.
2838  for (const Function &F : *M) {
2839  Out << '\n';
2840  printFunction(&F);
2841  }
2842 
2843  // Output global use-lists.
2844  printUseLists(nullptr);
2845 
2846  // Output all attribute groups.
2847  if (!Machine.as_empty()) {
2848  Out << '\n';
2849  writeAllAttributeGroups();
2850  }
2851 
2852  // Output named metadata.
2853  if (!M->named_metadata_empty()) Out << '\n';
2854 
2855  for (const NamedMDNode &Node : M->named_metadata())
2856  printNamedMDNode(&Node);
2857 
2858  // Output metadata.
2859  if (!Machine.mdn_empty()) {
2860  Out << '\n';
2861  writeAllMDNodes();
2862  }
2863 }
2864 
2865 void AssemblyWriter::printModuleSummaryIndex() {
2866  assert(TheIndex);
2867  int NumSlots = Machine.initializeIndexIfNeeded();
2868 
2869  Out << "\n";
2870 
2871  // Print module path entries. To print in order, add paths to a vector
2872  // indexed by module slot.
2873  std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2874  std::string RegularLTOModuleName =
2875  ModuleSummaryIndex::getRegularLTOModuleName();
2876  moduleVec.resize(TheIndex->modulePaths().size());
2877  for (auto &ModPath : TheIndex->modulePaths())
2878  moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2879  // A module id of -1 is a special entry for a regular LTO module created
2880  // during the thin link.
2881  ModPath.second.first == -1u ? RegularLTOModuleName
2882  : (std::string)std::string(ModPath.first()),
2883  ModPath.second.second);
2884 
2885  unsigned i = 0;
2886  for (auto &ModPair : moduleVec) {
2887  Out << "^" << i++ << " = module: (";
2888  Out << "path: \"";
2889  printEscapedString(ModPair.first, Out);
2890  Out << "\", hash: (";
2891  FieldSeparator FS;
2892  for (auto Hash : ModPair.second)
2893  Out << FS << Hash;
2894  Out << "))\n";
2895  }
2896 
2897  // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2898  // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2899  for (auto &GlobalList : *TheIndex) {
2900  auto GUID = GlobalList.first;
2901  for (auto &Summary : GlobalList.second.SummaryList)
2902  SummaryToGUIDMap[Summary.get()] = GUID;
2903  }
2904 
2905  // Print the global value summary entries.
2906  for (auto &GlobalList : *TheIndex) {
2907  auto GUID = GlobalList.first;
2908  auto VI = TheIndex->getValueInfo(GlobalList);
2909  printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2910  }
2911 
2912  // Print the TypeIdMap entries.
2913  for (const auto &TID : TheIndex->typeIds()) {
2914  Out << "^" << Machine.getTypeIdSlot(TID.second.first)
2915  << " = typeid: (name: \"" << TID.second.first << "\"";
2916  printTypeIdSummary(TID.second.second);
2917  Out << ") ; guid = " << TID.first << "\n";
2918  }
2919 
2920  // Print the TypeIdCompatibleVtableMap entries.
2921  for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2922  auto GUID = GlobalValue::getGUID(TId.first);
2923  Out << "^" << Machine.getGUIDSlot(GUID)
2924  << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
2925  printTypeIdCompatibleVtableSummary(TId.second);
2926  Out << ") ; guid = " << GUID << "\n";
2927  }
2928 
2929  // Don't emit flags when it's not really needed (value is zero by default).
2930  if (TheIndex->getFlags()) {
2931  Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
2932  ++NumSlots;
2933  }
2934 
2935  Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
2936  << "\n";
2937 }
2938 
2939 static const char *
2941  switch (K) {
2942  case WholeProgramDevirtResolution::Indir:
2943  return "indir";
2944  case WholeProgramDevirtResolution::SingleImpl:
2945  return "singleImpl";
2946  case WholeProgramDevirtResolution::BranchFunnel:
2947  return "branchFunnel";
2948  }
2949  llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2950 }
2951 
2954  switch (K) {
2955  case WholeProgramDevirtResolution::ByArg::Indir:
2956  return "indir";
2957  case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2958  return "uniformRetVal";
2959  case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2960  return "uniqueRetVal";
2961  case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2962  return "virtualConstProp";
2963  }
2964  llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2965 }
2966 
2968  switch (K) {
2970  return "unknown";
2971  case TypeTestResolution::Unsat:
2972  return "unsat";
2973  case TypeTestResolution::ByteArray:
2974  return "byteArray";
2975  case TypeTestResolution::Inline:
2976  return "inline";
2978  return "single";
2979  case TypeTestResolution::AllOnes:
2980  return "allOnes";
2981  }
2982  llvm_unreachable("invalid TypeTestResolution kind");
2983 }
2984 
2985 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2986  Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2987  << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2988 
2989  // The following fields are only used if the target does not support the use
2990  // of absolute symbols to store constants. Print only if non-zero.
2991  if (TTRes.AlignLog2)
2992  Out << ", alignLog2: " << TTRes.AlignLog2;
2993  if (TTRes.SizeM1)
2994  Out << ", sizeM1: " << TTRes.SizeM1;
2995  if (TTRes.BitMask)
2996  // BitMask is uint8_t which causes it to print the corresponding char.
2997  Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2998  if (TTRes.InlineBits)
2999  Out << ", inlineBits: " << TTRes.InlineBits;
3000 
3001  Out << ")";
3002 }
3003 
3004 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
3005  Out << ", summary: (";
3006  printTypeTestResolution(TIS.TTRes);
3007  if (!TIS.WPDRes.empty()) {
3008  Out << ", wpdResolutions: (";
3009  FieldSeparator FS;
3010  for (auto &WPDRes : TIS.WPDRes) {
3011  Out << FS;
3012  Out << "(offset: " << WPDRes.first << ", ";
3013  printWPDRes(WPDRes.second);
3014  Out << ")";
3015  }
3016  Out << ")";
3017  }
3018  Out << ")";
3019 }
3020 
3021 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3022  const TypeIdCompatibleVtableInfo &TI) {
3023  Out << ", summary: (";
3024  FieldSeparator FS;
3025  for (auto &P : TI) {
3026  Out << FS;
3027  Out << "(offset: " << P.AddressPointOffset << ", ";
3028  Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
3029  Out << ")";
3030  }
3031  Out << ")";
3032 }
3033 
3034 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
3035  Out << "args: (";
3036  FieldSeparator FS;
3037  for (auto arg : Args) {
3038  Out << FS;
3039  Out << arg;
3040  }
3041  Out << ")";
3042 }
3043 
3044 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
3045  Out << "wpdRes: (kind: ";
3046  Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
3047 
3048  if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
3049  Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
3050 
3051  if (!WPDRes.ResByArg.empty()) {
3052  Out << ", resByArg: (";
3053  FieldSeparator FS;
3054  for (auto &ResByArg : WPDRes.ResByArg) {
3055  Out << FS;
3056  printArgs(ResByArg.first);
3057  Out << ", byArg: (kind: ";
3058  Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
3059  if (ResByArg.second.TheKind ==
3060  WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3061  ResByArg.second.TheKind ==
3062  WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3063  Out << ", info: " << ResByArg.second.Info;
3064 
3065  // The following fields are only used if the target does not support the
3066  // use of absolute symbols to store constants. Print only if non-zero.
3067  if (ResByArg.second.Byte || ResByArg.second.Bit)
3068  Out << ", byte: " << ResByArg.second.Byte
3069  << ", bit: " << ResByArg.second.Bit;
3070 
3071  Out << ")";
3072  }
3073  Out << ")";
3074  }
3075  Out << ")";
3076 }
3077 
3079  switch (SK) {
3080  case GlobalValueSummary::AliasKind:
3081  return "alias";
3082  case GlobalValueSummary::FunctionKind:
3083  return "function";
3084  case GlobalValueSummary::GlobalVarKind:
3085  return "variable";
3086  }
3087  llvm_unreachable("invalid summary kind");
3088 }
3089 
3090 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
3091  Out << ", aliasee: ";
3092  // The indexes emitted for distributed backends may not include the
3093  // aliasee summary (only if it is being imported directly). Handle
3094  // that case by just emitting "null" as the aliasee.
3095  if (AS->hasAliasee())
3096  Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
3097  else
3098  Out << "null";
3099 }
3100 
3101 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
3102  auto VTableFuncs = GS->vTableFuncs();
3103  Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3104  << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3105  << "constant: " << GS->VarFlags.Constant;
3106  if (!VTableFuncs.empty())
3107  Out << ", "
3108  << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3109  Out << ")";
3110 
3111  if (!VTableFuncs.empty()) {
3112  Out << ", vTableFuncs: (";
3113  FieldSeparator FS;
3114  for (auto &P : VTableFuncs) {
3115  Out << FS;
3116  Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
3117  << ", offset: " << P.VTableOffset;
3118  Out << ")";
3119  }
3120  Out << ")";
3121  }
3122 }
3123 
3125  switch (LT) {
3126  case GlobalValue::ExternalLinkage:
3127  return "external";
3128  case GlobalValue::PrivateLinkage:
3129  return "private";
3130  case GlobalValue::InternalLinkage:
3131  return "internal";
3132  case GlobalValue::LinkOnceAnyLinkage:
3133  return "linkonce";
3134  case GlobalValue::LinkOnceODRLinkage:
3135  return "linkonce_odr";
3136  case GlobalValue::WeakAnyLinkage:
3137  return "weak";
3138  case GlobalValue::WeakODRLinkage:
3139  return "weak_odr";
3140  case GlobalValue::CommonLinkage:
3141  return "common";
3142  case GlobalValue::AppendingLinkage:
3143  return "appending";
3144  case GlobalValue::ExternalWeakLinkage:
3145  return "extern_weak";
3146  case GlobalValue::AvailableExternallyLinkage:
3147  return "available_externally";
3148  }
3149  llvm_unreachable("invalid linkage");
3150 }
3151 
3152 // When printing the linkage types in IR where the ExternalLinkage is
3153 // not printed, and other linkage types are expected to be printed with
3154 // a space after the name.
3156  if (LT == GlobalValue::ExternalLinkage)
3157  return "";
3158  return getLinkageName(LT) + " ";
3159 }
3160 
3162  switch (Vis) {
3163  case GlobalValue::DefaultVisibility:
3164  return "default";
3165  case GlobalValue::HiddenVisibility:
3166  return "hidden";
3167  case GlobalValue::ProtectedVisibility:
3168  return "protected";
3169  }
3170  llvm_unreachable("invalid visibility");
3171 }
3172 
3173 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
3174  Out << ", insts: " << FS->instCount();
3175  if (FS->fflags().anyFlagSet())
3176  Out << ", " << FS->fflags();
3177 
3178  if (!FS->calls().empty()) {
3179  Out << ", calls: (";
3180  FieldSeparator IFS;
3181  for (auto &Call : FS->calls()) {
3182  Out << IFS;
3183  Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
3184  if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
3185  Out << ", hotness: " << getHotnessName(Call.second.getHotness());
3186  else if (Call.second.RelBlockFreq)
3187  Out << ", relbf: " << Call.second.RelBlockFreq;
3188  Out << ")";
3189  }
3190  Out << ")";
3191  }
3192 
3193  if (const auto *TIdInfo = FS->getTypeIdInfo())
3194  printTypeIdInfo(*TIdInfo);
3195 
3196  // The AllocationType identifiers capture the profiled context behavior
3197  // reaching a specific static allocation site (possibly cloned). Thus
3198  // "notcoldandcold" implies there are multiple contexts which reach this site,
3199  // some of which are cold and some of which are not, and that need to
3200  // disambiguate via cloning or other context identification.
3201  auto AllocTypeName = [](uint8_t Type) -> const char * {
3202  switch (Type) {
3203  case (uint8_t)AllocationType::None:
3204  return "none";
3205  case (uint8_t)AllocationType::NotCold:
3206  return "notcold";
3207  case (uint8_t)AllocationType::Cold:
3208  return "cold";
3209  case (uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold:
3210  return "notcoldandcold";
3211  }
3212  llvm_unreachable("Unexpected alloc type");
3213  };
3214 
3215  if (!FS->allocs().empty()) {
3216  Out << ", allocs: (";
3217  FieldSeparator AFS;
3218  for (auto &AI : FS->allocs()) {
3219  Out << AFS;
3220  Out << "(versions: (";
3221  FieldSeparator VFS;
3222  for (auto V : AI.Versions) {
3223  Out << VFS;
3224  Out << AllocTypeName(V);
3225  }
3226  Out << "), memProf: (";
3227  FieldSeparator MIBFS;
3228  for (auto &MIB : AI.MIBs) {
3229  Out << MIBFS;
3230  Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3231  Out << ", stackIds: (";
3232  FieldSeparator SIDFS;
3233  for (auto Id : MIB.StackIdIndices) {
3234  Out << SIDFS;
3235  Out << TheIndex->getStackIdAtIndex(Id);
3236  }
3237  Out << "))";
3238  }
3239  Out << "))";
3240  }
3241  Out << ")";
3242  }
3243 
3244  if (!FS->callsites().empty()) {
3245  Out << ", callsites: (";
3246  FieldSeparator SNFS;
3247  for (auto &CI : FS->callsites()) {
3248  Out << SNFS;
3249  if (CI.Callee)
3250  Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
3251  else
3252  Out << "(callee: null";
3253  Out << ", clones: (";
3254  FieldSeparator VFS;
3255  for (auto V : CI.Clones) {
3256  Out << VFS;
3257  Out << V;
3258  }
3259  Out << "), stackIds: (";
3260  FieldSeparator SIDFS;
3261  for (auto Id : CI.StackIdIndices) {
3262  Out << SIDFS;
3263  Out << TheIndex->getStackIdAtIndex(Id);
3264  }
3265  Out << "))";
3266  }
3267  Out << ")";
3268  }
3269 
3270  auto PrintRange = [&](const ConstantRange &Range) {
3271  Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3272  };
3273 
3274  if (!FS->paramAccesses().empty()) {
3275  Out << ", params: (";
3276  FieldSeparator IFS;
3277  for (auto &PS : FS->paramAccesses()) {
3278  Out << IFS;
3279  Out << "(param: " << PS.ParamNo;
3280  Out << ", offset: ";
3281  PrintRange(PS.Use);
3282  if (!PS.Calls.empty()) {
3283  Out << ", calls: (";
3284  FieldSeparator IFS;
3285  for (auto &Call : PS.Calls) {
3286  Out << IFS;
3287  Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
3288  Out << ", param: " << Call.ParamNo;
3289  Out << ", offset: ";
3290  PrintRange(Call.Offsets);
3291  Out << ")";
3292  }
3293  Out << ")";
3294  }
3295  Out << ")";
3296  }
3297  Out << ")";
3298  }
3299 }
3300 
3301 void AssemblyWriter::printTypeIdInfo(
3302  const FunctionSummary::TypeIdInfo &TIDInfo) {
3303  Out << ", typeIdInfo: (";
3304  FieldSeparator TIDFS;
3305  if (!TIDInfo.TypeTests.empty()) {
3306  Out << TIDFS;
3307  Out << "typeTests: (";
3308  FieldSeparator FS;
3309  for (auto &GUID : TIDInfo.TypeTests) {
3310  auto TidIter = TheIndex->typeIds().equal_range(GUID);
3311  if (TidIter.first == TidIter.second) {
3312  Out << FS;
3313  Out << GUID;
3314  continue;
3315  }
3316  // Print all type id that correspond to this GUID.
3317  for (auto It = TidIter.first; It != TidIter.second; ++It) {
3318  Out << FS;
3319  auto Slot = Machine.getTypeIdSlot(It->second.first);
3320  assert(Slot != -1);
3321  Out << "^" << Slot;
3322  }
3323  }
3324  Out << ")";
3325  }
3326  if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3327  Out << TIDFS;
3328  printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3329  }
3330  if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3331  Out << TIDFS;
3332  printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3333  }
3334  if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3335  Out << TIDFS;
3336  printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3337  "typeTestAssumeConstVCalls");
3338  }
3339  if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3340  Out << TIDFS;
3341  printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3342  "typeCheckedLoadConstVCalls");
3343  }
3344  Out << ")";
3345 }
3346 
3347 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3348  auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3349  if (TidIter.first == TidIter.second) {
3350  Out << "vFuncId: (";
3351  Out << "guid: " << VFId.GUID;
3352  Out << ", offset: " << VFId.Offset;
3353  Out << ")";
3354  return;
3355  }
3356  // Print all type id that correspond to this GUID.
3357  FieldSeparator FS;
3358  for (auto It = TidIter.first; It != TidIter.second; ++It) {
3359  Out << FS;
3360  Out << "vFuncId: (";
3361  auto Slot = Machine.getTypeIdSlot(It->second.first);
3362  assert(Slot != -1);
3363  Out << "^" << Slot;
3364  Out << ", offset: " << VFId.Offset;
3365  Out << ")";
3366  }
3367 }
3368 
3369 void AssemblyWriter::printNonConstVCalls(
3370  const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
3371  Out << Tag << ": (";
3372  FieldSeparator FS;
3373  for (auto &VFuncId : VCallList) {
3374  Out << FS;
3375  printVFuncId(VFuncId);
3376  }
3377  Out << ")";
3378 }
3379 
3380 void AssemblyWriter::printConstVCalls(
3381  const std::vector<FunctionSummary::ConstVCall> &VCallList,
3382  const char *Tag) {
3383  Out << Tag << ": (";
3384  FieldSeparator FS;
3385  for (auto &ConstVCall : VCallList) {
3386  Out << FS;
3387  Out << "(";
3388  printVFuncId(ConstVCall.VFunc);
3389  if (!ConstVCall.Args.empty()) {
3390  Out << ", ";
3391  printArgs(ConstVCall.Args);
3392  }
3393  Out << ")";
3394  }
3395  Out << ")";
3396 }
3397 
3398 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3399  GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3401  Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3402  Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3403  << ", flags: (";
3404  Out << "linkage: " << getLinkageName(LT);
3405  Out << ", visibility: "
3407  Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3408  Out << ", live: " << GVFlags.Live;
3409  Out << ", dsoLocal: " << GVFlags.DSOLocal;
3410  Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3411  Out << ")";
3412 
3413  if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3414  printAliasSummary(cast<AliasSummary>(&Summary));
3415  else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3416  printFunctionSummary(cast<FunctionSummary>(&Summary));
3417  else
3418  printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3419 
3420  auto RefList = Summary.refs();
3421  if (!RefList.empty()) {
3422  Out << ", refs: (";
3423  FieldSeparator FS;
3424  for (auto &Ref : RefList) {
3425  Out << FS;
3426  if (Ref.isReadOnly())
3427  Out << "readonly ";
3428  else if (Ref.isWriteOnly())
3429  Out << "writeonly ";
3430  Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3431  }
3432  Out << ")";
3433  }
3434 
3435  Out << ")";
3436 }
3437 
3438 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3439  Out << "^" << Slot << " = gv: (";
3440  if (!VI.name().empty())
3441  Out << "name: \"" << VI.name() << "\"";
3442  else
3443  Out << "guid: " << VI.getGUID();
3444  if (!VI.getSummaryList().empty()) {
3445  Out << ", summaries: (";
3446  FieldSeparator FS;
3447  for (auto &Summary : VI.getSummaryList()) {
3448  Out << FS;
3449  printSummary(*Summary);
3450  }
3451  Out << ")";
3452  }
3453  Out << ")";
3454  if (!VI.name().empty())
3455  Out << " ; guid = " << VI.getGUID();
3456  Out << "\n";
3457 }
3458 
3460  formatted_raw_ostream &Out) {
3461  if (Name.empty()) {
3462  Out << "<empty name> ";
3463  } else {
3464  if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3465  Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3466  Out << Name[0];
3467  else
3468  Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3469  for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3470  unsigned char C = Name[i];
3471  if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3472  C == '.' || C == '_')
3473  Out << C;
3474  else
3475  Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3476  }
3477  }
3478 }
3479 
3480 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3481  Out << '!';
3482  printMetadataIdentifier(NMD->getName(), Out);
3483  Out << " = !{";
3484  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3485  if (i)
3486  Out << ", ";
3487 
3488  // Write DIExpressions inline.
3489  // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3490  MDNode *Op = NMD->getOperand(i);
3491  assert(!isa<DIArgList>(Op) &&
3492  "DIArgLists should not appear in NamedMDNodes");
3493  if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3494  writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
3495  continue;
3496  }
3497 
3498  int Slot = Machine.getMetadataSlot(Op);
3499  if (Slot == -1)
3500  Out << "<badref>";
3501  else
3502  Out << '!' << Slot;
3503  }
3504  Out << "}\n";
3505 }
3506 
3508  formatted_raw_ostream &Out) {
3509  switch (Vis) {
3510  case GlobalValue::DefaultVisibility: break;
3511  case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3512  case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3513  }
3514 }
3515 
3516 static void PrintDSOLocation(const GlobalValue &GV,
3517  formatted_raw_ostream &Out) {
3518  if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
3519  Out << "dso_local ";
3520 }
3521 
3523  formatted_raw_ostream &Out) {
3524  switch (SCT) {
3525  case GlobalValue::DefaultStorageClass: break;
3526  case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3527  case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3528  }
3529 }
3530 
3531 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3532  formatted_raw_ostream &Out) {
3533  switch (TLM) {
3534  case GlobalVariable::NotThreadLocal:
3535  break;
3536  case GlobalVariable::GeneralDynamicTLSModel:
3537  Out << "thread_local ";
3538  break;
3539  case GlobalVariable::LocalDynamicTLSModel:
3540  Out << "thread_local(localdynamic) ";
3541  break;
3542  case GlobalVariable::InitialExecTLSModel:
3543  Out << "thread_local(initialexec) ";
3544  break;
3545  case GlobalVariable::LocalExecTLSModel:
3546  Out << "thread_local(localexec) ";
3547  break;
3548  }
3549 }
3550 
3551 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3552  switch (UA) {
3554  return "";
3555  case GlobalVariable::UnnamedAddr::Local:
3556  return "local_unnamed_addr";
3557  case GlobalVariable::UnnamedAddr::Global:
3558  return "unnamed_addr";
3559  }
3560  llvm_unreachable("Unknown UnnamedAddr");
3561 }
3562 
3564  const GlobalObject &GO) {
3565  const Comdat *C = GO.getComdat();
3566  if (!C)
3567  return;
3568 
3569  if (isa<GlobalVariable>(GO))
3570  Out << ',';
3571  Out << " comdat";
3572 
3573  if (GO.getName() == C->getName())
3574  return;
3575 
3576  Out << '(';
3577  PrintLLVMName(Out, C->getName(), ComdatPrefix);
3578  Out << ')';
3579 }
3580 
3581 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3582  if (GV->isMaterializable())
3583  Out << "; Materializable\n";
3584 
3585  AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
3586  WriteAsOperandInternal(Out, GV, WriterCtx);
3587  Out << " = ";
3588 
3589  if (!GV->hasInitializer() && GV->hasExternalLinkage())
3590  Out << "external ";
3591 
3592  Out << getLinkageNameWithSpace(GV->getLinkage());
3593  PrintDSOLocation(*GV, Out);
3594  PrintVisibility(GV->getVisibility(), Out);
3598  if (!UA.empty())
3599  Out << UA << ' ';
3600 
3601  if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3602  Out << "addrspace(" << AddressSpace << ") ";
3603  if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3604  Out << (GV->isConstant() ? "constant " : "global ");
3605  TypePrinter.print(GV->getValueType(), Out);
3606 
3607  if (GV->hasInitializer()) {
3608  Out << ' ';
3609  writeOperand(GV->getInitializer(), false);
3610  }
3611 
3612  if (GV->hasSection()) {
3613  Out << ", section \"";
3614  printEscapedString(GV->getSection(), Out);
3615  Out << '"';
3616  }
3617  if (GV->hasPartition()) {
3618  Out << ", partition \"";
3619  printEscapedString(GV->getPartition(), Out);
3620  Out << '"';
3621  }
3622 
3624  if (GV->hasSanitizerMetadata()) {
3626  if (MD.NoAddress)
3627  Out << ", no_sanitize_address";
3628  if (MD.NoHWAddress)
3629  Out << ", no_sanitize_hwaddress";
3630  if (MD.Memtag)
3631  Out << ", sanitize_memtag";
3632  if (MD.IsDynInit)
3633  Out << ", sanitize_address_dyninit";
3634  }
3635 
3636  maybePrintComdat(Out, *GV);
3637  if (MaybeAlign A = GV->getAlign())
3638  Out << ", align " << A->value();
3639 
3641  GV->getAllMetadata(MDs);
3642  printMetadataAttachments(MDs, ", ");
3643 
3644  auto Attrs = GV->getAttributes();
3645  if (Attrs.hasAttributes())
3646  Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3647 
3648  printInfoComment(*GV);
3649 }
3650 
3651 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
3652  if (GA->isMaterializable())
3653  Out << "; Materializable\n";
3654 
3655  AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
3656  WriteAsOperandInternal(Out, GA, WriterCtx);
3657  Out << " = ";
3658 
3659  Out << getLinkageNameWithSpace(GA->getLinkage());
3660  PrintDSOLocation(*GA, Out);
3661  PrintVisibility(GA->getVisibility(), Out);
3665  if (!UA.empty())
3666  Out << UA << ' ';
3667 
3668  Out << "alias ";
3669 
3670  TypePrinter.print(GA->getValueType(), Out);
3671  Out << ", ";
3672 
3673  if (const Constant *Aliasee = GA->getAliasee()) {
3674  writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
3675  } else {
3676  TypePrinter.print(GA->getType(), Out);
3677  Out << " <<NULL ALIASEE>>";
3678  }
3679 
3680  if (GA->hasPartition()) {
3681  Out << ", partition \"";
3682  printEscapedString(GA->getPartition(), Out);
3683  Out << '"';
3684  }
3685 
3686  printInfoComment(*GA);
3687  Out << '\n';
3688 }
3689 
3690 void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
3691  if (GI->isMaterializable())
3692  Out << "; Materializable\n";
3693 
3694  AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
3695  WriteAsOperandInternal(Out, GI, WriterCtx);
3696  Out << " = ";
3697 
3698  Out << getLinkageNameWithSpace(GI->getLinkage());
3699  PrintDSOLocation(*GI, Out);
3700  PrintVisibility(GI->getVisibility(), Out);
3701 
3702  Out << "ifunc ";
3703 
3704  TypePrinter.print(GI->getValueType(), Out);
3705  Out << ", ";
3706 
3707  if (const Constant *Resolver = GI->getResolver()) {
3708  writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
3709  } else {
3710  TypePrinter.print(GI->getType(), Out);
3711  Out << " <<NULL RESOLVER>>";
3712  }
3713 
3714  if (GI->hasPartition()) {
3715  Out << ", partition \"";
3716  printEscapedString(GI->getPartition(), Out);
3717  Out << '"';
3718  }
3719 
3720  printInfoComment(*GI);
3721  Out << '\n';
3722 }
3723 
3724 void AssemblyWriter::printComdat(const Comdat *C) {
3725  C->print(Out);
3726 }
3727 
3728 void AssemblyWriter::printTypeIdentities() {
3729  if (TypePrinter.empty())
3730  return;
3731 
3732  Out << '\n';
3733 
3734  // Emit all numbered types.
3735  auto &NumberedTypes = TypePrinter.getNumberedTypes();
3736  for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3737  Out << '%' << I << " = type ";
3738 
3739  // Make sure we print out at least one level of the type structure, so
3740  // that we do not get %2 = type %2
3741  TypePrinter.printStructBody(NumberedTypes[I], Out);
3742  Out << '\n';
3743  }
3744 
3745  auto &NamedTypes = TypePrinter.getNamedTypes();
3746  for (StructType *NamedType : NamedTypes) {
3747  PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
3748  Out << " = type ";
3749 
3750  // Make sure we print out at least one level of the type structure, so
3751  // that we do not get %FILE = type %FILE
3752  TypePrinter.printStructBody(NamedType, Out);
3753  Out << '\n';
3754  }
3755 }
3756 
3757 /// printFunction - Print all aspects of a function.
3758 void AssemblyWriter::printFunction(const Function *F) {
3759  if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3760 
3761  if (F->isMaterializable())
3762  Out << "; Materializable\n";
3763 
3764  const AttributeList &Attrs = F->getAttributes();
3765  if (Attrs.hasFnAttrs()) {
3766  AttributeSet AS = Attrs.getFnAttrs();
3767  std::string AttrStr;
3768 
3769  for (const Attribute &Attr : AS) {
3770  if (!Attr.isStringAttribute()) {
3771  if (!AttrStr.empty()) AttrStr += ' ';
3772  AttrStr += Attr.getAsString();
3773  }
3774  }
3775 
3776  if (!AttrStr.empty())
3777  Out << "; Function Attrs: " << AttrStr << '\n';
3778  }
3779 
3780  Machine.incorporateFunction(F);
3781 
3782  if (F->isDeclaration()) {
3783  Out << "declare";
3785  F->getAllMetadata(MDs);
3786  printMetadataAttachments(MDs, " ");
3787  Out << ' ';
3788  } else
3789  Out << "define ";
3790 
3791  Out << getLinkageNameWithSpace(F->getLinkage());
3792  PrintDSOLocation(*F, Out);
3793  PrintVisibility(F->getVisibility(), Out);
3794  PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3795 
3796  // Print the calling convention.
3797  if (F->getCallingConv() != CallingConv::C) {
3798  PrintCallingConv(F->getCallingConv(), Out);
3799  Out << " ";
3800  }
3801 
3802  FunctionType *FT = F->getFunctionType();
3803  if (Attrs.hasRetAttrs())
3804  Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3805  TypePrinter.print(F->getReturnType(), Out);
3806  AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
3807  Out << ' ';
3808  WriteAsOperandInternal(Out, F, WriterCtx);
3809  Out << '(';
3810 
3811  // Loop over the arguments, printing them...
3812  if (F->isDeclaration() && !IsForDebug) {
3813  // We're only interested in the type here - don't print argument names.
3814  for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3815  // Insert commas as we go... the first arg doesn't get a comma
3816  if (I)
3817  Out << ", ";
3818  // Output type...
3819  TypePrinter.print(FT->getParamType(I), Out);
3820 
3821  AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
3822  if (ArgAttrs.hasAttributes()) {
3823  Out << ' ';
3824  writeAttributeSet(ArgAttrs);
3825  }
3826  }
3827  } else {
3828  // The arguments are meaningful here, print them in detail.
3829  for (const Argument &Arg : F->args()) {
3830  // Insert commas as we go... the first arg doesn't get a comma
3831  if (Arg.getArgNo() != 0)
3832  Out << ", ";
3833  printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
3834  }
3835  }
3836 
3837  // Finish printing arguments...
3838  if (FT->isVarArg()) {
3839  if (FT->getNumParams()) Out << ", ";
3840  Out << "..."; // Output varargs portion of signature!
3841  }
3842  Out << ')';
3843  StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3844  if (!UA.empty())
3845  Out << ' ' << UA;
3846  // We print the function address space if it is non-zero or if we are writing
3847  // a module with a non-zero program address space or if there is no valid
3848  // Module* so that the file can be parsed without the datalayout string.
3849  const Module *Mod = F->getParent();
3850  if (F->getAddressSpace() != 0 || !Mod ||
3852  Out << " addrspace(" << F->getAddressSpace() << ")";
3853  if (Attrs.hasFnAttrs())
3854  Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
3855  if (F->hasSection()) {
3856  Out << " section \"";
3857  printEscapedString(F->getSection(), Out);
3858  Out << '"';
3859  }
3860  if (F->hasPartition()) {
3861  Out << " partition \"";
3862  printEscapedString(F->getPartition(), Out);
3863  Out << '"';
3864  }
3865  maybePrintComdat(Out, *F);
3866  if (MaybeAlign A = F->getAlign())
3867  Out << " align " << A->value();
3868  if (F->hasGC())
3869  Out << " gc \"" << F->getGC() << '"';
3870  if (F->hasPrefixData()) {
3871  Out << " prefix ";
3872  writeOperand(F->getPrefixData(), true);
3873  }
3874  if (F->hasPrologueData()) {
3875  Out << " prologue ";
3876  writeOperand(F->getPrologueData(), true);
3877  }
3878  if (F->hasPersonalityFn()) {
3879  Out << " personality ";
3880  writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3881  }
3882 
3883  if (F->isDeclaration()) {
3884  Out << '\n';
3885  } else {
3887  F->getAllMetadata(MDs);
3888  printMetadataAttachments(MDs, " ");
3889 
3890  Out << " {";
3891  // Output all of the function's basic blocks.
3892  for (const BasicBlock &BB : *F)
3893  printBasicBlock(&BB);
3894 
3895  // Output the function's use-lists.
3896  printUseLists(F);
3897 
3898  Out << "}\n";
3899  }
3900 
3901  Machine.purgeFunction();
3902 }
3903 
3904 /// printArgument - This member is called for every argument that is passed into
3905 /// the function. Simply print it out
3906 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3907  // Output type...
3908  TypePrinter.print(Arg->getType(), Out);
3909 
3910  // Output parameter attributes list
3911  if (Attrs.hasAttributes()) {
3912  Out << ' ';
3913  writeAttributeSet(Attrs);
3914  }
3915 
3916  // Output name, if available...
3917  if (Arg->hasName()) {
3918  Out << ' ';
3919  PrintLLVMName(Out, Arg);
3920  } else {
3921  int Slot = Machine.getLocalSlot(Arg);
3922  assert(Slot != -1 && "expect argument in function here");
3923  Out << " %" << Slot;
3924  }
3925 }
3926 
3927 /// printBasicBlock - This member is called for each basic block in a method.
3928 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3929  bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
3930  if (BB->hasName()) { // Print out the label if it exists...
3931  Out << "\n";
3932  PrintLLVMName(Out, BB->getName(), LabelPrefix);
3933  Out << ':';
3934  } else if (!IsEntryBlock) {
3935  Out << "\n";
3936  int Slot = Machine.getLocalSlot(BB);
3937  if (Slot != -1)
3938  Out << Slot << ":";
3939  else
3940  Out << "<badref>:";
3941  }
3942 
3943  if (!IsEntryBlock) {
3944  // Output predecessors for the block.
3945  Out.PadToColumn(50);
3946  Out << ";";
3948 
3949  if (PI == PE) {
3950  Out << " No predecessors!";
3951  } else {
3952  Out << " preds = ";
3953  writeOperand(*PI, false);
3954  for (++PI; PI != PE; ++PI) {
3955  Out << ", ";
3956  writeOperand(*PI, false);
3957  }
3958  }
3959  }
3960 
3961  Out << "\n";
3962 
3963  if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3964 
3965  // Output all of the instructions in the basic block...
3966  for (const Instruction &I : *BB) {
3967  printInstructionLine(I);
3968  }
3969 
3970  if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3971 }
3972 
3973 /// printInstructionLine - Print an instruction and a newline character.
3974 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3975  printInstruction(I);
3976  Out << '\n';
3977 }
3978 
3979 /// printGCRelocateComment - print comment after call to the gc.relocate
3980 /// intrinsic indicating base and derived pointer names.
3981 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3982  Out << " ; (";
3983  writeOperand(Relocate.getBasePtr(), false);
3984  Out << ", ";
3985  writeOperand(Relocate.getDerivedPtr(), false);
3986  Out << ")";
3987 }
3988 
3989 /// printInfoComment - Print a little comment after the instruction indicating
3990 /// which slot it occupies.
3991 void AssemblyWriter::printInfoComment(const Value &V) {
3992  if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3993  printGCRelocateComment(*Relocate);
3994 
3995  if (AnnotationWriter)
3996  AnnotationWriter->printInfoComment(V, Out);
3997 }
3998 
3999 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
4000  raw_ostream &Out) {
4001  // We print the address space of the call if it is non-zero.
4002  unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
4003  bool PrintAddrSpace = CallAddrSpace != 0;
4004  if (!PrintAddrSpace) {
4005  const Module *Mod = getModuleFromVal(I);
4006  // We also print it if it is zero but not equal to the program address space
4007  // or if we can't find a valid Module* to make it possible to parse
4008  // the resulting file even without a datalayout string.
4009  if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
4010  PrintAddrSpace = true;
4011  }
4012  if (PrintAddrSpace)
4013  Out << " addrspace(" << CallAddrSpace << ")";
4014 }
4015 
4016 // This member is called for each Instruction in a function..
4017 void AssemblyWriter::printInstruction(const Instruction &I) {
4018  if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
4019 
4020  // Print out indentation for an instruction.
4021  Out << " ";
4022 
4023  // Print out name if it exists...
4024  if (I.hasName()) {
4025  PrintLLVMName(Out, &I);
4026  Out << " = ";
4027  } else if (!I.getType()->isVoidTy()) {
4028  // Print out the def slot taken.
4029  int SlotNum = Machine.getLocalSlot(&I);
4030  if (SlotNum == -1)
4031  Out << "<badref> = ";
4032  else
4033  Out << '%' << SlotNum << " = ";
4034  }
4035 
4036  if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4037  if (CI->isMustTailCall())
4038  Out << "musttail ";
4039  else if (CI->isTailCall())
4040  Out << "tail ";
4041  else if (CI->isNoTailCall())
4042  Out << "notail ";
4043  }
4044 
4045  // Print out the opcode...
4046  Out << I.getOpcodeName();
4047 
4048  // If this is an atomic load or store, print out the atomic marker.
4049  if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
4050  (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
4051  Out << " atomic";
4052 
4053  if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
4054  Out << " weak";
4055 
4056  // If this is a volatile operation, print out the volatile marker.
4057  if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
4058  (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
4059  (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
4060  (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
4061  Out << " volatile";
4062 
4063  // Print out optimization information.
4064  WriteOptimizationInfo(Out, &I);
4065 
4066  // Print out the compare instruction predicates
4067  if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
4068  Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
4069 
4070  // Print out the atomicrmw operation
4071  if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
4072  Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
4073 
4074  // Print out the type of the operands...
4075  const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
4076 
4077  // Special case conditional branches to swizzle the condition out to the front
4078  if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
4079  const BranchInst &BI(cast<BranchInst>(I));
4080  Out << ' ';
4081  writeOperand(BI.getCondition(), true);
4082  Out << ", ";
4083  writeOperand(BI.getSuccessor(0), true);
4084  Out << ", ";
4085  writeOperand(BI.getSuccessor(1), true);
4086 
4087  } else if (isa<SwitchInst>(I)) {
4088  const SwitchInst& SI(cast<SwitchInst>(I));
4089  // Special case switch instruction to get formatting nice and correct.
4090  Out << ' ';
4091  writeOperand(SI.getCondition(), true);
4092  Out << ", ";
4093  writeOperand(SI.getDefaultDest(), true);
4094  Out << " [";
4095  for (auto Case : SI.cases()) {
4096  Out << "\n ";
4097  writeOperand(Case.getCaseValue(), true);
4098  Out << ", ";
4099  writeOperand(Case.getCaseSuccessor(), true);
4100  }
4101  Out << "\n ]";
4102  } else if (isa<IndirectBrInst>(I)) {
4103  // Special case indirectbr instruction to get formatting nice and correct.
4104  Out << ' ';
4105  writeOperand(Operand, true);
4106  Out << ", [";
4107 
4108  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
4109  if (i != 1)
4110  Out << ", ";
4111  writeOperand(I.getOperand(i), true);
4112  }
4113  Out << ']';
4114  } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
4115  Out << ' ';
4116  TypePrinter.print(I.getType(), Out);
4117  Out << ' ';
4118 
4119  for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
4120  if (op) Out << ", ";
4121  Out << "[ ";
4122  writeOperand(PN->getIncomingValue(op), false); Out << ", ";
4123  writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
4124  }
4125  } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
4126  Out << ' ';
4127  writeOperand(I.getOperand(0), true);
4128  for (unsigned i : EVI->indices())
4129  Out << ", " << i;
4130  } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
4131  Out << ' ';
4132  writeOperand(I.getOperand(0), true); Out << ", ";
4133  writeOperand(I.getOperand(1), true);
4134  for (unsigned i : IVI->indices())
4135  Out << ", " << i;
4136  } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
4137  Out << ' ';
4138  TypePrinter.print(I.getType(), Out);
4139  if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4140  Out << '\n';
4141 
4142  if (LPI->isCleanup())
4143  Out << " cleanup";
4144 
4145  for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
4146  if (i != 0 || LPI->isCleanup()) Out << "\n";
4147  if (LPI->isCatch(i))
4148  Out << " catch ";
4149  else
4150  Out << " filter ";
4151 
4152  writeOperand(LPI->getClause(i), true);
4153  }
4154  } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
4155  Out << " within ";
4156  writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
4157  Out << " [";
4158  unsigned Op = 0;
4159  for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
4160  if (Op > 0)
4161  Out << ", ";
4162  writeOperand(PadBB, /*PrintType=*/true);
4163  ++Op;
4164  }
4165  Out << "] unwind ";
4166  if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4167  writeOperand(UnwindDest, /*PrintType=*/true);
4168  else
4169  Out << "to caller";
4170  } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
4171  Out << " within ";
4172  writeOperand(FPI->getParentPad(), /*PrintType=*/false);
4173  Out << " [";
4174  for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
4175  if (Op > 0)
4176  Out << ", ";
4177  writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
4178  }
4179  Out << ']';
4180  } else if (isa<ReturnInst>(I) && !Operand) {
4181  Out << " void";
4182  } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
4183  Out << " from ";
4184  writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4185 
4186  Out << " to ";
4187  writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4188  } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
4189  Out << " from ";
4190  writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4191 
4192  Out << " unwind ";
4193  if (CRI->hasUnwindDest())
4194  writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4195  else
4196  Out << "to caller";
4197  } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4198  // Print the calling convention being used.
4199  if (CI->getCallingConv() != CallingConv::C) {
4200  Out << " ";
4201  PrintCallingConv(CI->getCallingConv(), Out);
4202  }
4203 
4204  Operand = CI->getCalledOperand();
4205  FunctionType *FTy = CI->getFunctionType();
4206  Type *RetTy = FTy->getReturnType();
4207  const AttributeList &PAL = CI->getAttributes();
4208 
4209  if (PAL.hasRetAttrs())
4210  Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4211 
4212  // Only print addrspace(N) if necessary:
4213  maybePrintCallAddrSpace(Operand, &I, Out);
4214 
4215  // If possible, print out the short form of the call instruction. We can
4216  // only do this if the first argument is a pointer to a nonvararg function,
4217  // and if the return type is not a pointer to a function.
4218  Out << ' ';
4219  TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4220  Out << ' ';
4221  writeOperand(Operand, false);
4222  Out << '(';
4223  for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
4224  if (op > 0)
4225  Out << ", ";
4226  writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
4227  }
4228 
4229  // Emit an ellipsis if this is a musttail call in a vararg function. This
4230  // is only to aid readability, musttail calls forward varargs by default.
4231  if (CI->isMustTailCall() && CI->getParent() &&
4232  CI->getParent()->getParent() &&
4233  CI->getParent()->getParent()->isVarArg()) {
4234  if (CI->arg_size() > 0)
4235  Out << ", ";
4236  Out << "...";
4237  }
4238 
4239  Out << ')';
4240  if (PAL.hasFnAttrs())
4241  Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4242 
4243  writeOperandBundles(CI);
4244  } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
4245  Operand = II->getCalledOperand();
4246  FunctionType *FTy = II->getFunctionType();
4247  Type *RetTy = FTy->getReturnType();
4248  const AttributeList &PAL = II->getAttributes();
4249 
4250  // Print the calling convention being used.
4251  if (II->getCallingConv() != CallingConv::C) {
4252  Out << " ";
4253  PrintCallingConv(II->getCallingConv(), Out);
4254  }
4255 
4256  if (PAL.hasRetAttrs())
4257  Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4258 
4259  // Only print addrspace(N) if necessary:
4260  maybePrintCallAddrSpace(Operand, &I, Out);
4261 
4262  // If possible, print out the short form of the invoke instruction. We can
4263  // only do this if the first argument is a pointer to a nonvararg function,
4264  // and if the return type is not a pointer to a function.
4265  //
4266  Out << ' ';
4267  TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4268  Out << ' ';
4269  writeOperand(Operand, false);
4270  Out << '(';
4271  for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
4272  if (op)
4273  Out << ", ";
4274  writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
4275  }
4276 
4277  Out << ')';
4278  if (PAL.hasFnAttrs())
4279  Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4280 
4281  writeOperandBundles(II);
4282 
4283  Out << "\n to ";
4284  writeOperand(II->getNormalDest(), true);
4285  Out << " unwind ";
4286  writeOperand(II->getUnwindDest(), true);
4287  } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
4288  Operand = CBI->getCalledOperand();
4289  FunctionType *FTy = CBI->getFunctionType();
4290  Type *RetTy = FTy->getReturnType();
4291  const AttributeList &PAL = CBI->getAttributes();
4292 
4293  // Print the calling convention being used.
4294  if (CBI->getCallingConv() != CallingConv::C) {
4295  Out << " ";
4296  PrintCallingConv(CBI->getCallingConv(), Out);
4297  }
4298 
4299  if (PAL.hasRetAttrs())
4300  Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4301 
4302  // If possible, print out the short form of the callbr instruction. We can
4303  // only do this if the first argument is a pointer to a nonvararg function,
4304  // and if the return type is not a pointer to a function.
4305  //
4306  Out << ' ';
4307  TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4308  Out << ' ';
4309  writeOperand(Operand, false);
4310  Out << '(';
4311  for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
4312  if (op)
4313  Out << ", ";
4314  writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
4315  }
4316 
4317  Out << ')';
4318  if (PAL.hasFnAttrs())
4319  Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4320 
4321  writeOperandBundles(CBI);
4322 
4323  Out << "\n to ";
4324  writeOperand(CBI->getDefaultDest(), true);
4325  Out << " [";
4326  for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
4327  if (i != 0)
4328  Out << ", ";
4329  writeOperand(CBI->getIndirectDest(i), true);
4330  }
4331  Out << ']';
4332  } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4333  Out << ' ';
4334  if (AI->isUsedWithInAlloca())
4335  Out << "inalloca ";
4336  if (AI->isSwiftError())
4337  Out << "swifterror ";
4338  TypePrinter.print(AI->getAllocatedType(), Out);
4339 
4340  // Explicitly write the array size if the code is broken, if it's an array
4341  // allocation, or if the type is not canonical for scalar allocations. The
4342  // latter case prevents the type from mutating when round-tripping through
4343  // assembly.
4344  if (!AI->getArraySize() || AI->isArrayAllocation() ||
4345  !AI->getArraySize()->getType()->isIntegerTy(32)) {
4346  Out << ", ";
4347  writeOperand(AI->getArraySize(), true);
4348  }
4349  if (MaybeAlign A = AI->getAlign()) {
4350  Out << ", align " << A->value();
4351  }
4352 
4353  unsigned AddrSpace = AI->getAddressSpace();
4354  if (AddrSpace != 0) {
4355  Out << ", addrspace(" << AddrSpace << ')';
4356  }
4357  } else if (isa<CastInst>(I)) {
4358  if (Operand) {
4359  Out << ' ';
4360  writeOperand(Operand, true); // Work with broken code
4361  }
4362  Out << " to ";
4363  TypePrinter.print(I.getType(), Out);
4364  } else if (isa<VAArgInst>(I)) {
4365  if (Operand) {
4366  Out << ' ';
4367  writeOperand(Operand, true); // Work with broken code
4368  }
4369  Out << ", ";
4370  TypePrinter.print(I.getType(), Out);
4371  } else if (Operand) { // Print the normal way.
4372  if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4373  Out << ' ';
4374  TypePrinter.print(GEP->getSourceElementType(), Out);
4375  Out << ',';
4376  } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4377  Out << ' ';
4378  TypePrinter.print(LI->getType(), Out);
4379  Out << ',';
4380  }
4381 
4382  // PrintAllTypes - Instructions who have operands of all the same type
4383  // omit the type from all but the first operand. If the instruction has
4384  // different type operands (for example br), then they are all printed.
4385  bool PrintAllTypes = false;
4386  Type *TheType = Operand->getType();
4387 
4388  // Select, Store, ShuffleVector and CmpXchg always print all types.
4389  if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
4390  isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I)) {
4391  PrintAllTypes = true;
4392  } else {
4393  for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4394  Operand = I.getOperand(i);
4395  // note that Operand shouldn't be null, but the test helps make dump()
4396  // more tolerant of malformed IR
4397  if (Operand && Operand->getType() != TheType) {
4398  PrintAllTypes = true; // We have differing types! Print them all!
4399  break;
4400  }
4401  }
4402  }
4403 
4404  if (!PrintAllTypes) {
4405  Out << ' ';
4406  TypePrinter.print(TheType, Out);
4407  }
4408 
4409  Out << ' ';
4410  for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4411  if (i) Out << ", ";
4412  writeOperand(I.getOperand(i), PrintAllTypes);
4413  }
4414  }
4415 
4416  // Print atomic ordering/alignment for memory operations
4417  if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4418  if (LI->isAtomic())
4419  writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4420  if (MaybeAlign A = LI->getAlign())
4421  Out << ", align " << A->value();
4422  } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4423  if (SI->isAtomic())
4424  writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4425  if (MaybeAlign A = SI->getAlign())
4426  Out << ", align " << A->value();
4427  } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4428  writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4429  CXI->getFailureOrdering(), CXI->getSyncScopeID());
4430  Out << ", align " << CXI->getAlign().value();
4431  } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4432  writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4433  RMWI->getSyncScopeID());
4434  Out << ", align " << RMWI->getAlign().value();
4435  } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4436  writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4437  } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
4438  PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
4439  }
4440 
4441  // Print Metadata info.
4443  I.getAllMetadata(InstMD);
4444  printMetadataAttachments(InstMD, ", ");
4445 
4446  // Print a nice comment.
4447  printInfoComment(I);
4448 }
4449 
4450 void AssemblyWriter::printMetadataAttachments(
4451  const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4452  StringRef Separator) {
4453  if (MDs.empty())
4454  return;
4455 
4456  if (MDNames.empty())
4457  MDs[0].second->getContext().getMDKindNames(MDNames);
4458 
4459  auto WriterCtx = getContext();
4460  for (const auto &I : MDs) {
4461  unsigned Kind = I.first;
4462  Out << Separator;
4463  if (Kind < MDNames.size()) {
4464  Out << "!";
4465  printMetadataIdentifier(MDNames[Kind], Out);
4466  } else
4467  Out << "!<unknown kind #" << Kind << ">";
4468  Out << ' ';
4469  WriteAsOperandInternal(Out, I.second, WriterCtx);
4470  }
4471 }
4472 
4473 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4474  Out << '!' << Slot << " = ";
4475  printMDNodeBody(Node);
4476  Out << "\n";
4477 }
4478 
4479 void AssemblyWriter::writeAllMDNodes() {
4481  Nodes.resize(Machine.mdn_size());
4482  for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
4483  Nodes[I.second] = cast<MDNode>(I.first);
4484 
4485  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4486  writeMDNode(i, Nodes[i]);
4487  }
4488 }
4489 
4490 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4491  auto WriterCtx = getContext();
4492  WriteMDNodeBodyInternal(Out, Node, WriterCtx);
4493 }
4494 
4495 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4496  if (!Attr.isTypeAttribute()) {
4497  Out << Attr.getAsString(InAttrGroup);
4498  return;
4499  }
4500 
4501  Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());
4502  if (Type *Ty = Attr.getValueAsType()) {
4503  Out << '(';
4504  TypePrinter.print(Ty, Out);
4505  Out << ')';
4506  }
4507 }
4508 
4509 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4510  bool InAttrGroup) {
4511  bool FirstAttr = true;
4512  for (const auto &Attr : AttrSet) {
4513  if (!FirstAttr)
4514  Out << ' ';
4515  writeAttribute(Attr, InAttrGroup);
4516  FirstAttr = false;
4517  }
4518 }
4519 
4520 void AssemblyWriter::writeAllAttributeGroups() {
4521  std::vector<std::pair<AttributeSet, unsigned>> asVec;
4522  asVec.resize(Machine.as_size());
4523 
4524  for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
4525  asVec[I.second] = I;
4526 
4527  for (const auto &I : asVec)
4528  Out << "attributes #" << I.second << " = { "
4529  << I.first.getAsString(true) << " }\n";
4530 }
4531 
4532 void AssemblyWriter::printUseListOrder(const Value *V,
4533  const std::vector<unsigned> &Shuffle) {
4534  bool IsInFunction = Machine.getFunction();
4535  if (IsInFunction)
4536  Out << " ";
4537 
4538  Out << "uselistorder";
4539  if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
4540  Out << "_bb ";
4541  writeOperand(BB->getParent(), false);
4542  Out << ", ";
4543  writeOperand(BB, false);
4544  } else {
4545  Out << " ";
4546  writeOperand(V, true);
4547  }
4548  Out << ", { ";
4549 
4550  assert(Shuffle.size() >= 2 && "Shuffle too small");
4551  Out << Shuffle[0];
4552  for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)
4553  Out << ", " << Shuffle[I];
4554  Out << " }\n";
4555 }
4556 
4557 void AssemblyWriter::printUseLists(const Function *F) {
4558  auto It = UseListOrders.find(F);
4559  if (It == UseListOrders.end())
4560  return;
4561 
4562  Out << "\n; uselistorder directives\n";
4563  for (const auto &Pair : It->second)
4564  printUseListOrder(Pair.first, Pair.second);
4565 }
4566 
4567 //===----------------------------------------------------------------------===//
4568 // External Interface declarations
4569 //===----------------------------------------------------------------------===//
4570 
4572  bool ShouldPreserveUseListOrder,
4573  bool IsForDebug) const {
4574  SlotTracker SlotTable(this->getParent());
4575  formatted_raw_ostream OS(ROS);
4576  AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4577  IsForDebug,
4578  ShouldPreserveUseListOrder);
4579  W.printFunction(this);
4580 }
4581 
4583  bool ShouldPreserveUseListOrder,
4584  bool IsForDebug) const {
4585  SlotTracker SlotTable(this->getParent());
4586  formatted_raw_ostream OS(ROS);
4587  AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
4588  IsForDebug,
4589  ShouldPreserveUseListOrder);
4590  W.printBasicBlock(this);
4591 }
4592 
4594  bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4595  SlotTracker SlotTable(this);
4596  formatted_raw_ostream OS(ROS);
4597  AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4598  ShouldPreserveUseListOrder);
4599  W.printModule(this);
4600 }
4601 
4602 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4603  SlotTracker SlotTable(getParent());
4604  formatted_raw_ostream OS(ROS);
4605  AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4606  W.printNamedMDNode(this);
4607 }
4608 
4610  bool IsForDebug) const {
4611  std::optional<SlotTracker> LocalST;
4612  SlotTracker *SlotTable;
4613  if (auto *ST = MST.getMachine())
4614  SlotTable = ST;
4615  else {
4616  LocalST.emplace(getParent());
4617  SlotTable = &*LocalST;
4618  }
4619 
4620  formatted_raw_ostream OS(ROS);
4621  AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4622  W.printNamedMDNode(this);
4623 }
4624 
4625 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4627  ROS << " = comdat ";
4628 
4629  switch (getSelectionKind()) {
4630  case Comdat::Any:
4631  ROS << "any";
4632  break;
4633  case Comdat::ExactMatch:
4634  ROS << "exactmatch";
4635  break;
4636  case Comdat::Largest:
4637  ROS << "largest";
4638  break;
4639  case Comdat::NoDeduplicate:
4640  ROS << "nodeduplicate";
4641  break;
4642  case Comdat::SameSize:
4643  ROS << "samesize";
4644  break;
4645  }
4646 
4647  ROS << '\n';
4648 }
4649 
4650 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4651  TypePrinting TP;
4652  TP.print(const_cast<Type*>(this), OS);
4653 
4654  if (NoDetails)
4655  return;
4656 
4657  // If the type is a named struct type, print the body as well.
4658  if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4659  if (!STy->isLiteral()) {
4660  OS << " = type ";
4661  TP.printStructBody(STy, OS);
4662  }
4663 }
4664 
4665 static bool isReferencingMDNode(const Instruction &I) {
4666  if (const auto *CI = dyn_cast<CallInst>(&I))
4667  if (Function *F = CI->getCalledFunction())
4668  if (F->isIntrinsic())
4669  for (auto &Op : I.operands())
4670  if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4671  if (isa<MDNode>(V->getMetadata()))
4672  return true;
4673  return false;
4674 }
4675 
4676 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4677  bool ShouldInitializeAllMetadata = false;
4678  if (auto *I = dyn_cast<Instruction>(this))
4679  ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4680  else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4681  ShouldInitializeAllMetadata = true;
4682 
4683  ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4684  print(ROS, MST, IsForDebug);
4685 }
4686 
4688  bool IsForDebug) const {
4689  formatted_raw_ostream OS(ROS);
4690  SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4691  SlotTracker &SlotTable =
4692  MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4693  auto incorporateFunction = [&](const Function *F) {
4694  if (F)
4695  MST.incorporateFunction(*F);
4696  };
4697 
4698  if (const Instruction *I = dyn_cast<Instruction>(this)) {
4699  incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4700  AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4701  W.printInstruction(*I);
4702  } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4703  incorporateFunction(BB->getParent());
4704  AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4705  W.printBasicBlock(BB);
4706  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4707  AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4708  if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4709  W.printGlobal(V);
4710  else if (const Function *F = dyn_cast<Function>(GV))
4711  W.printFunction(F);
4712  else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
4713  W.printAlias(A);
4714  else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
4715  W.printIFunc(I);
4716  else
4717  llvm_unreachable("Unknown GlobalValue to print out!");
4718  } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4719  V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4720  } else if (const Constant *C = dyn_cast<Constant>(this)) {
4721  TypePrinting TypePrinter;
4722  TypePrinter.print(C->getType(), OS);
4723  OS << ' ';
4724  AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
4725  WriteConstantInternal(OS, C, WriterCtx);
4726  } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4727  this->printAsOperand(OS, /* PrintType */ true, MST);
4728  } else {
4729  llvm_unreachable("Unknown value to print out!");
4730  }
4731 }
4732 
4733 /// Print without a type, skipping the TypePrinting object.
4734 ///
4735 /// \return \c true iff printing was successful.
4736 static bool printWithoutType(const Value &V, raw_ostream &O,
4737  SlotTracker *Machine, const Module *M) {
4738  if (V.hasName() || isa<GlobalValue>(V) ||
4739  (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4740  AsmWriterContext WriterCtx(nullptr, Machine, M);
4741  WriteAsOperandInternal(O, &V, WriterCtx);
4742  return true;
4743  }
4744  return false;
4745 }
4746 
4747 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4748  ModuleSlotTracker &MST) {
4749  TypePrinting TypePrinter(MST.getModule());
4750  if (PrintType) {
4751  TypePrinter.print(V.getType(), O);
4752  O << ' ';
4753  }
4754 
4755  AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
4756  WriteAsOperandInternal(O, &V, WriterCtx);
4757 }
4758 
4759 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4760  const Module *M) const {
4761  if (!M)
4762  M = getModuleFromVal(this);
4763 
4764  if (!PrintType)
4765  if (printWithoutType(*this, O, nullptr, M))
4766  return;
4767 
4769  M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4770  ModuleSlotTracker MST(Machine, M);
4771  printAsOperandImpl(*this, O, PrintType, MST);
4772 }
4773 
4774 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4775  ModuleSlotTracker &MST) const {
4776  if (!PrintType)
4777  if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4778  return;
4779 
4780  printAsOperandImpl(*this, O, PrintType, MST);
4781 }
4782 
4783 /// Recursive version of printMetadataImpl.
4784 static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
4785  AsmWriterContext &WriterCtx) {
4786  formatted_raw_ostream OS(ROS);
4787  WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
4788 
4789  auto *N = dyn_cast<MDNode>(&MD);
4790  if (!N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4791  return;
4792 
4793  OS << " = ";
4794  WriteMDNodeBodyInternal(OS, N, WriterCtx);
4795 }
4796 
4797 namespace {
4798 struct MDTreeAsmWriterContext : public AsmWriterContext {
4799  unsigned Level;
4800  // {Level, Printed string}
4801  using EntryTy = std::pair<unsigned, std::string>;
4802  SmallVector<EntryTy, 4> Buffer;
4803 
4804  // Used to break the cycle in case there is any.
4806 
4807  raw_ostream &MainOS;
4808 
4809  MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
4810  raw_ostream &OS, const Metadata *InitMD)
4811  : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
4812 
4813  void onWriteMetadataAsOperand(const Metadata *MD) override {
4814  if (!Visited.insert(MD).second)
4815  return;
4816 
4817  std::string Str;
4818  raw_string_ostream SS(Str);
4819  ++Level;
4820  // A placeholder entry to memorize the correct
4821  // position in buffer.
4822  Buffer.emplace_back(std::make_pair(Level, ""));
4823  unsigned InsertIdx = Buffer.size() - 1;
4824 
4825  printMetadataImplRec(SS, *MD, *this);
4826  Buffer[InsertIdx].second = std::move(SS.str());
4827  --Level;
4828  }
4829 
4830  ~MDTreeAsmWriterContext() {
4831  for (const auto &Entry : Buffer) {
4832  MainOS << "\n";
4833  unsigned NumIndent = Entry.first * 2U;
4834  MainOS.indent(NumIndent) << Entry.second;
4835  }
4836  }
4837 };
4838 } // end anonymous namespace
4839 
4840 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4841  ModuleSlotTracker &MST, const Module *M,
4842  bool OnlyAsOperand, bool PrintAsTree = false) {
4843  formatted_raw_ostream OS(ROS);
4844 
4845  TypePrinting TypePrinter(M);
4846 
4847  std::unique_ptr<AsmWriterContext> WriterCtx;
4848  if (PrintAsTree && !OnlyAsOperand)
4849  WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
4850  &TypePrinter, MST.getMachine(), M, OS, &MD);
4851  else
4852  WriterCtx =
4853  std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
4854 
4855  WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
4856 
4857  auto *N = dyn_cast<MDNode>(&MD);
4858  if (OnlyAsOperand || !N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4859  return;
4860 
4861  OS << " = ";
4862  WriteMDNodeBodyInternal(OS, N, *WriterCtx);
4863 }
4864 
4865 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4866  ModuleSlotTracker MST(M, isa<MDNode>(this));
4867  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4868 }
4869 
4871  const Module *M) const {
4872  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4873 }
4874 
4876  bool /*IsForDebug*/) const {
4877  ModuleSlotTracker MST(M, isa<MDNode>(this));
4878  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4879 }
4880 
4882  const Module *M, bool /*IsForDebug*/) const {
4883  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4884 }
4885 
4886 void MDNode::printTree(raw_ostream &OS, const Module *M) const {
4887  ModuleSlotTracker MST(M, true);
4888  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
4889  /*PrintAsTree=*/true);
4890 }
4891 
4893  const Module *M) const {
4894  printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
4895  /*PrintAsTree=*/true);
4896 }
4897 
4898 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4899  SlotTracker SlotTable(this);
4900  formatted_raw_ostream OS(ROS);
4901  AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4902  W.printModuleSummaryIndex();
4903 }
4904 
4906  unsigned UB) const {
4907  SlotTracker *ST = MachineStorage.get();
4908  if (!ST)
4909  return;
4910 
4911  for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
4912  if (I.second >= LB && I.second < UB)
4913  L.push_back(std::make_pair(I.second, I.first));
4914 }
4915 
4916 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4917 // Value::dump - allow easy printing of Values from the debugger.
4919 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4920 
4921 // Type::dump - allow easy printing of Types from the debugger.
4923 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4924 
4925 // Module::dump() - Allow printing of Modules from the debugger.
4927 void Module::dump() const {
4928  print(dbgs(), nullptr,
4929  /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4930 }
4931 
4932 // Allow printing of Comdats from the debugger.
4934 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4935 
4936 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4938 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4939 
4941 void Metadata::dump() const { dump(nullptr); }
4942 
4944 void Metadata::dump(const Module *M) const {
4945  print(dbgs(), M, /*IsForDebug=*/true);
4946  dbgs() << '\n';
4947 }
4948 
4950 void MDNode::dumpTree() const { dumpTree(nullptr); }
4951 
4953 void MDNode::dumpTree(const Module *M) const {
4954  printTree(dbgs(), M);
4955  dbgs() << '\n';
4956 }
4957 
4958 // Allow printing of ModuleSummaryIndex from the debugger.
4960 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4961 #endif
llvm::FunctionSummary::TypeIdInfo
All type identifier related information.
Definition: ModuleSummaryIndex.h:617
llvm::WholeProgramDevirtResolution::ResByArg
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
Definition: ModuleSummaryIndex.h:1141
i
i
Definition: README.txt:29
llvm::lltok::APFloat
@ APFloat
Definition: LLToken.h:459
llvm::Type::ArrayTyID
@ ArrayTyID
Arrays.
Definition: Type.h:75
llvm::GlobalValue::hasSanitizerMetadata
bool hasSanitizerMetadata() const
Definition: GlobalValue.h:349
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition: Argument.h:28
llvm::BasicBlock::print
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:4582
as
compiles conv shl5 shl ret i32 or10 it would be better as
Definition: README.txt:615
Attrs
Function Attrs
Definition: README_ALTIVEC.txt:215
llvm::Type::FloatTyID
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
llvm::less_second
Function object to check whether the second component of a std::pair compares less than the second co...
Definition: STLExtras.h:1459
llvm::APFloat::isInfinity
bool isInfinity() const
Definition: APFloat.h:1227
llvm::DIArgList
List of ValueAsMetadata, to be used as an argument to a dbg.value intrinsic.
Definition: DebugInfoMetadata.h:3603
llvm::CallingConv::AnyReg
@ AnyReg
Used for dynamic register based calls (e.g.
Definition: CallingConv.h:60
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:108
LLVM_DUMP_METHOD
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:492
llvm::Type::DoubleTyID
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
GlobalIFunc.h
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
predictValueUseListOrder
static std::vector< unsigned > predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM)
Definition: AsmWriter.cpp:178
llvm::ModuleSlotTracker::getModule
const Module * getModule() const
Definition: ModuleSlotTracker.h:80
llvm::CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:239
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
llvm::AttributeSet::hasAttributes
bool hasAttributes() const
Return true if attributes exists in this set.
Definition: Attributes.h:354
it
into xmm2 addss xmm2 xmm1 xmm3 addss xmm3 movaps xmm0 unpcklps xmm0 ret seems silly when it could just be one addps Expand libm rounding functions main should enable SSE DAZ mode and other fast SSE modes Think about doing i64 math in SSE regs on x86 This testcase should have no SSE instructions in it
Definition: README-SSE.txt:81
Comdat.h
llvm::make_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Definition: iterator_range.h:53
llvm::NamedMDNode
A tuple of MDNodes.
Definition: Metadata.h:1588
Optional.h
llvm::StructType::getName
StringRef getName() const
Return the name for this struct type if it has an identity.
Definition: Type.cpp:581
llvm::Comdat::getName
StringRef getName() const
Definition: Comdat.cpp:28
PrintLLVMName
static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix)
Turn the specified name into an 'LLVM name', which is either prefixed with % (if the string only cont...
Definition: AsmWriter.cpp:391
print
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Definition: ArchiveWriter.cpp:189
Metadata.h
llvm::NamedMDNode::getNumOperands
unsigned getNumOperands() const
Definition: Metadata.cpp:1212
llvm::Comdat::ExactMatch
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
llvm::GlobalValue::hasExternalLinkage
bool hasExternalLinkage() const
Definition: GlobalValue.h:504
llvm::BasicBlock::getParent
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:104
IntrinsicInst.h
AtomicOrdering.h
llvm::ElementCount
Definition: TypeSize.h:404
llvm::APFloatBase::IEEEsingle
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:201
DebugInfoMetadata.h
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:161
llvm::GlobalValue::getLinkage
LinkageTypes getLinkage() const
Definition: GlobalValue.h:539
llvm::TypeTestResolution::Kind
Kind
Specifies which kind of type check we should emit for this byte array.
Definition: ModuleSummaryIndex.h:1081
llvm::DataLayout::getProgramAddressSpace
unsigned getProgramAddressSpace() const
Definition: DataLayout.h:295
llvm::GlobalValue::isImplicitDSOLocal
bool isImplicitDSOLocal() const
Definition: GlobalValue.h:292
llvm::Function
Definition: Function.h:60
llvm::Function::print
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the function to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:4571
getTTResKindName
static const char * getTTResKindName(TypeTestResolution::Kind K)
Definition: AsmWriter.cpp:2967
llvm::Attribute
Definition: Attributes.h:66
llvm::CallingConv::PTX_Kernel
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
Definition: CallingConv.h:122
llvm::Type::VoidTyID
@ VoidTyID
type with no size
Definition: Type.h:63
llvm::Module::dump
void dump() const
Dump the module to stderr (for debugging).
Definition: AsmWriter.cpp:4927
llvm::Value::dump
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4919
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
llvm::MDNode::printTree
void printTree(raw_ostream &OS, const Module *M=nullptr) const
Print in tree shape.
Definition: AsmWriter.cpp:4886
llvm::GlobalVarSummary
Global variable summary information to aid decisions and implementation of importing.
Definition: ModuleSummaryIndex.h:1004
llvm::Module::ifuncs
iterator_range< ifunc_iterator > ifuncs()
Definition: Module.h:672
llvm::CallingConv::MSP430_INTR
@ MSP430_INTR
Used for MSP430 interrupt routines.
Definition: CallingConv.h:114
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:628
llvm::GlobalObject::getSection
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:111
llvm::Attribute::isTypeAttribute
bool isTypeAttribute() const
Return true if the attribute is a type attribute.
Definition: Attributes.cpp:280
op
#define op(i)
llvm::Comdat::NoDeduplicate
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1199
llvm::printLLVMNameWithoutPrefix
void printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name)
Print out a name of an LLVM value without any prefixes.
Definition: AsmWriter.cpp:356
llvm::RISCVFenceField::W
@ W
Definition: RISCVBaseInfo.h:266
llvm::GlobalObject::getAlign
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:79
InlineAsm.h
llvm::LandingPadInst
The landingpad instruction holds all of the information necessary to generate correct exception handl...
Definition: Instructions.h:2950
llvm::GlobalVariable::isExternallyInitialized
bool isExternallyInitialized() const
Definition: GlobalVariable.h:155
llvm::CallingConv::AMDGPU_CS
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:198
llvm::SlotTracker::getTypeIdSlot
int getTypeIdSlot(StringRef Id)
Definition: AsmWriter.cpp:1201
llvm::TypeTestResolution::InlineBits
uint64_t InlineBits
Definition: ModuleSummaryIndex.h:1104
llvm::Value::hasName
bool hasName() const
Definition: Value.h:261
ErrorHandling.h
llvm::Type::getPointerAddressSpace
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:729
llvm::GlobalVariable
Definition: GlobalVariable.h:39
llvm::PointerType::getAddressSpace
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:682
llvm::CallingConv::Cold
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition: CallingConv.h:47
llvm::Type::X86_AMXTyID
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition: Type.h:67
llvm::GlobalAlias
Definition: GlobalAlias.h:28
llvm::AliasSummary
Alias summary information.
Definition: ModuleSummaryIndex.h:522
llvm::Type::getTypeID
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:136
writeDIArgList
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
Definition: AsmWriter.cpp:2329
GlobalPrefix
@ GlobalPrefix
Definition: AsmWriter.cpp:349
llvm::APFloatBase::x87DoubleExtended
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:213
APInt.h
llvm::DILocation
Debug location.
Definition: DebugInfoMetadata.h:1595
llvm::DenseMapIterator
Definition: DenseMap.h:57
llvm::StringMap::end
iterator end()
Definition: StringMap.h:204
llvm::CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:242
llvm::CallingConv::ARM_APCS
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
Definition: CallingConv.h:104
llvm::Type
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
DenseMap.h
Module.h
llvm::APFloatBase::BFloat
static const fltSemantics & BFloat() LLVM_READNONE
Definition: APFloat.cpp:198
llvm::AttributeList
Definition: Attributes.h:430
llvm::Metadata::printAsOperand
void printAsOperand(raw_ostream &OS, const Module *M=nullptr) const
Print as operand.
Definition: AsmWriter.cpp:4865
llvm::X86AS::FS
@ FS
Definition: X86.h:200
llvm::GlobalValueSummary::GVFlags::Linkage
unsigned Linkage
The linkage type of the associated global value.
Definition: ModuleSummaryIndex.h:377
llvm::AttributeList::getFnAttrs
AttributeSet getFnAttrs() const
The function attributes are returned.
Definition: Attributes.cpp:1470
llvm::LLVMContext::getSyncScopeNames
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
Definition: LLVMContext.cpp:314
llvm::FenceInst
An instruction for ordering other memory operations.
Definition: Instructions.h:432
GlobalObject.h
llvm::MapVector
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:37
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
llvm::Comdat::Largest
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
Operator.h
llvm::VectorType::getElementType
Type * getElementType() const
Definition: DerivedTypes.h:422
llvm::CallingConv::ARM_AAPCS
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:108
llvm::FunctionSummary::TypeIdInfo::TypeTestAssumeConstVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
Definition: ModuleSummaryIndex.h:631
llvm::APFloat::getSNaN
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:939
llvm::FunctionType::getNumParams
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
llvm::ModuleSlotTracker::incorporateFunction
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:861
STLExtras.h
llvm::GlobalValueSummary::GVFlags::NotEligibleToImport
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
Definition: ModuleSummaryIndex.h:384
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2596
llvm::GlobalValue::LinkageTypes
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
llvm::ArrayType
Class to represent array types.
Definition: DerivedTypes.h:357
llvm::StringMap::find
iterator find(StringRef Key)
Definition: StringMap.h:217
llvm::MetadataAsValue
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:176
maybePrintCallAddrSpace
static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I, raw_ostream &Out)
Definition: AsmWriter.cpp:3999
llvm::dwarf::Tag
Tag
Definition: Dwarf.h:105
Format.h
llvm::FunctionSummary::VFuncId::Offset
uint64_t Offset
Definition: ModuleSummaryIndex.h:604
llvm::format_hex_no_prefix
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition: Format.h:199
llvm::Type::getNonOpaquePointerElementType
Type * getNonOpaquePointerElementType() const
Only use this method in code that is not reachable with opaque pointers, or part of deprecated method...
Definition: Type.h:401
llvm::APFloat::getSemantics
const fltSemantics & getSemantics() const
Definition: APFloat.h:1238
llvm::ModuleSlotTracker
Manage lifetime of a slot tracker for printing IR.
Definition: ModuleSlotTracker.h:44
llvm::AliasSummary::getAliasee
const GlobalValueSummary & getAliasee() const
Definition: ModuleSummaryIndex.h:553
Use.h
llvm::PossiblyExactOperator
A udiv or sdiv instruction, which can be marked as "exact", indicating that no bits are destroyed.
Definition: Operator.h:126
ModuleSummaryIndex.h
llvm::NamedMDNode::dump
void dump() const
Definition: AsmWriter.cpp:4938
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::FunctionType::isVarArg
bool isVarArg() const
Definition: DerivedTypes.h:123
llvm::APFloatBase::IEEEquad
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:207
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:55
llvm::UndefMaskElem
constexpr int UndefMaskElem
Definition: Instructions.h:1995
llvm::GlobalValueSummary::GVFlags
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
Definition: ModuleSummaryIndex.h:369
PrintThreadLocalModel
static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3531
llvm::FunctionSummary::TypeIdInfo::TypeCheckedLoadVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
Definition: ModuleSummaryIndex.h:626
llvm::AArch64CC::LT
@ LT
Definition: AArch64BaseInfo.h:266
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::Resolver
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2133
llvm::X86AS::SS
@ SS
Definition: X86.h:201
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:187
llvm::BitmaskEnumDetail::Mask
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:80
Instruction.h
llvm::CallingConv::PreserveAll
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition: CallingConv.h:66
FormattedStream.h
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::GlobalValueSummary
Function and variable summary information to aid decisions and implementation of importing.
Definition: ModuleSummaryIndex.h:363
llvm::SlotTracker::createMetadataSlot
void createMetadataSlot(const MDNode *N) override
getMetadataSlot - Get the slot number of a MDNode.
Definition: AsmWriter.cpp:1151
llvm::all_of
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1709
llvm::Type::MetadataTyID
@ MetadataTyID
Metadata.
Definition: Type.h:65
llvm::AttributeList::hasRetAttrs
bool hasRetAttrs() const
Return true if attributes exist for the return value.
Definition: Attributes.h:787
GlobalValue.h
llvm::Type::FunctionTyID
@ FunctionTyID
Functions.
Definition: Type.h:72
llvm::GlobalValue::VisibilityTypes
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:62
llvm::ArrayType::getNumElements
uint64_t getNumElements() const
Definition: DerivedTypes.h:369
llvm::ModRefInfo::Ref
@ Ref
The access may reference the value stored in memory.
Constants.h
llvm::Module::globals
iterator_range< global_iterator > globals()
Definition: Module.h:614
PrintCallingConv
static void PrintCallingConv(unsigned cc, raw_ostream &Out)
Definition: AsmWriter.cpp:290
SmallString.h
PrintDSOLocation
static void PrintDSOLocation(const GlobalValue &GV, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3516
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::APFloatBase::IEEEhalf
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:195
llvm::CallingConv::AVR_SIGNAL
@ AVR_SIGNAL
Used for AVR signal routines.
Definition: CallingConv.h:180
llvm::User
Definition: User.h:44
llvm::GlobalValue::getSanitizerMetadata
const SanitizerMetadata & getSanitizerMetadata() const
Definition: Globals.cpp:225
llvm::CallingConv::AMDGPU_HS
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:207
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::CallingConv::Swift
@ Swift
Calling convention for Swift.
Definition: CallingConv.h:69
llvm::GlobalValue::getThreadLocalMode
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:265
InstrTypes.h
llvm::APInt::getHiBits
APInt getHiBits(unsigned numBits) const
Compute an APInt containing numBits highbits from this APInt.
Definition: APInt.cpp:600
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::NamedMDNode::getName
StringRef getName() const
Definition: Metadata.cpp:1233
llvm::Type::print
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4650
LocalPrefix
@ LocalPrefix
Definition: AsmWriter.cpp:352
TypeFinder.h
SI
@ SI
Definition: SIInstrInfo.cpp:7882
llvm::Module::named_metadata
iterator_range< named_metadata_iterator > named_metadata()
Definition: Module.h:719
llvm::WholeProgramDevirtResolution::ByArg::Kind
Kind
Definition: ModuleSummaryIndex.h:1119
t
bitcast float %x to i32 %s=and i32 %t, 2147483647 %d=bitcast i32 %s to float ret float %d } declare float @fabsf(float %n) define float @bar(float %x) nounwind { %d=call float @fabsf(float %x) ret float %d } This IR(from PR6194):target datalayout="e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128" target triple="x86_64-apple-darwin10.0.0" %0=type { double, double } %struct.float3=type { float, float, float } define void @test(%0, %struct.float3 *nocapture %res) nounwind noinline ssp { entry:%tmp18=extractvalue %0 %0, 0 t
Definition: README-SSE.txt:788
llvm::APFloat::isNaN
bool isNaN() const
Definition: APFloat.h:1228
printWithoutType
static bool printWithoutType(const Value &V, raw_ostream &O, SlotTracker *Machine, const Module *M)
Print without a type, skipping the TypePrinting object.
Definition: AsmWriter.cpp:4736
llvm::AD_ATT
@ AD_ATT
Definition: SystemZMCAsmInfo.h:18
llvm::Comdat::Any
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
llvm::Value::uses
iterator_range< use_iterator > uses()
Definition: Value.h:376
false
Definition: StackSlotColoring.cpp:141
llvm::VectorType::getElementCount
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Definition: DerivedTypes.h:627
llvm::dwarf::Index
Index
Definition: Dwarf.h:472
llvm::GlobalObject::getComdat
const Comdat * getComdat() const
Definition: GlobalObject.h:122
llvm::MaybeAlign
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
llvm::CallingConv::PTX_Device
@ PTX_Device
Call to a PTX device function.
Definition: CallingConv.h:126
llvm::Function::arg_end
arg_iterator arg_end()
Definition: Function.h:731
llvm::ConstantArray
ConstantArray - Constant Array Declarations.
Definition: Constants.h:410
llvm::APFloat::isNegative
bool isNegative() const
Definition: APFloat.h:1230
llvm::APFloat::convertToDouble
double convertToDouble() const
Converts this APFloat to host double value.
Definition: APFloat.cpp:5143
emit
dxil metadata emit
Definition: DXILTranslateMetadata.cpp:64
llvm::Instruction
Definition: Instruction.h:42
getVisibilityName
static const char * getVisibilityName(GlobalValue::VisibilityTypes Vis)
Definition: AsmWriter.cpp:3161
llvm::AttributeList::getAttributes
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
Definition: Attributes.cpp:1587
llvm::APInt::getZExtValue
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1486
IRPrintingPasses.h
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
llvm::ConstantFP
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:257
APFloat.h
llvm::SmallVectorImpl::resize
void resize(size_type N)
Definition: SmallVector.h:642
llvm::CallingConv::SPIR_FUNC
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
Definition: CallingConv.h:135
llvm::CallingConv::CXX_FAST_TLS
@ CXX_FAST_TLS
Used for access functions.
Definition: CallingConv.h:72
getWholeProgDevirtResKindName
static const char * getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K)
Definition: AsmWriter.cpp:2940
llvm::Comdat::SameSize
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
llvm::getHotnessName
const char * getHotnessName(CalleeInfo::HotnessType HT)
Definition: ModuleSummaryIndex.h:106
llvm::FunctionType::params
ArrayRef< Type * > params() const
Definition: DerivedTypes.h:130
llvm::AArch64PACKey::IA
@ IA
Definition: AArch64BaseInfo.h:819
llvm::GlobalValue::SanitizerMetadata
Definition: GlobalValue.h:311
SmallPtrSet.h
llvm::BasicBlock::getModule
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:147
llvm::Type::PointerTyID
@ PointerTyID
Pointers.
Definition: Type.h:73
llvm::WholeProgramDevirtResolution::Kind
Kind
Definition: ModuleSummaryIndex.h:1108
llvm::APFloat::bitcastToAPInt
APInt bitcastToAPInt() const
Definition: APFloat.h:1145
llvm::CallingConv::AMDGPU_LS
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:214
llvm::pdb::PDB_ColorItem::Path
@ Path
llvm::Comdat
Definition: Comdat.h:33
llvm::MCID::Call
@ Call
Definition: MCInstrDesc.h:155
llvm::Metadata
Root of the metadata hierarchy.
Definition: Metadata.h:62
llvm::PointerType::isOpaque
bool isOpaque() const
Definition: DerivedTypes.h:673
llvm::TypeTestResolution::BitMask
uint8_t BitMask
Definition: ModuleSummaryIndex.h:1103
llvm::AddressSpace
AddressSpace
Definition: NVPTXBaseInfo.h:21
llvm::Type::BFloatTyID
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition: Type.h:57
llvm::SlotTracker::getAttributeGroupSlot
int getAttributeGroupSlot(AttributeSet AS)
Definition: AsmWriter.cpp:1174
llvm::lltok::Kind
Kind
Definition: LLToken.h:18
llvm::GlobalValueSummary::GVFlags::Visibility
unsigned Visibility
Indicates the visibility.
Definition: ModuleSummaryIndex.h:380
llvm::Value::use_empty
bool use_empty() const
Definition: Value.h:344
llvm::CallingConv::ID
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
llvm::CallingConv::HHVM_C
@ HHVM_C
HHVM calling convention for invoking C/C++ helpers.
Definition: CallingConv.h:168
Type.h
llvm::SlotTracker::getMetadataSlot
int getMetadataSlot(const MDNode *N) override
getMetadataSlot - Get the slot number of a MDNode.
Definition: AsmWriter.cpp:1154
llvm::ValueInfo
Struct that holds a reference to a particular GUID in a global value summary.
Definition: ModuleSummaryIndex.h:168
llvm::SmallString< 128 >
CFG.h
llvm::Function::getAttributes
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:314
llvm::InvokeInst
Invoke instruction.
Definition: Instructions.h:3810
llvm::ModuleSlotTracker::collectMDNodes
void collectMDNodes(MachineMDNodeListType &L, unsigned LB, unsigned UB) const
Definition: AsmWriter.cpp:4905
llvm::TypeTestResolution::AlignLog2
uint64_t AlignLog2
Definition: ModuleSummaryIndex.h:1101
llvm::AliasSummary::hasAliasee
bool hasAliasee() const
Definition: ModuleSummaryIndex.h:546
llvm::WholeProgramDevirtResolution::SingleImplName
std::string SingleImplName
Definition: ModuleSummaryIndex.h:1116
llvm::CallingConv::Intel_OCL_BI
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
Definition: CallingConv.h:144
llvm::CmpInst
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:709
llvm::S