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