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