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