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