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   Printer.printString("sysroot", N->getSysRoot());
1949   Out << ")";
1950 }
1951 
1952 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1953                               TypePrinting *TypePrinter, SlotTracker *Machine,
1954                               const Module *Context) {
1955   Out << "!DISubprogram(";
1956   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1957   Printer.printString("name", N->getName());
1958   Printer.printString("linkageName", N->getLinkageName());
1959   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1960   Printer.printMetadata("file", N->getRawFile());
1961   Printer.printInt("line", N->getLine());
1962   Printer.printMetadata("type", N->getRawType());
1963   Printer.printInt("scopeLine", N->getScopeLine());
1964   Printer.printMetadata("containingType", N->getRawContainingType());
1965   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1966       N->getVirtualIndex() != 0)
1967     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
1968   Printer.printInt("thisAdjustment", N->getThisAdjustment());
1969   Printer.printDIFlags("flags", N->getFlags());
1970   Printer.printDISPFlags("spFlags", N->getSPFlags());
1971   Printer.printMetadata("unit", N->getRawUnit());
1972   Printer.printMetadata("templateParams", N->getRawTemplateParams());
1973   Printer.printMetadata("declaration", N->getRawDeclaration());
1974   Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
1975   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
1976   Out << ")";
1977 }
1978 
1979 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1980                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1981                                 const Module *Context) {
1982   Out << "!DILexicalBlock(";
1983   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1984   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1985   Printer.printMetadata("file", N->getRawFile());
1986   Printer.printInt("line", N->getLine());
1987   Printer.printInt("column", N->getColumn());
1988   Out << ")";
1989 }
1990 
1991 static void writeDILexicalBlockFile(raw_ostream &Out,
1992                                     const DILexicalBlockFile *N,
1993                                     TypePrinting *TypePrinter,
1994                                     SlotTracker *Machine,
1995                                     const Module *Context) {
1996   Out << "!DILexicalBlockFile(";
1997   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1998   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1999   Printer.printMetadata("file", N->getRawFile());
2000   Printer.printInt("discriminator", N->getDiscriminator(),
2001                    /* ShouldSkipZero */ false);
2002   Out << ")";
2003 }
2004 
2005 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2006                              TypePrinting *TypePrinter, SlotTracker *Machine,
2007                              const Module *Context) {
2008   Out << "!DINamespace(";
2009   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2010   Printer.printString("name", N->getName());
2011   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2012   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2013   Out << ")";
2014 }
2015 
2016 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2017                                TypePrinting *TypePrinter, SlotTracker *Machine,
2018                                const Module *Context) {
2019   Out << "!DICommonBlock(";
2020   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2021   Printer.printMetadata("scope", N->getRawScope(), false);
2022   Printer.printMetadata("declaration", N->getRawDecl(), false);
2023   Printer.printString("name", N->getName());
2024   Printer.printMetadata("file", N->getRawFile());
2025   Printer.printInt("line", N->getLineNo());
2026   Out << ")";
2027 }
2028 
2029 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2030                          TypePrinting *TypePrinter, SlotTracker *Machine,
2031                          const Module *Context) {
2032   Out << "!DIMacro(";
2033   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2034   Printer.printMacinfoType(N);
2035   Printer.printInt("line", N->getLine());
2036   Printer.printString("name", N->getName());
2037   Printer.printString("value", N->getValue());
2038   Out << ")";
2039 }
2040 
2041 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2042                              TypePrinting *TypePrinter, SlotTracker *Machine,
2043                              const Module *Context) {
2044   Out << "!DIMacroFile(";
2045   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2046   Printer.printInt("line", N->getLine());
2047   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2048   Printer.printMetadata("nodes", N->getRawElements());
2049   Out << ")";
2050 }
2051 
2052 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2053                           TypePrinting *TypePrinter, SlotTracker *Machine,
2054                           const Module *Context) {
2055   Out << "!DIModule(";
2056   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2057   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2058   Printer.printString("name", N->getName());
2059   Printer.printString("configMacros", N->getConfigurationMacros());
2060   Printer.printString("includePath", N->getIncludePath());
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 =
2689       ModuleSummaryIndex::getRegularLTOModuleName();
2690   moduleVec.resize(TheIndex->modulePaths().size());
2691   for (auto &ModPath : TheIndex->modulePaths())
2692     moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2693         // A module id of -1 is a special entry for a regular LTO module created
2694         // during the thin link.
2695         ModPath.second.first == -1u ? RegularLTOModuleName
2696                                     : (std::string)std::string(ModPath.first()),
2697         ModPath.second.second);
2698 
2699   unsigned i = 0;
2700   for (auto &ModPair : moduleVec) {
2701     Out << "^" << i++ << " = module: (";
2702     Out << "path: \"";
2703     printEscapedString(ModPair.first, Out);
2704     Out << "\", hash: (";
2705     FieldSeparator FS;
2706     for (auto Hash : ModPair.second)
2707       Out << FS << Hash;
2708     Out << "))\n";
2709   }
2710 
2711   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2712   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2713   for (auto &GlobalList : *TheIndex) {
2714     auto GUID = GlobalList.first;
2715     for (auto &Summary : GlobalList.second.SummaryList)
2716       SummaryToGUIDMap[Summary.get()] = GUID;
2717   }
2718 
2719   // Print the global value summary entries.
2720   for (auto &GlobalList : *TheIndex) {
2721     auto GUID = GlobalList.first;
2722     auto VI = TheIndex->getValueInfo(GlobalList);
2723     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2724   }
2725 
2726   // Print the TypeIdMap entries.
2727   for (auto TidIter = TheIndex->typeIds().begin();
2728        TidIter != TheIndex->typeIds().end(); TidIter++) {
2729     Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2730         << " = typeid: (name: \"" << TidIter->second.first << "\"";
2731     printTypeIdSummary(TidIter->second.second);
2732     Out << ") ; guid = " << TidIter->first << "\n";
2733   }
2734 
2735   // Print the TypeIdCompatibleVtableMap entries.
2736   for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2737     auto GUID = GlobalValue::getGUID(TId.first);
2738     Out << "^" << Machine.getGUIDSlot(GUID)
2739         << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
2740     printTypeIdCompatibleVtableSummary(TId.second);
2741     Out << ") ; guid = " << GUID << "\n";
2742   }
2743 }
2744 
2745 static const char *
2746 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2747   switch (K) {
2748   case WholeProgramDevirtResolution::Indir:
2749     return "indir";
2750   case WholeProgramDevirtResolution::SingleImpl:
2751     return "singleImpl";
2752   case WholeProgramDevirtResolution::BranchFunnel:
2753     return "branchFunnel";
2754   }
2755   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2756 }
2757 
2758 static const char *getWholeProgDevirtResByArgKindName(
2759     WholeProgramDevirtResolution::ByArg::Kind K) {
2760   switch (K) {
2761   case WholeProgramDevirtResolution::ByArg::Indir:
2762     return "indir";
2763   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2764     return "uniformRetVal";
2765   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2766     return "uniqueRetVal";
2767   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2768     return "virtualConstProp";
2769   }
2770   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2771 }
2772 
2773 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2774   switch (K) {
2775   case TypeTestResolution::Unsat:
2776     return "unsat";
2777   case TypeTestResolution::ByteArray:
2778     return "byteArray";
2779   case TypeTestResolution::Inline:
2780     return "inline";
2781   case TypeTestResolution::Single:
2782     return "single";
2783   case TypeTestResolution::AllOnes:
2784     return "allOnes";
2785   }
2786   llvm_unreachable("invalid TypeTestResolution kind");
2787 }
2788 
2789 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2790   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2791       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2792 
2793   // The following fields are only used if the target does not support the use
2794   // of absolute symbols to store constants. Print only if non-zero.
2795   if (TTRes.AlignLog2)
2796     Out << ", alignLog2: " << TTRes.AlignLog2;
2797   if (TTRes.SizeM1)
2798     Out << ", sizeM1: " << TTRes.SizeM1;
2799   if (TTRes.BitMask)
2800     // BitMask is uint8_t which causes it to print the corresponding char.
2801     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2802   if (TTRes.InlineBits)
2803     Out << ", inlineBits: " << TTRes.InlineBits;
2804 
2805   Out << ")";
2806 }
2807 
2808 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2809   Out << ", summary: (";
2810   printTypeTestResolution(TIS.TTRes);
2811   if (!TIS.WPDRes.empty()) {
2812     Out << ", wpdResolutions: (";
2813     FieldSeparator FS;
2814     for (auto &WPDRes : TIS.WPDRes) {
2815       Out << FS;
2816       Out << "(offset: " << WPDRes.first << ", ";
2817       printWPDRes(WPDRes.second);
2818       Out << ")";
2819     }
2820     Out << ")";
2821   }
2822   Out << ")";
2823 }
2824 
2825 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
2826     const TypeIdCompatibleVtableInfo &TI) {
2827   Out << ", summary: (";
2828   FieldSeparator FS;
2829   for (auto &P : TI) {
2830     Out << FS;
2831     Out << "(offset: " << P.AddressPointOffset << ", ";
2832     Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
2833     Out << ")";
2834   }
2835   Out << ")";
2836 }
2837 
2838 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2839   Out << "args: (";
2840   FieldSeparator FS;
2841   for (auto arg : Args) {
2842     Out << FS;
2843     Out << arg;
2844   }
2845   Out << ")";
2846 }
2847 
2848 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2849   Out << "wpdRes: (kind: ";
2850   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2851 
2852   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
2853     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2854 
2855   if (!WPDRes.ResByArg.empty()) {
2856     Out << ", resByArg: (";
2857     FieldSeparator FS;
2858     for (auto &ResByArg : WPDRes.ResByArg) {
2859       Out << FS;
2860       printArgs(ResByArg.first);
2861       Out << ", byArg: (kind: ";
2862       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2863       if (ResByArg.second.TheKind ==
2864               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
2865           ResByArg.second.TheKind ==
2866               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
2867         Out << ", info: " << ResByArg.second.Info;
2868 
2869       // The following fields are only used if the target does not support the
2870       // use of absolute symbols to store constants. Print only if non-zero.
2871       if (ResByArg.second.Byte || ResByArg.second.Bit)
2872         Out << ", byte: " << ResByArg.second.Byte
2873             << ", bit: " << ResByArg.second.Bit;
2874 
2875       Out << ")";
2876     }
2877     Out << ")";
2878   }
2879   Out << ")";
2880 }
2881 
2882 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
2883   switch (SK) {
2884   case GlobalValueSummary::AliasKind:
2885     return "alias";
2886   case GlobalValueSummary::FunctionKind:
2887     return "function";
2888   case GlobalValueSummary::GlobalVarKind:
2889     return "variable";
2890   }
2891   llvm_unreachable("invalid summary kind");
2892 }
2893 
2894 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
2895   Out << ", aliasee: ";
2896   // The indexes emitted for distributed backends may not include the
2897   // aliasee summary (only if it is being imported directly). Handle
2898   // that case by just emitting "null" as the aliasee.
2899   if (AS->hasAliasee())
2900     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2901   else
2902     Out << "null";
2903 }
2904 
2905 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2906   auto VTableFuncs = GS->vTableFuncs();
2907   Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
2908       << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
2909       << "constant: " << GS->VarFlags.Constant;
2910   if (!VTableFuncs.empty())
2911     Out << ", "
2912         << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
2913   Out << ")";
2914 
2915   if (!VTableFuncs.empty()) {
2916     Out << ", vTableFuncs: (";
2917     FieldSeparator FS;
2918     for (auto &P : VTableFuncs) {
2919       Out << FS;
2920       Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
2921           << ", offset: " << P.VTableOffset;
2922       Out << ")";
2923     }
2924     Out << ")";
2925   }
2926 }
2927 
2928 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
2929   switch (LT) {
2930   case GlobalValue::ExternalLinkage:
2931     return "external";
2932   case GlobalValue::PrivateLinkage:
2933     return "private";
2934   case GlobalValue::InternalLinkage:
2935     return "internal";
2936   case GlobalValue::LinkOnceAnyLinkage:
2937     return "linkonce";
2938   case GlobalValue::LinkOnceODRLinkage:
2939     return "linkonce_odr";
2940   case GlobalValue::WeakAnyLinkage:
2941     return "weak";
2942   case GlobalValue::WeakODRLinkage:
2943     return "weak_odr";
2944   case GlobalValue::CommonLinkage:
2945     return "common";
2946   case GlobalValue::AppendingLinkage:
2947     return "appending";
2948   case GlobalValue::ExternalWeakLinkage:
2949     return "extern_weak";
2950   case GlobalValue::AvailableExternallyLinkage:
2951     return "available_externally";
2952   }
2953   llvm_unreachable("invalid linkage");
2954 }
2955 
2956 // When printing the linkage types in IR where the ExternalLinkage is
2957 // not printed, and other linkage types are expected to be printed with
2958 // a space after the name.
2959 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
2960   if (LT == GlobalValue::ExternalLinkage)
2961     return "";
2962   return getLinkageName(LT) + " ";
2963 }
2964 
2965 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2966   Out << ", insts: " << FS->instCount();
2967 
2968   FunctionSummary::FFlags FFlags = FS->fflags();
2969   if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2970       FFlags.ReturnDoesNotAlias | FFlags.NoInline | FFlags.AlwaysInline) {
2971     Out << ", funcFlags: (";
2972     Out << "readNone: " << FFlags.ReadNone;
2973     Out << ", readOnly: " << FFlags.ReadOnly;
2974     Out << ", noRecurse: " << FFlags.NoRecurse;
2975     Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2976     Out << ", noInline: " << FFlags.NoInline;
2977     Out << ", alwaysInline: " << FFlags.AlwaysInline;
2978     Out << ")";
2979   }
2980   if (!FS->calls().empty()) {
2981     Out << ", calls: (";
2982     FieldSeparator IFS;
2983     for (auto &Call : FS->calls()) {
2984       Out << IFS;
2985       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2986       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2987         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2988       else if (Call.second.RelBlockFreq)
2989         Out << ", relbf: " << Call.second.RelBlockFreq;
2990       Out << ")";
2991     }
2992     Out << ")";
2993   }
2994 
2995   if (const auto *TIdInfo = FS->getTypeIdInfo())
2996     printTypeIdInfo(*TIdInfo);
2997 }
2998 
2999 void AssemblyWriter::printTypeIdInfo(
3000     const FunctionSummary::TypeIdInfo &TIDInfo) {
3001   Out << ", typeIdInfo: (";
3002   FieldSeparator TIDFS;
3003   if (!TIDInfo.TypeTests.empty()) {
3004     Out << TIDFS;
3005     Out << "typeTests: (";
3006     FieldSeparator FS;
3007     for (auto &GUID : TIDInfo.TypeTests) {
3008       auto TidIter = TheIndex->typeIds().equal_range(GUID);
3009       if (TidIter.first == TidIter.second) {
3010         Out << FS;
3011         Out << GUID;
3012         continue;
3013       }
3014       // Print all type id that correspond to this GUID.
3015       for (auto It = TidIter.first; It != TidIter.second; ++It) {
3016         Out << FS;
3017         auto Slot = Machine.getTypeIdSlot(It->second.first);
3018         assert(Slot != -1);
3019         Out << "^" << Slot;
3020       }
3021     }
3022     Out << ")";
3023   }
3024   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3025     Out << TIDFS;
3026     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3027   }
3028   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3029     Out << TIDFS;
3030     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3031   }
3032   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3033     Out << TIDFS;
3034     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3035                      "typeTestAssumeConstVCalls");
3036   }
3037   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3038     Out << TIDFS;
3039     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3040                      "typeCheckedLoadConstVCalls");
3041   }
3042   Out << ")";
3043 }
3044 
3045 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3046   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3047   if (TidIter.first == TidIter.second) {
3048     Out << "vFuncId: (";
3049     Out << "guid: " << VFId.GUID;
3050     Out << ", offset: " << VFId.Offset;
3051     Out << ")";
3052     return;
3053   }
3054   // Print all type id that correspond to this GUID.
3055   FieldSeparator FS;
3056   for (auto It = TidIter.first; It != TidIter.second; ++It) {
3057     Out << FS;
3058     Out << "vFuncId: (";
3059     auto Slot = Machine.getTypeIdSlot(It->second.first);
3060     assert(Slot != -1);
3061     Out << "^" << Slot;
3062     Out << ", offset: " << VFId.Offset;
3063     Out << ")";
3064   }
3065 }
3066 
3067 void AssemblyWriter::printNonConstVCalls(
3068     const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
3069   Out << Tag << ": (";
3070   FieldSeparator FS;
3071   for (auto &VFuncId : VCallList) {
3072     Out << FS;
3073     printVFuncId(VFuncId);
3074   }
3075   Out << ")";
3076 }
3077 
3078 void AssemblyWriter::printConstVCalls(
3079     const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
3080   Out << Tag << ": (";
3081   FieldSeparator FS;
3082   for (auto &ConstVCall : VCallList) {
3083     Out << FS;
3084     Out << "(";
3085     printVFuncId(ConstVCall.VFunc);
3086     if (!ConstVCall.Args.empty()) {
3087       Out << ", ";
3088       printArgs(ConstVCall.Args);
3089     }
3090     Out << ")";
3091   }
3092   Out << ")";
3093 }
3094 
3095 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3096   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3097   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3098   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3099   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3100       << ", flags: (";
3101   Out << "linkage: " << getLinkageName(LT);
3102   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3103   Out << ", live: " << GVFlags.Live;
3104   Out << ", dsoLocal: " << GVFlags.DSOLocal;
3105   Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3106   Out << ")";
3107 
3108   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3109     printAliasSummary(cast<AliasSummary>(&Summary));
3110   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3111     printFunctionSummary(cast<FunctionSummary>(&Summary));
3112   else
3113     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3114 
3115   auto RefList = Summary.refs();
3116   if (!RefList.empty()) {
3117     Out << ", refs: (";
3118     FieldSeparator FS;
3119     for (auto &Ref : RefList) {
3120       Out << FS;
3121       if (Ref.isReadOnly())
3122         Out << "readonly ";
3123       else if (Ref.isWriteOnly())
3124         Out << "writeonly ";
3125       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3126     }
3127     Out << ")";
3128   }
3129 
3130   Out << ")";
3131 }
3132 
3133 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3134   Out << "^" << Slot << " = gv: (";
3135   if (!VI.name().empty())
3136     Out << "name: \"" << VI.name() << "\"";
3137   else
3138     Out << "guid: " << VI.getGUID();
3139   if (!VI.getSummaryList().empty()) {
3140     Out << ", summaries: (";
3141     FieldSeparator FS;
3142     for (auto &Summary : VI.getSummaryList()) {
3143       Out << FS;
3144       printSummary(*Summary);
3145     }
3146     Out << ")";
3147   }
3148   Out << ")";
3149   if (!VI.name().empty())
3150     Out << " ; guid = " << VI.getGUID();
3151   Out << "\n";
3152 }
3153 
3154 static void printMetadataIdentifier(StringRef Name,
3155                                     formatted_raw_ostream &Out) {
3156   if (Name.empty()) {
3157     Out << "<empty name> ";
3158   } else {
3159     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3160         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3161       Out << Name[0];
3162     else
3163       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3164     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3165       unsigned char C = Name[i];
3166       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3167           C == '.' || C == '_')
3168         Out << C;
3169       else
3170         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3171     }
3172   }
3173 }
3174 
3175 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3176   Out << '!';
3177   printMetadataIdentifier(NMD->getName(), Out);
3178   Out << " = !{";
3179   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3180     if (i)
3181       Out << ", ";
3182 
3183     // Write DIExpressions inline.
3184     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3185     MDNode *Op = NMD->getOperand(i);
3186     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3187       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3188       continue;
3189     }
3190 
3191     int Slot = Machine.getMetadataSlot(Op);
3192     if (Slot == -1)
3193       Out << "<badref>";
3194     else
3195       Out << '!' << Slot;
3196   }
3197   Out << "}\n";
3198 }
3199 
3200 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3201                             formatted_raw_ostream &Out) {
3202   switch (Vis) {
3203   case GlobalValue::DefaultVisibility: break;
3204   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
3205   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3206   }
3207 }
3208 
3209 static void PrintDSOLocation(const GlobalValue &GV,
3210                              formatted_raw_ostream &Out) {
3211   // GVs with local linkage or non default visibility are implicitly dso_local,
3212   // so we don't print it.
3213   bool Implicit = GV.hasLocalLinkage() ||
3214                   (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
3215   if (GV.isDSOLocal() && !Implicit)
3216     Out << "dso_local ";
3217 }
3218 
3219 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3220                                  formatted_raw_ostream &Out) {
3221   switch (SCT) {
3222   case GlobalValue::DefaultStorageClass: break;
3223   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3224   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3225   }
3226 }
3227 
3228 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3229                                   formatted_raw_ostream &Out) {
3230   switch (TLM) {
3231     case GlobalVariable::NotThreadLocal:
3232       break;
3233     case GlobalVariable::GeneralDynamicTLSModel:
3234       Out << "thread_local ";
3235       break;
3236     case GlobalVariable::LocalDynamicTLSModel:
3237       Out << "thread_local(localdynamic) ";
3238       break;
3239     case GlobalVariable::InitialExecTLSModel:
3240       Out << "thread_local(initialexec) ";
3241       break;
3242     case GlobalVariable::LocalExecTLSModel:
3243       Out << "thread_local(localexec) ";
3244       break;
3245   }
3246 }
3247 
3248 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3249   switch (UA) {
3250   case GlobalVariable::UnnamedAddr::None:
3251     return "";
3252   case GlobalVariable::UnnamedAddr::Local:
3253     return "local_unnamed_addr";
3254   case GlobalVariable::UnnamedAddr::Global:
3255     return "unnamed_addr";
3256   }
3257   llvm_unreachable("Unknown UnnamedAddr");
3258 }
3259 
3260 static void maybePrintComdat(formatted_raw_ostream &Out,
3261                              const GlobalObject &GO) {
3262   const Comdat *C = GO.getComdat();
3263   if (!C)
3264     return;
3265 
3266   if (isa<GlobalVariable>(GO))
3267     Out << ',';
3268   Out << " comdat";
3269 
3270   if (GO.getName() == C->getName())
3271     return;
3272 
3273   Out << '(';
3274   PrintLLVMName(Out, C->getName(), ComdatPrefix);
3275   Out << ')';
3276 }
3277 
3278 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3279   if (GV->isMaterializable())
3280     Out << "; Materializable\n";
3281 
3282   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3283   Out << " = ";
3284 
3285   if (!GV->hasInitializer() && GV->hasExternalLinkage())
3286     Out << "external ";
3287 
3288   Out << getLinkageNameWithSpace(GV->getLinkage());
3289   PrintDSOLocation(*GV, Out);
3290   PrintVisibility(GV->getVisibility(), Out);
3291   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3292   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3293   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3294   if (!UA.empty())
3295       Out << UA << ' ';
3296 
3297   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3298     Out << "addrspace(" << AddressSpace << ") ";
3299   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3300   Out << (GV->isConstant() ? "constant " : "global ");
3301   TypePrinter.print(GV->getValueType(), Out);
3302 
3303   if (GV->hasInitializer()) {
3304     Out << ' ';
3305     writeOperand(GV->getInitializer(), false);
3306   }
3307 
3308   if (GV->hasSection()) {
3309     Out << ", section \"";
3310     printEscapedString(GV->getSection(), Out);
3311     Out << '"';
3312   }
3313   if (GV->hasPartition()) {
3314     Out << ", partition \"";
3315     printEscapedString(GV->getPartition(), Out);
3316     Out << '"';
3317   }
3318 
3319   maybePrintComdat(Out, *GV);
3320   if (GV->getAlignment())
3321     Out << ", align " << GV->getAlignment();
3322 
3323   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3324   GV->getAllMetadata(MDs);
3325   printMetadataAttachments(MDs, ", ");
3326 
3327   auto Attrs = GV->getAttributes();
3328   if (Attrs.hasAttributes())
3329     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3330 
3331   printInfoComment(*GV);
3332 }
3333 
3334 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3335   if (GIS->isMaterializable())
3336     Out << "; Materializable\n";
3337 
3338   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3339   Out << " = ";
3340 
3341   Out << getLinkageNameWithSpace(GIS->getLinkage());
3342   PrintDSOLocation(*GIS, Out);
3343   PrintVisibility(GIS->getVisibility(), Out);
3344   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3345   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
3346   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3347   if (!UA.empty())
3348       Out << UA << ' ';
3349 
3350   if (isa<GlobalAlias>(GIS))
3351     Out << "alias ";
3352   else if (isa<GlobalIFunc>(GIS))
3353     Out << "ifunc ";
3354   else
3355     llvm_unreachable("Not an alias or ifunc!");
3356 
3357   TypePrinter.print(GIS->getValueType(), Out);
3358 
3359   Out << ", ";
3360 
3361   const Constant *IS = GIS->getIndirectSymbol();
3362 
3363   if (!IS) {
3364     TypePrinter.print(GIS->getType(), Out);
3365     Out << " <<NULL ALIASEE>>";
3366   } else {
3367     writeOperand(IS, !isa<ConstantExpr>(IS));
3368   }
3369 
3370   if (GIS->hasPartition()) {
3371     Out << ", partition \"";
3372     printEscapedString(GIS->getPartition(), Out);
3373     Out << '"';
3374   }
3375 
3376   printInfoComment(*GIS);
3377   Out << '\n';
3378 }
3379 
3380 void AssemblyWriter::printComdat(const Comdat *C) {
3381   C->print(Out);
3382 }
3383 
3384 void AssemblyWriter::printTypeIdentities() {
3385   if (TypePrinter.empty())
3386     return;
3387 
3388   Out << '\n';
3389 
3390   // Emit all numbered types.
3391   auto &NumberedTypes = TypePrinter.getNumberedTypes();
3392   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3393     Out << '%' << I << " = type ";
3394 
3395     // Make sure we print out at least one level of the type structure, so
3396     // that we do not get %2 = type %2
3397     TypePrinter.printStructBody(NumberedTypes[I], Out);
3398     Out << '\n';
3399   }
3400 
3401   auto &NamedTypes = TypePrinter.getNamedTypes();
3402   for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3403     PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3404     Out << " = type ";
3405 
3406     // Make sure we print out at least one level of the type structure, so
3407     // that we do not get %FILE = type %FILE
3408     TypePrinter.printStructBody(NamedTypes[I], Out);
3409     Out << '\n';
3410   }
3411 }
3412 
3413 /// printFunction - Print all aspects of a function.
3414 void AssemblyWriter::printFunction(const Function *F) {
3415   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3416 
3417   if (F->isMaterializable())
3418     Out << "; Materializable\n";
3419 
3420   const AttributeList &Attrs = F->getAttributes();
3421   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
3422     AttributeSet AS = Attrs.getFnAttributes();
3423     std::string AttrStr;
3424 
3425     for (const Attribute &Attr : AS) {
3426       if (!Attr.isStringAttribute()) {
3427         if (!AttrStr.empty()) AttrStr += ' ';
3428         AttrStr += Attr.getAsString();
3429       }
3430     }
3431 
3432     if (!AttrStr.empty())
3433       Out << "; Function Attrs: " << AttrStr << '\n';
3434   }
3435 
3436   Machine.incorporateFunction(F);
3437 
3438   if (F->isDeclaration()) {
3439     Out << "declare";
3440     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3441     F->getAllMetadata(MDs);
3442     printMetadataAttachments(MDs, " ");
3443     Out << ' ';
3444   } else
3445     Out << "define ";
3446 
3447   Out << getLinkageNameWithSpace(F->getLinkage());
3448   PrintDSOLocation(*F, Out);
3449   PrintVisibility(F->getVisibility(), Out);
3450   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3451 
3452   // Print the calling convention.
3453   if (F->getCallingConv() != CallingConv::C) {
3454     PrintCallingConv(F->getCallingConv(), Out);
3455     Out << " ";
3456   }
3457 
3458   FunctionType *FT = F->getFunctionType();
3459   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3460     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3461   TypePrinter.print(F->getReturnType(), Out);
3462   Out << ' ';
3463   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3464   Out << '(';
3465 
3466   // Loop over the arguments, printing them...
3467   if (F->isDeclaration() && !IsForDebug) {
3468     // We're only interested in the type here - don't print argument names.
3469     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3470       // Insert commas as we go... the first arg doesn't get a comma
3471       if (I)
3472         Out << ", ";
3473       // Output type...
3474       TypePrinter.print(FT->getParamType(I), Out);
3475 
3476       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3477       if (ArgAttrs.hasAttributes()) {
3478         Out << ' ';
3479         writeAttributeSet(ArgAttrs);
3480       }
3481     }
3482   } else {
3483     // The arguments are meaningful here, print them in detail.
3484     for (const Argument &Arg : F->args()) {
3485       // Insert commas as we go... the first arg doesn't get a comma
3486       if (Arg.getArgNo() != 0)
3487         Out << ", ";
3488       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3489     }
3490   }
3491 
3492   // Finish printing arguments...
3493   if (FT->isVarArg()) {
3494     if (FT->getNumParams()) Out << ", ";
3495     Out << "...";  // Output varargs portion of signature!
3496   }
3497   Out << ')';
3498   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3499   if (!UA.empty())
3500     Out << ' ' << UA;
3501   // We print the function address space if it is non-zero or if we are writing
3502   // a module with a non-zero program address space or if there is no valid
3503   // Module* so that the file can be parsed without the datalayout string.
3504   const Module *Mod = F->getParent();
3505   if (F->getAddressSpace() != 0 || !Mod ||
3506       Mod->getDataLayout().getProgramAddressSpace() != 0)
3507     Out << " addrspace(" << F->getAddressSpace() << ")";
3508   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
3509     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3510   if (F->hasSection()) {
3511     Out << " section \"";
3512     printEscapedString(F->getSection(), Out);
3513     Out << '"';
3514   }
3515   if (F->hasPartition()) {
3516     Out << " partition \"";
3517     printEscapedString(F->getPartition(), Out);
3518     Out << '"';
3519   }
3520   maybePrintComdat(Out, *F);
3521   if (F->getAlignment())
3522     Out << " align " << F->getAlignment();
3523   if (F->hasGC())
3524     Out << " gc \"" << F->getGC() << '"';
3525   if (F->hasPrefixData()) {
3526     Out << " prefix ";
3527     writeOperand(F->getPrefixData(), true);
3528   }
3529   if (F->hasPrologueData()) {
3530     Out << " prologue ";
3531     writeOperand(F->getPrologueData(), true);
3532   }
3533   if (F->hasPersonalityFn()) {
3534     Out << " personality ";
3535     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3536   }
3537 
3538   if (F->isDeclaration()) {
3539     Out << '\n';
3540   } else {
3541     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3542     F->getAllMetadata(MDs);
3543     printMetadataAttachments(MDs, " ");
3544 
3545     Out << " {";
3546     // Output all of the function's basic blocks.
3547     for (const BasicBlock &BB : *F)
3548       printBasicBlock(&BB);
3549 
3550     // Output the function's use-lists.
3551     printUseLists(F);
3552 
3553     Out << "}\n";
3554   }
3555 
3556   Machine.purgeFunction();
3557 }
3558 
3559 /// printArgument - This member is called for every argument that is passed into
3560 /// the function.  Simply print it out
3561 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3562   // Output type...
3563   TypePrinter.print(Arg->getType(), Out);
3564 
3565   // Output parameter attributes list
3566   if (Attrs.hasAttributes()) {
3567     Out << ' ';
3568     writeAttributeSet(Attrs);
3569   }
3570 
3571   // Output name, if available...
3572   if (Arg->hasName()) {
3573     Out << ' ';
3574     PrintLLVMName(Out, Arg);
3575   } else {
3576     int Slot = Machine.getLocalSlot(Arg);
3577     assert(Slot != -1 && "expect argument in function here");
3578     Out << " %" << Slot;
3579   }
3580 }
3581 
3582 /// printBasicBlock - This member is called for each basic block in a method.
3583 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3584   assert(BB && BB->getParent() && "block without parent!");
3585   bool IsEntryBlock = BB == &BB->getParent()->getEntryBlock();
3586   if (BB->hasName()) {              // Print out the label if it exists...
3587     Out << "\n";
3588     PrintLLVMName(Out, BB->getName(), LabelPrefix);
3589     Out << ':';
3590   } else if (!IsEntryBlock) {
3591     Out << "\n";
3592     int Slot = Machine.getLocalSlot(BB);
3593     if (Slot != -1)
3594       Out << Slot << ":";
3595     else
3596       Out << "<badref>:";
3597   }
3598 
3599   if (!IsEntryBlock) {
3600     // Output predecessors for the block.
3601     Out.PadToColumn(50);
3602     Out << ";";
3603     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3604 
3605     if (PI == PE) {
3606       Out << " No predecessors!";
3607     } else {
3608       Out << " preds = ";
3609       writeOperand(*PI, false);
3610       for (++PI; PI != PE; ++PI) {
3611         Out << ", ";
3612         writeOperand(*PI, false);
3613       }
3614     }
3615   }
3616 
3617   Out << "\n";
3618 
3619   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3620 
3621   // Output all of the instructions in the basic block...
3622   for (const Instruction &I : *BB) {
3623     printInstructionLine(I);
3624   }
3625 
3626   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3627 }
3628 
3629 /// printInstructionLine - Print an instruction and a newline character.
3630 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3631   printInstruction(I);
3632   Out << '\n';
3633 }
3634 
3635 /// printGCRelocateComment - print comment after call to the gc.relocate
3636 /// intrinsic indicating base and derived pointer names.
3637 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3638   Out << " ; (";
3639   writeOperand(Relocate.getBasePtr(), false);
3640   Out << ", ";
3641   writeOperand(Relocate.getDerivedPtr(), false);
3642   Out << ")";
3643 }
3644 
3645 /// printInfoComment - Print a little comment after the instruction indicating
3646 /// which slot it occupies.
3647 void AssemblyWriter::printInfoComment(const Value &V) {
3648   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3649     printGCRelocateComment(*Relocate);
3650 
3651   if (AnnotationWriter)
3652     AnnotationWriter->printInfoComment(V, Out);
3653 }
3654 
3655 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3656                                     raw_ostream &Out) {
3657   // We print the address space of the call if it is non-zero.
3658   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3659   bool PrintAddrSpace = CallAddrSpace != 0;
3660   if (!PrintAddrSpace) {
3661     const Module *Mod = getModuleFromVal(I);
3662     // We also print it if it is zero but not equal to the program address space
3663     // or if we can't find a valid Module* to make it possible to parse
3664     // the resulting file even without a datalayout string.
3665     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3666       PrintAddrSpace = true;
3667   }
3668   if (PrintAddrSpace)
3669     Out << " addrspace(" << CallAddrSpace << ")";
3670 }
3671 
3672 // This member is called for each Instruction in a function..
3673 void AssemblyWriter::printInstruction(const Instruction &I) {
3674   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3675 
3676   // Print out indentation for an instruction.
3677   Out << "  ";
3678 
3679   // Print out name if it exists...
3680   if (I.hasName()) {
3681     PrintLLVMName(Out, &I);
3682     Out << " = ";
3683   } else if (!I.getType()->isVoidTy()) {
3684     // Print out the def slot taken.
3685     int SlotNum = Machine.getLocalSlot(&I);
3686     if (SlotNum == -1)
3687       Out << "<badref> = ";
3688     else
3689       Out << '%' << SlotNum << " = ";
3690   }
3691 
3692   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3693     if (CI->isMustTailCall())
3694       Out << "musttail ";
3695     else if (CI->isTailCall())
3696       Out << "tail ";
3697     else if (CI->isNoTailCall())
3698       Out << "notail ";
3699   }
3700 
3701   // Print out the opcode...
3702   Out << I.getOpcodeName();
3703 
3704   // If this is an atomic load or store, print out the atomic marker.
3705   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
3706       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3707     Out << " atomic";
3708 
3709   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3710     Out << " weak";
3711 
3712   // If this is a volatile operation, print out the volatile marker.
3713   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
3714       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3715       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3716       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3717     Out << " volatile";
3718 
3719   // Print out optimization information.
3720   WriteOptimizationInfo(Out, &I);
3721 
3722   // Print out the compare instruction predicates
3723   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3724     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3725 
3726   // Print out the atomicrmw operation
3727   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3728     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3729 
3730   // Print out the type of the operands...
3731   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3732 
3733   // Special case conditional branches to swizzle the condition out to the front
3734   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3735     const BranchInst &BI(cast<BranchInst>(I));
3736     Out << ' ';
3737     writeOperand(BI.getCondition(), true);
3738     Out << ", ";
3739     writeOperand(BI.getSuccessor(0), true);
3740     Out << ", ";
3741     writeOperand(BI.getSuccessor(1), true);
3742 
3743   } else if (isa<SwitchInst>(I)) {
3744     const SwitchInst& SI(cast<SwitchInst>(I));
3745     // Special case switch instruction to get formatting nice and correct.
3746     Out << ' ';
3747     writeOperand(SI.getCondition(), true);
3748     Out << ", ";
3749     writeOperand(SI.getDefaultDest(), true);
3750     Out << " [";
3751     for (auto Case : SI.cases()) {
3752       Out << "\n    ";
3753       writeOperand(Case.getCaseValue(), true);
3754       Out << ", ";
3755       writeOperand(Case.getCaseSuccessor(), true);
3756     }
3757     Out << "\n  ]";
3758   } else if (isa<IndirectBrInst>(I)) {
3759     // Special case indirectbr instruction to get formatting nice and correct.
3760     Out << ' ';
3761     writeOperand(Operand, true);
3762     Out << ", [";
3763 
3764     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3765       if (i != 1)
3766         Out << ", ";
3767       writeOperand(I.getOperand(i), true);
3768     }
3769     Out << ']';
3770   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3771     Out << ' ';
3772     TypePrinter.print(I.getType(), Out);
3773     Out << ' ';
3774 
3775     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3776       if (op) Out << ", ";
3777       Out << "[ ";
3778       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3779       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3780     }
3781   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3782     Out << ' ';
3783     writeOperand(I.getOperand(0), true);
3784     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3785       Out << ", " << *i;
3786   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3787     Out << ' ';
3788     writeOperand(I.getOperand(0), true); Out << ", ";
3789     writeOperand(I.getOperand(1), true);
3790     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3791       Out << ", " << *i;
3792   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3793     Out << ' ';
3794     TypePrinter.print(I.getType(), Out);
3795     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3796       Out << '\n';
3797 
3798     if (LPI->isCleanup())
3799       Out << "          cleanup";
3800 
3801     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3802       if (i != 0 || LPI->isCleanup()) Out << "\n";
3803       if (LPI->isCatch(i))
3804         Out << "          catch ";
3805       else
3806         Out << "          filter ";
3807 
3808       writeOperand(LPI->getClause(i), true);
3809     }
3810   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3811     Out << " within ";
3812     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3813     Out << " [";
3814     unsigned Op = 0;
3815     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3816       if (Op > 0)
3817         Out << ", ";
3818       writeOperand(PadBB, /*PrintType=*/true);
3819       ++Op;
3820     }
3821     Out << "] unwind ";
3822     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3823       writeOperand(UnwindDest, /*PrintType=*/true);
3824     else
3825       Out << "to caller";
3826   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3827     Out << " within ";
3828     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3829     Out << " [";
3830     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3831          ++Op) {
3832       if (Op > 0)
3833         Out << ", ";
3834       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3835     }
3836     Out << ']';
3837   } else if (isa<ReturnInst>(I) && !Operand) {
3838     Out << " void";
3839   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3840     Out << " from ";
3841     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3842 
3843     Out << " to ";
3844     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3845   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3846     Out << " from ";
3847     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3848 
3849     Out << " unwind ";
3850     if (CRI->hasUnwindDest())
3851       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3852     else
3853       Out << "to caller";
3854   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3855     // Print the calling convention being used.
3856     if (CI->getCallingConv() != CallingConv::C) {
3857       Out << " ";
3858       PrintCallingConv(CI->getCallingConv(), Out);
3859     }
3860 
3861     Operand = CI->getCalledValue();
3862     FunctionType *FTy = CI->getFunctionType();
3863     Type *RetTy = FTy->getReturnType();
3864     const AttributeList &PAL = CI->getAttributes();
3865 
3866     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3867       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3868 
3869     // Only print addrspace(N) if necessary:
3870     maybePrintCallAddrSpace(Operand, &I, Out);
3871 
3872     // If possible, print out the short form of the call instruction.  We can
3873     // only do this if the first argument is a pointer to a nonvararg function,
3874     // and if the return type is not a pointer to a function.
3875     //
3876     Out << ' ';
3877     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3878     Out << ' ';
3879     writeOperand(Operand, false);
3880     Out << '(';
3881     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3882       if (op > 0)
3883         Out << ", ";
3884       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3885     }
3886 
3887     // Emit an ellipsis if this is a musttail call in a vararg function.  This
3888     // is only to aid readability, musttail calls forward varargs by default.
3889     if (CI->isMustTailCall() && CI->getParent() &&
3890         CI->getParent()->getParent() &&
3891         CI->getParent()->getParent()->isVarArg())
3892       Out << ", ...";
3893 
3894     Out << ')';
3895     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3896       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3897 
3898     writeOperandBundles(CI);
3899   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3900     Operand = II->getCalledValue();
3901     FunctionType *FTy = II->getFunctionType();
3902     Type *RetTy = FTy->getReturnType();
3903     const AttributeList &PAL = II->getAttributes();
3904 
3905     // Print the calling convention being used.
3906     if (II->getCallingConv() != CallingConv::C) {
3907       Out << " ";
3908       PrintCallingConv(II->getCallingConv(), Out);
3909     }
3910 
3911     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3912       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3913 
3914     // Only print addrspace(N) if necessary:
3915     maybePrintCallAddrSpace(Operand, &I, Out);
3916 
3917     // If possible, print out the short form of the invoke instruction. We can
3918     // only do this if the first argument is a pointer to a nonvararg function,
3919     // and if the return type is not a pointer to a function.
3920     //
3921     Out << ' ';
3922     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3923     Out << ' ';
3924     writeOperand(Operand, false);
3925     Out << '(';
3926     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3927       if (op)
3928         Out << ", ";
3929       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3930     }
3931 
3932     Out << ')';
3933     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3934       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3935 
3936     writeOperandBundles(II);
3937 
3938     Out << "\n          to ";
3939     writeOperand(II->getNormalDest(), true);
3940     Out << " unwind ";
3941     writeOperand(II->getUnwindDest(), true);
3942   } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
3943     Operand = CBI->getCalledValue();
3944     FunctionType *FTy = CBI->getFunctionType();
3945     Type *RetTy = FTy->getReturnType();
3946     const AttributeList &PAL = CBI->getAttributes();
3947 
3948     // Print the calling convention being used.
3949     if (CBI->getCallingConv() != CallingConv::C) {
3950       Out << " ";
3951       PrintCallingConv(CBI->getCallingConv(), Out);
3952     }
3953 
3954     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3955       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3956 
3957     // If possible, print out the short form of the callbr instruction. We can
3958     // only do this if the first argument is a pointer to a nonvararg function,
3959     // and if the return type is not a pointer to a function.
3960     //
3961     Out << ' ';
3962     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3963     Out << ' ';
3964     writeOperand(Operand, false);
3965     Out << '(';
3966     for (unsigned op = 0, Eop = CBI->getNumArgOperands(); op < Eop; ++op) {
3967       if (op)
3968         Out << ", ";
3969       writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttributes(op));
3970     }
3971 
3972     Out << ')';
3973     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3974       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3975 
3976     writeOperandBundles(CBI);
3977 
3978     Out << "\n          to ";
3979     writeOperand(CBI->getDefaultDest(), true);
3980     Out << " [";
3981     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
3982       if (i != 0)
3983         Out << ", ";
3984       writeOperand(CBI->getIndirectDest(i), true);
3985     }
3986     Out << ']';
3987   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3988     Out << ' ';
3989     if (AI->isUsedWithInAlloca())
3990       Out << "inalloca ";
3991     if (AI->isSwiftError())
3992       Out << "swifterror ";
3993     TypePrinter.print(AI->getAllocatedType(), Out);
3994 
3995     // Explicitly write the array size if the code is broken, if it's an array
3996     // allocation, or if the type is not canonical for scalar allocations.  The
3997     // latter case prevents the type from mutating when round-tripping through
3998     // assembly.
3999     if (!AI->getArraySize() || AI->isArrayAllocation() ||
4000         !AI->getArraySize()->getType()->isIntegerTy(32)) {
4001       Out << ", ";
4002       writeOperand(AI->getArraySize(), true);
4003     }
4004     if (AI->getAlignment()) {
4005       Out << ", align " << AI->getAlignment();
4006     }
4007 
4008     unsigned AddrSpace = AI->getType()->getAddressSpace();
4009     if (AddrSpace != 0) {
4010       Out << ", addrspace(" << AddrSpace << ')';
4011     }
4012   } else if (isa<CastInst>(I)) {
4013     if (Operand) {
4014       Out << ' ';
4015       writeOperand(Operand, true);   // Work with broken code
4016     }
4017     Out << " to ";
4018     TypePrinter.print(I.getType(), Out);
4019   } else if (isa<VAArgInst>(I)) {
4020     if (Operand) {
4021       Out << ' ';
4022       writeOperand(Operand, true);   // Work with broken code
4023     }
4024     Out << ", ";
4025     TypePrinter.print(I.getType(), Out);
4026   } else if (Operand) {   // Print the normal way.
4027     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4028       Out << ' ';
4029       TypePrinter.print(GEP->getSourceElementType(), Out);
4030       Out << ',';
4031     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4032       Out << ' ';
4033       TypePrinter.print(LI->getType(), Out);
4034       Out << ',';
4035     }
4036 
4037     // PrintAllTypes - Instructions who have operands of all the same type
4038     // omit the type from all but the first operand.  If the instruction has
4039     // different type operands (for example br), then they are all printed.
4040     bool PrintAllTypes = false;
4041     Type *TheType = Operand->getType();
4042 
4043     // Select, Store and ShuffleVector always print all types.
4044     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
4045         || isa<ReturnInst>(I)) {
4046       PrintAllTypes = true;
4047     } else {
4048       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4049         Operand = I.getOperand(i);
4050         // note that Operand shouldn't be null, but the test helps make dump()
4051         // more tolerant of malformed IR
4052         if (Operand && Operand->getType() != TheType) {
4053           PrintAllTypes = true;    // We have differing types!  Print them all!
4054           break;
4055         }
4056       }
4057     }
4058 
4059     if (!PrintAllTypes) {
4060       Out << ' ';
4061       TypePrinter.print(TheType, Out);
4062     }
4063 
4064     Out << ' ';
4065     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4066       if (i) Out << ", ";
4067       writeOperand(I.getOperand(i), PrintAllTypes);
4068     }
4069   }
4070 
4071   // Print atomic ordering/alignment for memory operations
4072   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4073     if (LI->isAtomic())
4074       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4075     if (LI->getAlignment())
4076       Out << ", align " << LI->getAlignment();
4077   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4078     if (SI->isAtomic())
4079       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4080     if (SI->getAlignment())
4081       Out << ", align " << SI->getAlignment();
4082   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4083     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4084                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
4085   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4086     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4087                 RMWI->getSyncScopeID());
4088   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4089     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4090   }
4091 
4092   // Print Metadata info.
4093   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4094   I.getAllMetadata(InstMD);
4095   printMetadataAttachments(InstMD, ", ");
4096 
4097   // Print a nice comment.
4098   printInfoComment(I);
4099 }
4100 
4101 void AssemblyWriter::printMetadataAttachments(
4102     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4103     StringRef Separator) {
4104   if (MDs.empty())
4105     return;
4106 
4107   if (MDNames.empty())
4108     MDs[0].second->getContext().getMDKindNames(MDNames);
4109 
4110   for (const auto &I : MDs) {
4111     unsigned Kind = I.first;
4112     Out << Separator;
4113     if (Kind < MDNames.size()) {
4114       Out << "!";
4115       printMetadataIdentifier(MDNames[Kind], Out);
4116     } else
4117       Out << "!<unknown kind #" << Kind << ">";
4118     Out << ' ';
4119     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
4120   }
4121 }
4122 
4123 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4124   Out << '!' << Slot << " = ";
4125   printMDNodeBody(Node);
4126   Out << "\n";
4127 }
4128 
4129 void AssemblyWriter::writeAllMDNodes() {
4130   SmallVector<const MDNode *, 16> Nodes;
4131   Nodes.resize(Machine.mdn_size());
4132   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
4133        I != E; ++I)
4134     Nodes[I->second] = cast<MDNode>(I->first);
4135 
4136   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4137     writeMDNode(i, Nodes[i]);
4138   }
4139 }
4140 
4141 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4142   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
4143 }
4144 
4145 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4146   if (!Attr.isTypeAttribute()) {
4147     Out << Attr.getAsString(InAttrGroup);
4148     return;
4149   }
4150 
4151   assert(Attr.hasAttribute(Attribute::ByVal) && "unexpected type attr");
4152 
4153   Out << "byval";
4154   if (Type *Ty = Attr.getValueAsType()) {
4155     Out << '(';
4156     TypePrinter.print(Ty, Out);
4157     Out << ')';
4158   }
4159 }
4160 
4161 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4162                                        bool InAttrGroup) {
4163   bool FirstAttr = true;
4164   for (const auto &Attr : AttrSet) {
4165     if (!FirstAttr)
4166       Out << ' ';
4167     writeAttribute(Attr, InAttrGroup);
4168     FirstAttr = false;
4169   }
4170 }
4171 
4172 void AssemblyWriter::writeAllAttributeGroups() {
4173   std::vector<std::pair<AttributeSet, unsigned>> asVec;
4174   asVec.resize(Machine.as_size());
4175 
4176   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
4177        I != E; ++I)
4178     asVec[I->second] = *I;
4179 
4180   for (const auto &I : asVec)
4181     Out << "attributes #" << I.second << " = { "
4182         << I.first.getAsString(true) << " }\n";
4183 }
4184 
4185 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4186   bool IsInFunction = Machine.getFunction();
4187   if (IsInFunction)
4188     Out << "  ";
4189 
4190   Out << "uselistorder";
4191   if (const BasicBlock *BB =
4192           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4193     Out << "_bb ";
4194     writeOperand(BB->getParent(), false);
4195     Out << ", ";
4196     writeOperand(BB, false);
4197   } else {
4198     Out << " ";
4199     writeOperand(Order.V, true);
4200   }
4201   Out << ", { ";
4202 
4203   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4204   Out << Order.Shuffle[0];
4205   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4206     Out << ", " << Order.Shuffle[I];
4207   Out << " }\n";
4208 }
4209 
4210 void AssemblyWriter::printUseLists(const Function *F) {
4211   auto hasMore =
4212       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4213   if (!hasMore())
4214     // Nothing to do.
4215     return;
4216 
4217   Out << "\n; uselistorder directives\n";
4218   while (hasMore()) {
4219     printUseListOrder(UseListOrders.back());
4220     UseListOrders.pop_back();
4221   }
4222 }
4223 
4224 //===----------------------------------------------------------------------===//
4225 //                       External Interface declarations
4226 //===----------------------------------------------------------------------===//
4227 
4228 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4229                      bool ShouldPreserveUseListOrder,
4230                      bool IsForDebug) const {
4231   SlotTracker SlotTable(this->getParent());
4232   formatted_raw_ostream OS(ROS);
4233   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4234                    IsForDebug,
4235                    ShouldPreserveUseListOrder);
4236   W.printFunction(this);
4237 }
4238 
4239 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4240                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4241   SlotTracker SlotTable(this);
4242   formatted_raw_ostream OS(ROS);
4243   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4244                    ShouldPreserveUseListOrder);
4245   W.printModule(this);
4246 }
4247 
4248 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4249   SlotTracker SlotTable(getParent());
4250   formatted_raw_ostream OS(ROS);
4251   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4252   W.printNamedMDNode(this);
4253 }
4254 
4255 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4256                         bool IsForDebug) const {
4257   Optional<SlotTracker> LocalST;
4258   SlotTracker *SlotTable;
4259   if (auto *ST = MST.getMachine())
4260     SlotTable = ST;
4261   else {
4262     LocalST.emplace(getParent());
4263     SlotTable = &*LocalST;
4264   }
4265 
4266   formatted_raw_ostream OS(ROS);
4267   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4268   W.printNamedMDNode(this);
4269 }
4270 
4271 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4272   PrintLLVMName(ROS, getName(), ComdatPrefix);
4273   ROS << " = comdat ";
4274 
4275   switch (getSelectionKind()) {
4276   case Comdat::Any:
4277     ROS << "any";
4278     break;
4279   case Comdat::ExactMatch:
4280     ROS << "exactmatch";
4281     break;
4282   case Comdat::Largest:
4283     ROS << "largest";
4284     break;
4285   case Comdat::NoDuplicates:
4286     ROS << "noduplicates";
4287     break;
4288   case Comdat::SameSize:
4289     ROS << "samesize";
4290     break;
4291   }
4292 
4293   ROS << '\n';
4294 }
4295 
4296 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4297   TypePrinting TP;
4298   TP.print(const_cast<Type*>(this), OS);
4299 
4300   if (NoDetails)
4301     return;
4302 
4303   // If the type is a named struct type, print the body as well.
4304   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4305     if (!STy->isLiteral()) {
4306       OS << " = type ";
4307       TP.printStructBody(STy, OS);
4308     }
4309 }
4310 
4311 static bool isReferencingMDNode(const Instruction &I) {
4312   if (const auto *CI = dyn_cast<CallInst>(&I))
4313     if (Function *F = CI->getCalledFunction())
4314       if (F->isIntrinsic())
4315         for (auto &Op : I.operands())
4316           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4317             if (isa<MDNode>(V->getMetadata()))
4318               return true;
4319   return false;
4320 }
4321 
4322 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4323   bool ShouldInitializeAllMetadata = false;
4324   if (auto *I = dyn_cast<Instruction>(this))
4325     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4326   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4327     ShouldInitializeAllMetadata = true;
4328 
4329   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4330   print(ROS, MST, IsForDebug);
4331 }
4332 
4333 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4334                   bool IsForDebug) const {
4335   formatted_raw_ostream OS(ROS);
4336   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4337   SlotTracker &SlotTable =
4338       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4339   auto incorporateFunction = [&](const Function *F) {
4340     if (F)
4341       MST.incorporateFunction(*F);
4342   };
4343 
4344   if (const Instruction *I = dyn_cast<Instruction>(this)) {
4345     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4346     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4347     W.printInstruction(*I);
4348   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4349     incorporateFunction(BB->getParent());
4350     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4351     W.printBasicBlock(BB);
4352   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4353     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4354     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4355       W.printGlobal(V);
4356     else if (const Function *F = dyn_cast<Function>(GV))
4357       W.printFunction(F);
4358     else
4359       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4360   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4361     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4362   } else if (const Constant *C = dyn_cast<Constant>(this)) {
4363     TypePrinting TypePrinter;
4364     TypePrinter.print(C->getType(), OS);
4365     OS << ' ';
4366     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4367   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4368     this->printAsOperand(OS, /* PrintType */ true, MST);
4369   } else {
4370     llvm_unreachable("Unknown value to print out!");
4371   }
4372 }
4373 
4374 /// Print without a type, skipping the TypePrinting object.
4375 ///
4376 /// \return \c true iff printing was successful.
4377 static bool printWithoutType(const Value &V, raw_ostream &O,
4378                              SlotTracker *Machine, const Module *M) {
4379   if (V.hasName() || isa<GlobalValue>(V) ||
4380       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4381     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4382     return true;
4383   }
4384   return false;
4385 }
4386 
4387 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4388                                ModuleSlotTracker &MST) {
4389   TypePrinting TypePrinter(MST.getModule());
4390   if (PrintType) {
4391     TypePrinter.print(V.getType(), O);
4392     O << ' ';
4393   }
4394 
4395   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4396                          MST.getModule());
4397 }
4398 
4399 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4400                            const Module *M) const {
4401   if (!M)
4402     M = getModuleFromVal(this);
4403 
4404   if (!PrintType)
4405     if (printWithoutType(*this, O, nullptr, M))
4406       return;
4407 
4408   SlotTracker Machine(
4409       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4410   ModuleSlotTracker MST(Machine, M);
4411   printAsOperandImpl(*this, O, PrintType, MST);
4412 }
4413 
4414 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4415                            ModuleSlotTracker &MST) const {
4416   if (!PrintType)
4417     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4418       return;
4419 
4420   printAsOperandImpl(*this, O, PrintType, MST);
4421 }
4422 
4423 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4424                               ModuleSlotTracker &MST, const Module *M,
4425                               bool OnlyAsOperand) {
4426   formatted_raw_ostream OS(ROS);
4427 
4428   TypePrinting TypePrinter(M);
4429 
4430   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4431                          /* FromValue */ true);
4432 
4433   auto *N = dyn_cast<MDNode>(&MD);
4434   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4435     return;
4436 
4437   OS << " = ";
4438   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4439 }
4440 
4441 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4442   ModuleSlotTracker MST(M, isa<MDNode>(this));
4443   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4444 }
4445 
4446 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4447                               const Module *M) const {
4448   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4449 }
4450 
4451 void Metadata::print(raw_ostream &OS, const Module *M,
4452                      bool /*IsForDebug*/) const {
4453   ModuleSlotTracker MST(M, isa<MDNode>(this));
4454   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4455 }
4456 
4457 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4458                      const Module *M, bool /*IsForDebug*/) const {
4459   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4460 }
4461 
4462 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4463   SlotTracker SlotTable(this);
4464   formatted_raw_ostream OS(ROS);
4465   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4466   W.printModuleSummaryIndex();
4467 }
4468 
4469 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4470 // Value::dump - allow easy printing of Values from the debugger.
4471 LLVM_DUMP_METHOD
4472 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4473 
4474 // Type::dump - allow easy printing of Types from the debugger.
4475 LLVM_DUMP_METHOD
4476 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4477 
4478 // Module::dump() - Allow printing of Modules from the debugger.
4479 LLVM_DUMP_METHOD
4480 void Module::dump() const {
4481   print(dbgs(), nullptr,
4482         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4483 }
4484 
4485 // Allow printing of Comdats from the debugger.
4486 LLVM_DUMP_METHOD
4487 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4488 
4489 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4490 LLVM_DUMP_METHOD
4491 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4492 
4493 LLVM_DUMP_METHOD
4494 void Metadata::dump() const { dump(nullptr); }
4495 
4496 LLVM_DUMP_METHOD
4497 void Metadata::dump(const Module *M) const {
4498   print(dbgs(), M, /*IsForDebug=*/true);
4499   dbgs() << '\n';
4500 }
4501 
4502 // Allow printing of ModuleSummaryIndex from the debugger.
4503 LLVM_DUMP_METHOD
4504 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4505 #endif
4506