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