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