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