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