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 << "<";
624     if (PTy->isScalable())
625       OS << "vscale x ";
626     OS << PTy->getNumElements() << " x ";
627     print(PTy->getElementType(), OS);
628     OS << '>';
629     return;
630   }
631   }
632   llvm_unreachable("Invalid TypeID");
633 }
634 
635 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
636   if (STy->isOpaque()) {
637     OS << "opaque";
638     return;
639   }
640 
641   if (STy->isPacked())
642     OS << '<';
643 
644   if (STy->getNumElements() == 0) {
645     OS << "{}";
646   } else {
647     StructType::element_iterator I = STy->element_begin();
648     OS << "{ ";
649     print(*I++, OS);
650     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
651       OS << ", ";
652       print(*I, OS);
653     }
654 
655     OS << " }";
656   }
657   if (STy->isPacked())
658     OS << '>';
659 }
660 
661 namespace llvm {
662 
663 //===----------------------------------------------------------------------===//
664 // SlotTracker Class: Enumerate slot numbers for unnamed values
665 //===----------------------------------------------------------------------===//
666 /// This class provides computation of slot numbers for LLVM Assembly writing.
667 ///
668 class SlotTracker {
669 public:
670   /// ValueMap - A mapping of Values to slot numbers.
671   using ValueMap = DenseMap<const Value *, unsigned>;
672 
673 private:
674   /// TheModule - The module for which we are holding slot numbers.
675   const Module* TheModule;
676 
677   /// TheFunction - The function for which we are holding slot numbers.
678   const Function* TheFunction = nullptr;
679   bool FunctionProcessed = false;
680   bool ShouldInitializeAllMetadata;
681 
682   /// The summary index for which we are holding slot numbers.
683   const ModuleSummaryIndex *TheIndex = nullptr;
684 
685   /// mMap - The slot map for the module level data.
686   ValueMap mMap;
687   unsigned mNext = 0;
688 
689   /// fMap - The slot map for the function level data.
690   ValueMap fMap;
691   unsigned fNext = 0;
692 
693   /// mdnMap - Map for MDNodes.
694   DenseMap<const MDNode*, unsigned> mdnMap;
695   unsigned mdnNext = 0;
696 
697   /// asMap - The slot map for attribute sets.
698   DenseMap<AttributeSet, unsigned> asMap;
699   unsigned asNext = 0;
700 
701   /// ModulePathMap - The slot map for Module paths used in the summary index.
702   StringMap<unsigned> ModulePathMap;
703   unsigned ModulePathNext = 0;
704 
705   /// GUIDMap - The slot map for GUIDs used in the summary index.
706   DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
707   unsigned GUIDNext = 0;
708 
709   /// TypeIdMap - The slot map for type ids used in the summary index.
710   StringMap<unsigned> TypeIdMap;
711   unsigned TypeIdNext = 0;
712 
713 public:
714   /// Construct from a module.
715   ///
716   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
717   /// functions, giving correct numbering for metadata referenced only from
718   /// within a function (even if no functions have been initialized).
719   explicit SlotTracker(const Module *M,
720                        bool ShouldInitializeAllMetadata = false);
721 
722   /// Construct from a function, starting out in incorp state.
723   ///
724   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
725   /// functions, giving correct numbering for metadata referenced only from
726   /// within a function (even if no functions have been initialized).
727   explicit SlotTracker(const Function *F,
728                        bool ShouldInitializeAllMetadata = false);
729 
730   /// Construct from a module summary index.
731   explicit SlotTracker(const ModuleSummaryIndex *Index);
732 
733   SlotTracker(const SlotTracker &) = delete;
734   SlotTracker &operator=(const SlotTracker &) = delete;
735 
736   /// Return the slot number of the specified value in it's type
737   /// plane.  If something is not in the SlotTracker, return -1.
738   int getLocalSlot(const Value *V);
739   int getGlobalSlot(const GlobalValue *V);
740   int getMetadataSlot(const MDNode *N);
741   int getAttributeGroupSlot(AttributeSet AS);
742   int getModulePathSlot(StringRef Path);
743   int getGUIDSlot(GlobalValue::GUID GUID);
744   int getTypeIdSlot(StringRef Id);
745 
746   /// If you'd like to deal with a function instead of just a module, use
747   /// this method to get its data into the SlotTracker.
748   void incorporateFunction(const Function *F) {
749     TheFunction = F;
750     FunctionProcessed = false;
751   }
752 
753   const Function *getFunction() const { return TheFunction; }
754 
755   /// After calling incorporateFunction, use this method to remove the
756   /// most recently incorporated function from the SlotTracker. This
757   /// will reset the state of the machine back to just the module contents.
758   void purgeFunction();
759 
760   /// MDNode map iterators.
761   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
762 
763   mdn_iterator mdn_begin() { return mdnMap.begin(); }
764   mdn_iterator mdn_end() { return mdnMap.end(); }
765   unsigned mdn_size() const { return mdnMap.size(); }
766   bool mdn_empty() const { return mdnMap.empty(); }
767 
768   /// AttributeSet map iterators.
769   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
770 
771   as_iterator as_begin()   { return asMap.begin(); }
772   as_iterator as_end()     { return asMap.end(); }
773   unsigned as_size() const { return asMap.size(); }
774   bool as_empty() const    { return asMap.empty(); }
775 
776   /// GUID map iterators.
777   using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
778 
779   /// These functions do the actual initialization.
780   inline void initializeIfNeeded();
781   void initializeIndexIfNeeded();
782 
783   // Implementation Details
784 private:
785   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
786   void CreateModuleSlot(const GlobalValue *V);
787 
788   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
789   void CreateMetadataSlot(const MDNode *N);
790 
791   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
792   void CreateFunctionSlot(const Value *V);
793 
794   /// Insert the specified AttributeSet into the slot table.
795   void CreateAttributeSetSlot(AttributeSet AS);
796 
797   inline void CreateModulePathSlot(StringRef Path);
798   void CreateGUIDSlot(GlobalValue::GUID GUID);
799   void CreateTypeIdSlot(StringRef Id);
800 
801   /// Add all of the module level global variables (and their initializers)
802   /// and function declarations, but not the contents of those functions.
803   void processModule();
804   void processIndex();
805 
806   /// Add all of the functions arguments, basic blocks, and instructions.
807   void processFunction();
808 
809   /// Add the metadata directly attached to a GlobalObject.
810   void processGlobalObjectMetadata(const GlobalObject &GO);
811 
812   /// Add all of the metadata from a function.
813   void processFunctionMetadata(const Function &F);
814 
815   /// Add all of the metadata from an instruction.
816   void processInstructionMetadata(const Instruction &I);
817 };
818 
819 } // end namespace llvm
820 
821 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
822                                      const Function *F)
823     : M(M), F(F), Machine(&Machine) {}
824 
825 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
826                                      bool ShouldInitializeAllMetadata)
827     : ShouldCreateStorage(M),
828       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
829 
830 ModuleSlotTracker::~ModuleSlotTracker() = default;
831 
832 SlotTracker *ModuleSlotTracker::getMachine() {
833   if (!ShouldCreateStorage)
834     return Machine;
835 
836   ShouldCreateStorage = false;
837   MachineStorage =
838       llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
839   Machine = MachineStorage.get();
840   return Machine;
841 }
842 
843 void ModuleSlotTracker::incorporateFunction(const Function &F) {
844   // Using getMachine() may lazily create the slot tracker.
845   if (!getMachine())
846     return;
847 
848   // Nothing to do if this is the right function already.
849   if (this->F == &F)
850     return;
851   if (this->F)
852     Machine->purgeFunction();
853   Machine->incorporateFunction(&F);
854   this->F = &F;
855 }
856 
857 int ModuleSlotTracker::getLocalSlot(const Value *V) {
858   assert(F && "No function incorporated");
859   return Machine->getLocalSlot(V);
860 }
861 
862 static SlotTracker *createSlotTracker(const Value *V) {
863   if (const Argument *FA = dyn_cast<Argument>(V))
864     return new SlotTracker(FA->getParent());
865 
866   if (const Instruction *I = dyn_cast<Instruction>(V))
867     if (I->getParent())
868       return new SlotTracker(I->getParent()->getParent());
869 
870   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
871     return new SlotTracker(BB->getParent());
872 
873   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
874     return new SlotTracker(GV->getParent());
875 
876   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
877     return new SlotTracker(GA->getParent());
878 
879   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
880     return new SlotTracker(GIF->getParent());
881 
882   if (const Function *Func = dyn_cast<Function>(V))
883     return new SlotTracker(Func);
884 
885   return nullptr;
886 }
887 
888 #if 0
889 #define ST_DEBUG(X) dbgs() << X
890 #else
891 #define ST_DEBUG(X)
892 #endif
893 
894 // Module level constructor. Causes the contents of the Module (sans functions)
895 // to be added to the slot table.
896 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
897     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
898 
899 // Function level constructor. Causes the contents of the Module and the one
900 // function provided to be added to the slot table.
901 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
902     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
903       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
904 
905 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
906     : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
907 
908 inline void SlotTracker::initializeIfNeeded() {
909   if (TheModule) {
910     processModule();
911     TheModule = nullptr; ///< Prevent re-processing next time we're called.
912   }
913 
914   if (TheFunction && !FunctionProcessed)
915     processFunction();
916 }
917 
918 void SlotTracker::initializeIndexIfNeeded() {
919   if (!TheIndex)
920     return;
921   processIndex();
922   TheIndex = nullptr; ///< Prevent re-processing next time we're called.
923 }
924 
925 // Iterate through all the global variables, functions, and global
926 // variable initializers and create slots for them.
927 void SlotTracker::processModule() {
928   ST_DEBUG("begin processModule!\n");
929 
930   // Add all of the unnamed global variables to the value table.
931   for (const GlobalVariable &Var : TheModule->globals()) {
932     if (!Var.hasName())
933       CreateModuleSlot(&Var);
934     processGlobalObjectMetadata(Var);
935     auto Attrs = Var.getAttributes();
936     if (Attrs.hasAttributes())
937       CreateAttributeSetSlot(Attrs);
938   }
939 
940   for (const GlobalAlias &A : TheModule->aliases()) {
941     if (!A.hasName())
942       CreateModuleSlot(&A);
943   }
944 
945   for (const GlobalIFunc &I : TheModule->ifuncs()) {
946     if (!I.hasName())
947       CreateModuleSlot(&I);
948   }
949 
950   // Add metadata used by named metadata.
951   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
952     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
953       CreateMetadataSlot(NMD.getOperand(i));
954   }
955 
956   for (const Function &F : *TheModule) {
957     if (!F.hasName())
958       // Add all the unnamed functions to the table.
959       CreateModuleSlot(&F);
960 
961     if (ShouldInitializeAllMetadata)
962       processFunctionMetadata(F);
963 
964     // Add all the function attributes to the table.
965     // FIXME: Add attributes of other objects?
966     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
967     if (FnAttrs.hasAttributes())
968       CreateAttributeSetSlot(FnAttrs);
969   }
970 
971   ST_DEBUG("end processModule!\n");
972 }
973 
974 // Process the arguments, basic blocks, and instructions  of a function.
975 void SlotTracker::processFunction() {
976   ST_DEBUG("begin processFunction!\n");
977   fNext = 0;
978 
979   // Process function metadata if it wasn't hit at the module-level.
980   if (!ShouldInitializeAllMetadata)
981     processFunctionMetadata(*TheFunction);
982 
983   // Add all the function arguments with no names.
984   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
985       AE = TheFunction->arg_end(); AI != AE; ++AI)
986     if (!AI->hasName())
987       CreateFunctionSlot(&*AI);
988 
989   ST_DEBUG("Inserting Instructions:\n");
990 
991   // Add all of the basic blocks and instructions with no names.
992   for (auto &BB : *TheFunction) {
993     if (!BB.hasName())
994       CreateFunctionSlot(&BB);
995 
996     for (auto &I : BB) {
997       if (!I.getType()->isVoidTy() && !I.hasName())
998         CreateFunctionSlot(&I);
999 
1000       // We allow direct calls to any llvm.foo function here, because the
1001       // target may not be linked into the optimizer.
1002       if (const auto *Call = dyn_cast<CallBase>(&I)) {
1003         // Add all the call attributes to the table.
1004         AttributeSet Attrs = Call->getAttributes().getFnAttributes();
1005         if (Attrs.hasAttributes())
1006           CreateAttributeSetSlot(Attrs);
1007       }
1008     }
1009   }
1010 
1011   FunctionProcessed = true;
1012 
1013   ST_DEBUG("end processFunction!\n");
1014 }
1015 
1016 // Iterate through all the GUID in the index and create slots for them.
1017 void SlotTracker::processIndex() {
1018   ST_DEBUG("begin processIndex!\n");
1019   assert(TheIndex);
1020 
1021   // The first block of slots are just the module ids, which start at 0 and are
1022   // assigned consecutively. Since the StringMap iteration order isn't
1023   // guaranteed, use a std::map to order by module ID before assigning slots.
1024   std::map<uint64_t, StringRef> ModuleIdToPathMap;
1025   for (auto &ModPath : TheIndex->modulePaths())
1026     ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1027   for (auto &ModPair : ModuleIdToPathMap)
1028     CreateModulePathSlot(ModPair.second);
1029 
1030   // Start numbering the GUIDs after the module ids.
1031   GUIDNext = ModulePathNext;
1032 
1033   for (auto &GlobalList : *TheIndex)
1034     CreateGUIDSlot(GlobalList.first);
1035 
1036   // Start numbering the TypeIds after the GUIDs.
1037   TypeIdNext = GUIDNext;
1038 
1039   for (auto TidIter = TheIndex->typeIds().begin();
1040        TidIter != TheIndex->typeIds().end(); TidIter++)
1041     CreateTypeIdSlot(TidIter->second.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 printTypeTestResolution(const TypeTestResolution &TTRes);
2417   void printArgs(const std::vector<uint64_t> &Args);
2418   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2419   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2420   void printVFuncId(const FunctionSummary::VFuncId VFId);
2421   void
2422   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
2423                       const char *Tag);
2424   void
2425   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
2426                    const char *Tag);
2427 
2428 private:
2429   /// Print out metadata attachments.
2430   void printMetadataAttachments(
2431       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2432       StringRef Separator);
2433 
2434   // printInfoComment - Print a little comment after the instruction indicating
2435   // which slot it occupies.
2436   void printInfoComment(const Value &V);
2437 
2438   // printGCRelocateComment - print comment after call to the gc.relocate
2439   // intrinsic indicating base and derived pointer names.
2440   void printGCRelocateComment(const GCRelocateInst &Relocate);
2441 };
2442 
2443 } // end anonymous namespace
2444 
2445 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2446                                const Module *M, AssemblyAnnotationWriter *AAW,
2447                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2448     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2449       IsForDebug(IsForDebug),
2450       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2451   if (!TheModule)
2452     return;
2453   for (const GlobalObject &GO : TheModule->global_objects())
2454     if (const Comdat *C = GO.getComdat())
2455       Comdats.insert(C);
2456 }
2457 
2458 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2459                                const ModuleSummaryIndex *Index, bool IsForDebug)
2460     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2461       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2462 
2463 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2464   if (!Operand) {
2465     Out << "<null operand!>";
2466     return;
2467   }
2468   if (PrintType) {
2469     TypePrinter.print(Operand->getType(), Out);
2470     Out << ' ';
2471   }
2472   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2473 }
2474 
2475 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2476                                     SyncScope::ID SSID) {
2477   switch (SSID) {
2478   case SyncScope::System: {
2479     break;
2480   }
2481   default: {
2482     if (SSNs.empty())
2483       Context.getSyncScopeNames(SSNs);
2484 
2485     Out << " syncscope(\"";
2486     printEscapedString(SSNs[SSID], Out);
2487     Out << "\")";
2488     break;
2489   }
2490   }
2491 }
2492 
2493 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2494                                  AtomicOrdering Ordering,
2495                                  SyncScope::ID SSID) {
2496   if (Ordering == AtomicOrdering::NotAtomic)
2497     return;
2498 
2499   writeSyncScope(Context, SSID);
2500   Out << " " << toIRString(Ordering);
2501 }
2502 
2503 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2504                                         AtomicOrdering SuccessOrdering,
2505                                         AtomicOrdering FailureOrdering,
2506                                         SyncScope::ID SSID) {
2507   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2508          FailureOrdering != AtomicOrdering::NotAtomic);
2509 
2510   writeSyncScope(Context, SSID);
2511   Out << " " << toIRString(SuccessOrdering);
2512   Out << " " << toIRString(FailureOrdering);
2513 }
2514 
2515 void AssemblyWriter::writeParamOperand(const Value *Operand,
2516                                        AttributeSet Attrs) {
2517   if (!Operand) {
2518     Out << "<null operand!>";
2519     return;
2520   }
2521 
2522   // Print the type
2523   TypePrinter.print(Operand->getType(), Out);
2524   // Print parameter attributes list
2525   if (Attrs.hasAttributes())
2526     Out << ' ' << Attrs.getAsString();
2527   Out << ' ';
2528   // Print the operand
2529   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2530 }
2531 
2532 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2533   if (!Call->hasOperandBundles())
2534     return;
2535 
2536   Out << " [ ";
2537 
2538   bool FirstBundle = true;
2539   for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2540     OperandBundleUse BU = Call->getOperandBundleAt(i);
2541 
2542     if (!FirstBundle)
2543       Out << ", ";
2544     FirstBundle = false;
2545 
2546     Out << '"';
2547     printEscapedString(BU.getTagName(), Out);
2548     Out << '"';
2549 
2550     Out << '(';
2551 
2552     bool FirstInput = true;
2553     for (const auto &Input : BU.Inputs) {
2554       if (!FirstInput)
2555         Out << ", ";
2556       FirstInput = false;
2557 
2558       TypePrinter.print(Input->getType(), Out);
2559       Out << " ";
2560       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2561     }
2562 
2563     Out << ')';
2564   }
2565 
2566   Out << " ]";
2567 }
2568 
2569 void AssemblyWriter::printModule(const Module *M) {
2570   Machine.initializeIfNeeded();
2571 
2572   if (ShouldPreserveUseListOrder)
2573     UseListOrders = predictUseListOrder(M);
2574 
2575   if (!M->getModuleIdentifier().empty() &&
2576       // Don't print the ID if it will start a new line (which would
2577       // require a comment char before it).
2578       M->getModuleIdentifier().find('\n') == std::string::npos)
2579     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2580 
2581   if (!M->getSourceFileName().empty()) {
2582     Out << "source_filename = \"";
2583     printEscapedString(M->getSourceFileName(), Out);
2584     Out << "\"\n";
2585   }
2586 
2587   const std::string &DL = M->getDataLayoutStr();
2588   if (!DL.empty())
2589     Out << "target datalayout = \"" << DL << "\"\n";
2590   if (!M->getTargetTriple().empty())
2591     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2592 
2593   if (!M->getModuleInlineAsm().empty()) {
2594     Out << '\n';
2595 
2596     // Split the string into lines, to make it easier to read the .ll file.
2597     StringRef Asm = M->getModuleInlineAsm();
2598     do {
2599       StringRef Front;
2600       std::tie(Front, Asm) = Asm.split('\n');
2601 
2602       // We found a newline, print the portion of the asm string from the
2603       // last newline up to this newline.
2604       Out << "module asm \"";
2605       printEscapedString(Front, Out);
2606       Out << "\"\n";
2607     } while (!Asm.empty());
2608   }
2609 
2610   printTypeIdentities();
2611 
2612   // Output all comdats.
2613   if (!Comdats.empty())
2614     Out << '\n';
2615   for (const Comdat *C : Comdats) {
2616     printComdat(C);
2617     if (C != Comdats.back())
2618       Out << '\n';
2619   }
2620 
2621   // Output all globals.
2622   if (!M->global_empty()) Out << '\n';
2623   for (const GlobalVariable &GV : M->globals()) {
2624     printGlobal(&GV); Out << '\n';
2625   }
2626 
2627   // Output all aliases.
2628   if (!M->alias_empty()) Out << "\n";
2629   for (const GlobalAlias &GA : M->aliases())
2630     printIndirectSymbol(&GA);
2631 
2632   // Output all ifuncs.
2633   if (!M->ifunc_empty()) Out << "\n";
2634   for (const GlobalIFunc &GI : M->ifuncs())
2635     printIndirectSymbol(&GI);
2636 
2637   // Output global use-lists.
2638   printUseLists(nullptr);
2639 
2640   // Output all of the functions.
2641   for (const Function &F : *M)
2642     printFunction(&F);
2643   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2644 
2645   // Output all attribute groups.
2646   if (!Machine.as_empty()) {
2647     Out << '\n';
2648     writeAllAttributeGroups();
2649   }
2650 
2651   // Output named metadata.
2652   if (!M->named_metadata_empty()) Out << '\n';
2653 
2654   for (const NamedMDNode &Node : M->named_metadata())
2655     printNamedMDNode(&Node);
2656 
2657   // Output metadata.
2658   if (!Machine.mdn_empty()) {
2659     Out << '\n';
2660     writeAllMDNodes();
2661   }
2662 }
2663 
2664 void AssemblyWriter::printModuleSummaryIndex() {
2665   assert(TheIndex);
2666   Machine.initializeIndexIfNeeded();
2667 
2668   Out << "\n";
2669 
2670   // Print module path entries. To print in order, add paths to a vector
2671   // indexed by module slot.
2672   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2673   std::string RegularLTOModuleName = "[Regular LTO]";
2674   moduleVec.resize(TheIndex->modulePaths().size());
2675   for (auto &ModPath : TheIndex->modulePaths())
2676     moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2677         // A module id of -1 is a special entry for a regular LTO module created
2678         // during the thin link.
2679         ModPath.second.first == -1u ? RegularLTOModuleName
2680                                     : (std::string)ModPath.first(),
2681         ModPath.second.second);
2682 
2683   unsigned i = 0;
2684   for (auto &ModPair : moduleVec) {
2685     Out << "^" << i++ << " = module: (";
2686     Out << "path: \"";
2687     printEscapedString(ModPair.first, Out);
2688     Out << "\", hash: (";
2689     FieldSeparator FS;
2690     for (auto Hash : ModPair.second)
2691       Out << FS << Hash;
2692     Out << "))\n";
2693   }
2694 
2695   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2696   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2697   for (auto &GlobalList : *TheIndex) {
2698     auto GUID = GlobalList.first;
2699     for (auto &Summary : GlobalList.second.SummaryList)
2700       SummaryToGUIDMap[Summary.get()] = GUID;
2701   }
2702 
2703   // Print the global value summary entries.
2704   for (auto &GlobalList : *TheIndex) {
2705     auto GUID = GlobalList.first;
2706     auto VI = TheIndex->getValueInfo(GlobalList);
2707     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2708   }
2709 
2710   // Print the TypeIdMap entries.
2711   for (auto TidIter = TheIndex->typeIds().begin();
2712        TidIter != TheIndex->typeIds().end(); TidIter++) {
2713     Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2714         << " = typeid: (name: \"" << TidIter->second.first << "\"";
2715     printTypeIdSummary(TidIter->second.second);
2716     Out << ") ; guid = " << TidIter->first << "\n";
2717   }
2718 }
2719 
2720 static const char *
2721 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2722   switch (K) {
2723   case WholeProgramDevirtResolution::Indir:
2724     return "indir";
2725   case WholeProgramDevirtResolution::SingleImpl:
2726     return "singleImpl";
2727   case WholeProgramDevirtResolution::BranchFunnel:
2728     return "branchFunnel";
2729   }
2730   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2731 }
2732 
2733 static const char *getWholeProgDevirtResByArgKindName(
2734     WholeProgramDevirtResolution::ByArg::Kind K) {
2735   switch (K) {
2736   case WholeProgramDevirtResolution::ByArg::Indir:
2737     return "indir";
2738   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2739     return "uniformRetVal";
2740   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2741     return "uniqueRetVal";
2742   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2743     return "virtualConstProp";
2744   }
2745   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2746 }
2747 
2748 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2749   switch (K) {
2750   case TypeTestResolution::Unsat:
2751     return "unsat";
2752   case TypeTestResolution::ByteArray:
2753     return "byteArray";
2754   case TypeTestResolution::Inline:
2755     return "inline";
2756   case TypeTestResolution::Single:
2757     return "single";
2758   case TypeTestResolution::AllOnes:
2759     return "allOnes";
2760   }
2761   llvm_unreachable("invalid TypeTestResolution kind");
2762 }
2763 
2764 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2765   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2766       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2767 
2768   // The following fields are only used if the target does not support the use
2769   // of absolute symbols to store constants. Print only if non-zero.
2770   if (TTRes.AlignLog2)
2771     Out << ", alignLog2: " << TTRes.AlignLog2;
2772   if (TTRes.SizeM1)
2773     Out << ", sizeM1: " << TTRes.SizeM1;
2774   if (TTRes.BitMask)
2775     // BitMask is uint8_t which causes it to print the corresponding char.
2776     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2777   if (TTRes.InlineBits)
2778     Out << ", inlineBits: " << TTRes.InlineBits;
2779 
2780   Out << ")";
2781 }
2782 
2783 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2784   Out << ", summary: (";
2785   printTypeTestResolution(TIS.TTRes);
2786   if (!TIS.WPDRes.empty()) {
2787     Out << ", wpdResolutions: (";
2788     FieldSeparator FS;
2789     for (auto &WPDRes : TIS.WPDRes) {
2790       Out << FS;
2791       Out << "(offset: " << WPDRes.first << ", ";
2792       printWPDRes(WPDRes.second);
2793       Out << ")";
2794     }
2795     Out << ")";
2796   }
2797   Out << ")";
2798 }
2799 
2800 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2801   Out << "args: (";
2802   FieldSeparator FS;
2803   for (auto arg : Args) {
2804     Out << FS;
2805     Out << arg;
2806   }
2807   Out << ")";
2808 }
2809 
2810 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2811   Out << "wpdRes: (kind: ";
2812   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2813 
2814   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
2815     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2816 
2817   if (!WPDRes.ResByArg.empty()) {
2818     Out << ", resByArg: (";
2819     FieldSeparator FS;
2820     for (auto &ResByArg : WPDRes.ResByArg) {
2821       Out << FS;
2822       printArgs(ResByArg.first);
2823       Out << ", byArg: (kind: ";
2824       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2825       if (ResByArg.second.TheKind ==
2826               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
2827           ResByArg.second.TheKind ==
2828               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
2829         Out << ", info: " << ResByArg.second.Info;
2830 
2831       // The following fields are only used if the target does not support the
2832       // use of absolute symbols to store constants. Print only if non-zero.
2833       if (ResByArg.second.Byte || ResByArg.second.Bit)
2834         Out << ", byte: " << ResByArg.second.Byte
2835             << ", bit: " << ResByArg.second.Bit;
2836 
2837       Out << ")";
2838     }
2839     Out << ")";
2840   }
2841   Out << ")";
2842 }
2843 
2844 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
2845   switch (SK) {
2846   case GlobalValueSummary::AliasKind:
2847     return "alias";
2848   case GlobalValueSummary::FunctionKind:
2849     return "function";
2850   case GlobalValueSummary::GlobalVarKind:
2851     return "variable";
2852   }
2853   llvm_unreachable("invalid summary kind");
2854 }
2855 
2856 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
2857   Out << ", aliasee: ";
2858   // The indexes emitted for distributed backends may not include the
2859   // aliasee summary (only if it is being imported directly). Handle
2860   // that case by just emitting "null" as the aliasee.
2861   if (AS->hasAliasee())
2862     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2863   else
2864     Out << "null";
2865 }
2866 
2867 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2868   Out << ", varFlags: (readonly: " << GS->VarFlags.ReadOnly << ")";
2869 }
2870 
2871 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
2872   switch (LT) {
2873   case GlobalValue::ExternalLinkage:
2874     return "external";
2875   case GlobalValue::PrivateLinkage:
2876     return "private";
2877   case GlobalValue::InternalLinkage:
2878     return "internal";
2879   case GlobalValue::LinkOnceAnyLinkage:
2880     return "linkonce";
2881   case GlobalValue::LinkOnceODRLinkage:
2882     return "linkonce_odr";
2883   case GlobalValue::WeakAnyLinkage:
2884     return "weak";
2885   case GlobalValue::WeakODRLinkage:
2886     return "weak_odr";
2887   case GlobalValue::CommonLinkage:
2888     return "common";
2889   case GlobalValue::AppendingLinkage:
2890     return "appending";
2891   case GlobalValue::ExternalWeakLinkage:
2892     return "extern_weak";
2893   case GlobalValue::AvailableExternallyLinkage:
2894     return "available_externally";
2895   }
2896   llvm_unreachable("invalid linkage");
2897 }
2898 
2899 // When printing the linkage types in IR where the ExternalLinkage is
2900 // not printed, and other linkage types are expected to be printed with
2901 // a space after the name.
2902 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
2903   if (LT == GlobalValue::ExternalLinkage)
2904     return "";
2905   return getLinkageName(LT) + " ";
2906 }
2907 
2908 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2909   Out << ", insts: " << FS->instCount();
2910 
2911   FunctionSummary::FFlags FFlags = FS->fflags();
2912   if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2913       FFlags.ReturnDoesNotAlias) {
2914     Out << ", funcFlags: (";
2915     Out << "readNone: " << FFlags.ReadNone;
2916     Out << ", readOnly: " << FFlags.ReadOnly;
2917     Out << ", noRecurse: " << FFlags.NoRecurse;
2918     Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2919     Out << ", noInline: " << FFlags.NoInline;
2920     Out << ")";
2921   }
2922   if (!FS->calls().empty()) {
2923     Out << ", calls: (";
2924     FieldSeparator IFS;
2925     for (auto &Call : FS->calls()) {
2926       Out << IFS;
2927       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2928       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2929         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2930       else if (Call.second.RelBlockFreq)
2931         Out << ", relbf: " << Call.second.RelBlockFreq;
2932       Out << ")";
2933     }
2934     Out << ")";
2935   }
2936 
2937   if (const auto *TIdInfo = FS->getTypeIdInfo())
2938     printTypeIdInfo(*TIdInfo);
2939 }
2940 
2941 void AssemblyWriter::printTypeIdInfo(
2942     const FunctionSummary::TypeIdInfo &TIDInfo) {
2943   Out << ", typeIdInfo: (";
2944   FieldSeparator TIDFS;
2945   if (!TIDInfo.TypeTests.empty()) {
2946     Out << TIDFS;
2947     Out << "typeTests: (";
2948     FieldSeparator FS;
2949     for (auto &GUID : TIDInfo.TypeTests) {
2950       auto TidIter = TheIndex->typeIds().equal_range(GUID);
2951       if (TidIter.first == TidIter.second) {
2952         Out << FS;
2953         Out << GUID;
2954         continue;
2955       }
2956       // Print all type id that correspond to this GUID.
2957       for (auto It = TidIter.first; It != TidIter.second; ++It) {
2958         Out << FS;
2959         auto Slot = Machine.getTypeIdSlot(It->second.first);
2960         assert(Slot != -1);
2961         Out << "^" << Slot;
2962       }
2963     }
2964     Out << ")";
2965   }
2966   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
2967     Out << TIDFS;
2968     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
2969   }
2970   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
2971     Out << TIDFS;
2972     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
2973   }
2974   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
2975     Out << TIDFS;
2976     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
2977                      "typeTestAssumeConstVCalls");
2978   }
2979   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
2980     Out << TIDFS;
2981     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
2982                      "typeCheckedLoadConstVCalls");
2983   }
2984   Out << ")";
2985 }
2986 
2987 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
2988   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
2989   if (TidIter.first == TidIter.second) {
2990     Out << "vFuncId: (";
2991     Out << "guid: " << VFId.GUID;
2992     Out << ", offset: " << VFId.Offset;
2993     Out << ")";
2994     return;
2995   }
2996   // Print all type id that correspond to this GUID.
2997   FieldSeparator FS;
2998   for (auto It = TidIter.first; It != TidIter.second; ++It) {
2999     Out << FS;
3000     Out << "vFuncId: (";
3001     auto Slot = Machine.getTypeIdSlot(It->second.first);
3002     assert(Slot != -1);
3003     Out << "^" << Slot;
3004     Out << ", offset: " << VFId.Offset;
3005     Out << ")";
3006   }
3007 }
3008 
3009 void AssemblyWriter::printNonConstVCalls(
3010     const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
3011   Out << Tag << ": (";
3012   FieldSeparator FS;
3013   for (auto &VFuncId : VCallList) {
3014     Out << FS;
3015     printVFuncId(VFuncId);
3016   }
3017   Out << ")";
3018 }
3019 
3020 void AssemblyWriter::printConstVCalls(
3021     const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
3022   Out << Tag << ": (";
3023   FieldSeparator FS;
3024   for (auto &ConstVCall : VCallList) {
3025     Out << FS;
3026     Out << "(";
3027     printVFuncId(ConstVCall.VFunc);
3028     if (!ConstVCall.Args.empty()) {
3029       Out << ", ";
3030       printArgs(ConstVCall.Args);
3031     }
3032     Out << ")";
3033   }
3034   Out << ")";
3035 }
3036 
3037 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3038   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3039   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3040   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3041   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3042       << ", flags: (";
3043   Out << "linkage: " << getLinkageName(LT);
3044   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3045   Out << ", live: " << GVFlags.Live;
3046   Out << ", dsoLocal: " << GVFlags.DSOLocal;
3047   Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3048   Out << ")";
3049 
3050   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3051     printAliasSummary(cast<AliasSummary>(&Summary));
3052   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3053     printFunctionSummary(cast<FunctionSummary>(&Summary));
3054   else
3055     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3056 
3057   auto RefList = Summary.refs();
3058   if (!RefList.empty()) {
3059     Out << ", refs: (";
3060     FieldSeparator FS;
3061     for (auto &Ref : RefList) {
3062       Out << FS;
3063       if (Ref.isReadOnly())
3064         Out << "readonly ";
3065       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3066     }
3067     Out << ")";
3068   }
3069 
3070   Out << ")";
3071 }
3072 
3073 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3074   Out << "^" << Slot << " = gv: (";
3075   if (!VI.name().empty())
3076     Out << "name: \"" << VI.name() << "\"";
3077   else
3078     Out << "guid: " << VI.getGUID();
3079   if (!VI.getSummaryList().empty()) {
3080     Out << ", summaries: (";
3081     FieldSeparator FS;
3082     for (auto &Summary : VI.getSummaryList()) {
3083       Out << FS;
3084       printSummary(*Summary);
3085     }
3086     Out << ")";
3087   }
3088   Out << ")";
3089   if (!VI.name().empty())
3090     Out << " ; guid = " << VI.getGUID();
3091   Out << "\n";
3092 }
3093 
3094 static void printMetadataIdentifier(StringRef Name,
3095                                     formatted_raw_ostream &Out) {
3096   if (Name.empty()) {
3097     Out << "<empty name> ";
3098   } else {
3099     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3100         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3101       Out << Name[0];
3102     else
3103       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3104     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3105       unsigned char C = Name[i];
3106       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3107           C == '.' || C == '_')
3108         Out << C;
3109       else
3110         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3111     }
3112   }
3113 }
3114 
3115 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3116   Out << '!';
3117   printMetadataIdentifier(NMD->getName(), Out);
3118   Out << " = !{";
3119   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3120     if (i)
3121       Out << ", ";
3122 
3123     // Write DIExpressions inline.
3124     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3125     MDNode *Op = NMD->getOperand(i);
3126     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3127       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3128       continue;
3129     }
3130 
3131     int Slot = Machine.getMetadataSlot(Op);
3132     if (Slot == -1)
3133       Out << "<badref>";
3134     else
3135       Out << '!' << Slot;
3136   }
3137   Out << "}\n";
3138 }
3139 
3140 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3141                             formatted_raw_ostream &Out) {
3142   switch (Vis) {
3143   case GlobalValue::DefaultVisibility: break;
3144   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
3145   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3146   }
3147 }
3148 
3149 static void PrintDSOLocation(const GlobalValue &GV,
3150                              formatted_raw_ostream &Out) {
3151   // GVs with local linkage or non default visibility are implicitly dso_local,
3152   // so we don't print it.
3153   bool Implicit = GV.hasLocalLinkage() ||
3154                   (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
3155   if (GV.isDSOLocal() && !Implicit)
3156     Out << "dso_local ";
3157 }
3158 
3159 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3160                                  formatted_raw_ostream &Out) {
3161   switch (SCT) {
3162   case GlobalValue::DefaultStorageClass: break;
3163   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3164   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3165   }
3166 }
3167 
3168 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3169                                   formatted_raw_ostream &Out) {
3170   switch (TLM) {
3171     case GlobalVariable::NotThreadLocal:
3172       break;
3173     case GlobalVariable::GeneralDynamicTLSModel:
3174       Out << "thread_local ";
3175       break;
3176     case GlobalVariable::LocalDynamicTLSModel:
3177       Out << "thread_local(localdynamic) ";
3178       break;
3179     case GlobalVariable::InitialExecTLSModel:
3180       Out << "thread_local(initialexec) ";
3181       break;
3182     case GlobalVariable::LocalExecTLSModel:
3183       Out << "thread_local(localexec) ";
3184       break;
3185   }
3186 }
3187 
3188 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3189   switch (UA) {
3190   case GlobalVariable::UnnamedAddr::None:
3191     return "";
3192   case GlobalVariable::UnnamedAddr::Local:
3193     return "local_unnamed_addr";
3194   case GlobalVariable::UnnamedAddr::Global:
3195     return "unnamed_addr";
3196   }
3197   llvm_unreachable("Unknown UnnamedAddr");
3198 }
3199 
3200 static void maybePrintComdat(formatted_raw_ostream &Out,
3201                              const GlobalObject &GO) {
3202   const Comdat *C = GO.getComdat();
3203   if (!C)
3204     return;
3205 
3206   if (isa<GlobalVariable>(GO))
3207     Out << ',';
3208   Out << " comdat";
3209 
3210   if (GO.getName() == C->getName())
3211     return;
3212 
3213   Out << '(';
3214   PrintLLVMName(Out, C->getName(), ComdatPrefix);
3215   Out << ')';
3216 }
3217 
3218 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3219   if (GV->isMaterializable())
3220     Out << "; Materializable\n";
3221 
3222   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3223   Out << " = ";
3224 
3225   if (!GV->hasInitializer() && GV->hasExternalLinkage())
3226     Out << "external ";
3227 
3228   Out << getLinkageNameWithSpace(GV->getLinkage());
3229   PrintDSOLocation(*GV, Out);
3230   PrintVisibility(GV->getVisibility(), Out);
3231   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3232   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3233   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3234   if (!UA.empty())
3235       Out << UA << ' ';
3236 
3237   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3238     Out << "addrspace(" << AddressSpace << ") ";
3239   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3240   Out << (GV->isConstant() ? "constant " : "global ");
3241   TypePrinter.print(GV->getValueType(), Out);
3242 
3243   if (GV->hasInitializer()) {
3244     Out << ' ';
3245     writeOperand(GV->getInitializer(), false);
3246   }
3247 
3248   if (GV->hasSection()) {
3249     Out << ", section \"";
3250     printEscapedString(GV->getSection(), Out);
3251     Out << '"';
3252   }
3253   if (GV->hasPartition()) {
3254     Out << ", partition \"";
3255     printEscapedString(GV->getPartition(), Out);
3256     Out << '"';
3257   }
3258 
3259   maybePrintComdat(Out, *GV);
3260   if (GV->getAlignment())
3261     Out << ", align " << GV->getAlignment();
3262 
3263   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3264   GV->getAllMetadata(MDs);
3265   printMetadataAttachments(MDs, ", ");
3266 
3267   auto Attrs = GV->getAttributes();
3268   if (Attrs.hasAttributes())
3269     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3270 
3271   printInfoComment(*GV);
3272 }
3273 
3274 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3275   if (GIS->isMaterializable())
3276     Out << "; Materializable\n";
3277 
3278   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3279   Out << " = ";
3280 
3281   Out << getLinkageNameWithSpace(GIS->getLinkage());
3282   PrintDSOLocation(*GIS, Out);
3283   PrintVisibility(GIS->getVisibility(), Out);
3284   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3285   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
3286   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3287   if (!UA.empty())
3288       Out << UA << ' ';
3289 
3290   if (isa<GlobalAlias>(GIS))
3291     Out << "alias ";
3292   else if (isa<GlobalIFunc>(GIS))
3293     Out << "ifunc ";
3294   else
3295     llvm_unreachable("Not an alias or ifunc!");
3296 
3297   TypePrinter.print(GIS->getValueType(), Out);
3298 
3299   Out << ", ";
3300 
3301   const Constant *IS = GIS->getIndirectSymbol();
3302 
3303   if (!IS) {
3304     TypePrinter.print(GIS->getType(), Out);
3305     Out << " <<NULL ALIASEE>>";
3306   } else {
3307     writeOperand(IS, !isa<ConstantExpr>(IS));
3308   }
3309 
3310   if (GIS->hasPartition()) {
3311     Out << ", partition \"";
3312     printEscapedString(GIS->getPartition(), Out);
3313     Out << '"';
3314   }
3315 
3316   printInfoComment(*GIS);
3317   Out << '\n';
3318 }
3319 
3320 void AssemblyWriter::printComdat(const Comdat *C) {
3321   C->print(Out);
3322 }
3323 
3324 void AssemblyWriter::printTypeIdentities() {
3325   if (TypePrinter.empty())
3326     return;
3327 
3328   Out << '\n';
3329 
3330   // Emit all numbered types.
3331   auto &NumberedTypes = TypePrinter.getNumberedTypes();
3332   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3333     Out << '%' << I << " = type ";
3334 
3335     // Make sure we print out at least one level of the type structure, so
3336     // that we do not get %2 = type %2
3337     TypePrinter.printStructBody(NumberedTypes[I], Out);
3338     Out << '\n';
3339   }
3340 
3341   auto &NamedTypes = TypePrinter.getNamedTypes();
3342   for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3343     PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3344     Out << " = type ";
3345 
3346     // Make sure we print out at least one level of the type structure, so
3347     // that we do not get %FILE = type %FILE
3348     TypePrinter.printStructBody(NamedTypes[I], Out);
3349     Out << '\n';
3350   }
3351 }
3352 
3353 /// printFunction - Print all aspects of a function.
3354 void AssemblyWriter::printFunction(const Function *F) {
3355   // Print out the return type and name.
3356   Out << '\n';
3357 
3358   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3359 
3360   if (F->isMaterializable())
3361     Out << "; Materializable\n";
3362 
3363   const AttributeList &Attrs = F->getAttributes();
3364   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
3365     AttributeSet AS = Attrs.getFnAttributes();
3366     std::string AttrStr;
3367 
3368     for (const Attribute &Attr : AS) {
3369       if (!Attr.isStringAttribute()) {
3370         if (!AttrStr.empty()) AttrStr += ' ';
3371         AttrStr += Attr.getAsString();
3372       }
3373     }
3374 
3375     if (!AttrStr.empty())
3376       Out << "; Function Attrs: " << AttrStr << '\n';
3377   }
3378 
3379   Machine.incorporateFunction(F);
3380 
3381   if (F->isDeclaration()) {
3382     Out << "declare";
3383     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3384     F->getAllMetadata(MDs);
3385     printMetadataAttachments(MDs, " ");
3386     Out << ' ';
3387   } else
3388     Out << "define ";
3389 
3390   Out << getLinkageNameWithSpace(F->getLinkage());
3391   PrintDSOLocation(*F, Out);
3392   PrintVisibility(F->getVisibility(), Out);
3393   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3394 
3395   // Print the calling convention.
3396   if (F->getCallingConv() != CallingConv::C) {
3397     PrintCallingConv(F->getCallingConv(), Out);
3398     Out << " ";
3399   }
3400 
3401   FunctionType *FT = F->getFunctionType();
3402   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3403     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3404   TypePrinter.print(F->getReturnType(), Out);
3405   Out << ' ';
3406   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3407   Out << '(';
3408 
3409   // Loop over the arguments, printing them...
3410   if (F->isDeclaration() && !IsForDebug) {
3411     // We're only interested in the type here - don't print argument names.
3412     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3413       // Insert commas as we go... the first arg doesn't get a comma
3414       if (I)
3415         Out << ", ";
3416       // Output type...
3417       TypePrinter.print(FT->getParamType(I), Out);
3418 
3419       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3420       if (ArgAttrs.hasAttributes())
3421         Out << ' ' << ArgAttrs.getAsString();
3422     }
3423   } else {
3424     // The arguments are meaningful here, print them in detail.
3425     for (const Argument &Arg : F->args()) {
3426       // Insert commas as we go... the first arg doesn't get a comma
3427       if (Arg.getArgNo() != 0)
3428         Out << ", ";
3429       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3430     }
3431   }
3432 
3433   // Finish printing arguments...
3434   if (FT->isVarArg()) {
3435     if (FT->getNumParams()) Out << ", ";
3436     Out << "...";  // Output varargs portion of signature!
3437   }
3438   Out << ')';
3439   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3440   if (!UA.empty())
3441     Out << ' ' << UA;
3442   // We print the function address space if it is non-zero or if we are writing
3443   // a module with a non-zero program address space or if there is no valid
3444   // Module* so that the file can be parsed without the datalayout string.
3445   const Module *Mod = F->getParent();
3446   if (F->getAddressSpace() != 0 || !Mod ||
3447       Mod->getDataLayout().getProgramAddressSpace() != 0)
3448     Out << " addrspace(" << F->getAddressSpace() << ")";
3449   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
3450     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3451   if (F->hasSection()) {
3452     Out << " section \"";
3453     printEscapedString(F->getSection(), Out);
3454     Out << '"';
3455   }
3456   if (F->hasPartition()) {
3457     Out << " partition \"";
3458     printEscapedString(F->getPartition(), Out);
3459     Out << '"';
3460   }
3461   maybePrintComdat(Out, *F);
3462   if (F->getAlignment())
3463     Out << " align " << F->getAlignment();
3464   if (F->hasGC())
3465     Out << " gc \"" << F->getGC() << '"';
3466   if (F->hasPrefixData()) {
3467     Out << " prefix ";
3468     writeOperand(F->getPrefixData(), true);
3469   }
3470   if (F->hasPrologueData()) {
3471     Out << " prologue ";
3472     writeOperand(F->getPrologueData(), true);
3473   }
3474   if (F->hasPersonalityFn()) {
3475     Out << " personality ";
3476     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3477   }
3478 
3479   if (F->isDeclaration()) {
3480     Out << '\n';
3481   } else {
3482     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3483     F->getAllMetadata(MDs);
3484     printMetadataAttachments(MDs, " ");
3485 
3486     Out << " {";
3487     // Output all of the function's basic blocks.
3488     for (const BasicBlock &BB : *F)
3489       printBasicBlock(&BB);
3490 
3491     // Output the function's use-lists.
3492     printUseLists(F);
3493 
3494     Out << "}\n";
3495   }
3496 
3497   Machine.purgeFunction();
3498 }
3499 
3500 /// printArgument - This member is called for every argument that is passed into
3501 /// the function.  Simply print it out
3502 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3503   // Output type...
3504   TypePrinter.print(Arg->getType(), Out);
3505 
3506   // Output parameter attributes list
3507   if (Attrs.hasAttributes())
3508     Out << ' ' << Attrs.getAsString();
3509 
3510   // Output name, if available...
3511   if (Arg->hasName()) {
3512     Out << ' ';
3513     PrintLLVMName(Out, Arg);
3514   }
3515 }
3516 
3517 /// printBasicBlock - This member is called for each basic block in a method.
3518 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3519   bool IsEntryBlock = BB == &BB->getParent()->getEntryBlock();
3520   if (BB->hasName()) {              // Print out the label if it exists...
3521     Out << "\n";
3522     PrintLLVMName(Out, BB->getName(), LabelPrefix);
3523     Out << ':';
3524   } else if (!IsEntryBlock) {
3525     Out << "\n";
3526     int Slot = Machine.getLocalSlot(BB);
3527     if (Slot != -1)
3528       Out << Slot << ":";
3529     else
3530       Out << "<badref>:";
3531   }
3532 
3533   if (!BB->getParent()) {
3534     Out.PadToColumn(50);
3535     Out << "; Error: Block without parent!";
3536   } else if (!IsEntryBlock) {
3537     // Output predecessors for the block.
3538     Out.PadToColumn(50);
3539     Out << ";";
3540     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3541 
3542     if (PI == PE) {
3543       Out << " No predecessors!";
3544     } else {
3545       Out << " preds = ";
3546       writeOperand(*PI, false);
3547       for (++PI; PI != PE; ++PI) {
3548         Out << ", ";
3549         writeOperand(*PI, false);
3550       }
3551     }
3552   }
3553 
3554   Out << "\n";
3555 
3556   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3557 
3558   // Output all of the instructions in the basic block...
3559   for (const Instruction &I : *BB) {
3560     printInstructionLine(I);
3561   }
3562 
3563   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3564 }
3565 
3566 /// printInstructionLine - Print an instruction and a newline character.
3567 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3568   printInstruction(I);
3569   Out << '\n';
3570 }
3571 
3572 /// printGCRelocateComment - print comment after call to the gc.relocate
3573 /// intrinsic indicating base and derived pointer names.
3574 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3575   Out << " ; (";
3576   writeOperand(Relocate.getBasePtr(), false);
3577   Out << ", ";
3578   writeOperand(Relocate.getDerivedPtr(), false);
3579   Out << ")";
3580 }
3581 
3582 /// printInfoComment - Print a little comment after the instruction indicating
3583 /// which slot it occupies.
3584 void AssemblyWriter::printInfoComment(const Value &V) {
3585   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3586     printGCRelocateComment(*Relocate);
3587 
3588   if (AnnotationWriter)
3589     AnnotationWriter->printInfoComment(V, Out);
3590 }
3591 
3592 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3593                                     raw_ostream &Out) {
3594   // We print the address space of the call if it is non-zero.
3595   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3596   bool PrintAddrSpace = CallAddrSpace != 0;
3597   if (!PrintAddrSpace) {
3598     const Module *Mod = getModuleFromVal(I);
3599     // We also print it if it is zero but not equal to the program address space
3600     // or if we can't find a valid Module* to make it possible to parse
3601     // the resulting file even without a datalayout string.
3602     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3603       PrintAddrSpace = true;
3604   }
3605   if (PrintAddrSpace)
3606     Out << " addrspace(" << CallAddrSpace << ")";
3607 }
3608 
3609 // This member is called for each Instruction in a function..
3610 void AssemblyWriter::printInstruction(const Instruction &I) {
3611   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3612 
3613   // Print out indentation for an instruction.
3614   Out << "  ";
3615 
3616   // Print out name if it exists...
3617   if (I.hasName()) {
3618     PrintLLVMName(Out, &I);
3619     Out << " = ";
3620   } else if (!I.getType()->isVoidTy()) {
3621     // Print out the def slot taken.
3622     int SlotNum = Machine.getLocalSlot(&I);
3623     if (SlotNum == -1)
3624       Out << "<badref> = ";
3625     else
3626       Out << '%' << SlotNum << " = ";
3627   }
3628 
3629   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3630     if (CI->isMustTailCall())
3631       Out << "musttail ";
3632     else if (CI->isTailCall())
3633       Out << "tail ";
3634     else if (CI->isNoTailCall())
3635       Out << "notail ";
3636   }
3637 
3638   // Print out the opcode...
3639   Out << I.getOpcodeName();
3640 
3641   // If this is an atomic load or store, print out the atomic marker.
3642   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
3643       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3644     Out << " atomic";
3645 
3646   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3647     Out << " weak";
3648 
3649   // If this is a volatile operation, print out the volatile marker.
3650   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
3651       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3652       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3653       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3654     Out << " volatile";
3655 
3656   // Print out optimization information.
3657   WriteOptimizationInfo(Out, &I);
3658 
3659   // Print out the compare instruction predicates
3660   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3661     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3662 
3663   // Print out the atomicrmw operation
3664   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3665     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3666 
3667   // Print out the type of the operands...
3668   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3669 
3670   // Special case conditional branches to swizzle the condition out to the front
3671   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3672     const BranchInst &BI(cast<BranchInst>(I));
3673     Out << ' ';
3674     writeOperand(BI.getCondition(), true);
3675     Out << ", ";
3676     writeOperand(BI.getSuccessor(0), true);
3677     Out << ", ";
3678     writeOperand(BI.getSuccessor(1), true);
3679 
3680   } else if (isa<SwitchInst>(I)) {
3681     const SwitchInst& SI(cast<SwitchInst>(I));
3682     // Special case switch instruction to get formatting nice and correct.
3683     Out << ' ';
3684     writeOperand(SI.getCondition(), true);
3685     Out << ", ";
3686     writeOperand(SI.getDefaultDest(), true);
3687     Out << " [";
3688     for (auto Case : SI.cases()) {
3689       Out << "\n    ";
3690       writeOperand(Case.getCaseValue(), true);
3691       Out << ", ";
3692       writeOperand(Case.getCaseSuccessor(), true);
3693     }
3694     Out << "\n  ]";
3695   } else if (isa<IndirectBrInst>(I)) {
3696     // Special case indirectbr instruction to get formatting nice and correct.
3697     Out << ' ';
3698     writeOperand(Operand, true);
3699     Out << ", [";
3700 
3701     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3702       if (i != 1)
3703         Out << ", ";
3704       writeOperand(I.getOperand(i), true);
3705     }
3706     Out << ']';
3707   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3708     Out << ' ';
3709     TypePrinter.print(I.getType(), Out);
3710     Out << ' ';
3711 
3712     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3713       if (op) Out << ", ";
3714       Out << "[ ";
3715       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3716       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3717     }
3718   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3719     Out << ' ';
3720     writeOperand(I.getOperand(0), true);
3721     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3722       Out << ", " << *i;
3723   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3724     Out << ' ';
3725     writeOperand(I.getOperand(0), true); Out << ", ";
3726     writeOperand(I.getOperand(1), true);
3727     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3728       Out << ", " << *i;
3729   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3730     Out << ' ';
3731     TypePrinter.print(I.getType(), Out);
3732     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3733       Out << '\n';
3734 
3735     if (LPI->isCleanup())
3736       Out << "          cleanup";
3737 
3738     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3739       if (i != 0 || LPI->isCleanup()) Out << "\n";
3740       if (LPI->isCatch(i))
3741         Out << "          catch ";
3742       else
3743         Out << "          filter ";
3744 
3745       writeOperand(LPI->getClause(i), true);
3746     }
3747   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3748     Out << " within ";
3749     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3750     Out << " [";
3751     unsigned Op = 0;
3752     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3753       if (Op > 0)
3754         Out << ", ";
3755       writeOperand(PadBB, /*PrintType=*/true);
3756       ++Op;
3757     }
3758     Out << "] unwind ";
3759     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3760       writeOperand(UnwindDest, /*PrintType=*/true);
3761     else
3762       Out << "to caller";
3763   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3764     Out << " within ";
3765     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3766     Out << " [";
3767     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3768          ++Op) {
3769       if (Op > 0)
3770         Out << ", ";
3771       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3772     }
3773     Out << ']';
3774   } else if (isa<ReturnInst>(I) && !Operand) {
3775     Out << " void";
3776   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3777     Out << " from ";
3778     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3779 
3780     Out << " to ";
3781     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3782   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3783     Out << " from ";
3784     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3785 
3786     Out << " unwind ";
3787     if (CRI->hasUnwindDest())
3788       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3789     else
3790       Out << "to caller";
3791   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3792     // Print the calling convention being used.
3793     if (CI->getCallingConv() != CallingConv::C) {
3794       Out << " ";
3795       PrintCallingConv(CI->getCallingConv(), Out);
3796     }
3797 
3798     Operand = CI->getCalledValue();
3799     FunctionType *FTy = CI->getFunctionType();
3800     Type *RetTy = FTy->getReturnType();
3801     const AttributeList &PAL = CI->getAttributes();
3802 
3803     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3804       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3805 
3806     // Only print addrspace(N) if necessary:
3807     maybePrintCallAddrSpace(Operand, &I, Out);
3808 
3809     // If possible, print out the short form of the call instruction.  We can
3810     // only do this if the first argument is a pointer to a nonvararg function,
3811     // and if the return type is not a pointer to a function.
3812     //
3813     Out << ' ';
3814     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3815     Out << ' ';
3816     writeOperand(Operand, false);
3817     Out << '(';
3818     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3819       if (op > 0)
3820         Out << ", ";
3821       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3822     }
3823 
3824     // Emit an ellipsis if this is a musttail call in a vararg function.  This
3825     // is only to aid readability, musttail calls forward varargs by default.
3826     if (CI->isMustTailCall() && CI->getParent() &&
3827         CI->getParent()->getParent() &&
3828         CI->getParent()->getParent()->isVarArg())
3829       Out << ", ...";
3830 
3831     Out << ')';
3832     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3833       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3834 
3835     writeOperandBundles(CI);
3836   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3837     Operand = II->getCalledValue();
3838     FunctionType *FTy = II->getFunctionType();
3839     Type *RetTy = FTy->getReturnType();
3840     const AttributeList &PAL = II->getAttributes();
3841 
3842     // Print the calling convention being used.
3843     if (II->getCallingConv() != CallingConv::C) {
3844       Out << " ";
3845       PrintCallingConv(II->getCallingConv(), Out);
3846     }
3847 
3848     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3849       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3850 
3851     // Only print addrspace(N) if necessary:
3852     maybePrintCallAddrSpace(Operand, &I, Out);
3853 
3854     // If possible, print out the short form of the invoke instruction. We can
3855     // only do this if the first argument is a pointer to a nonvararg function,
3856     // and if the return type is not a pointer to a function.
3857     //
3858     Out << ' ';
3859     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3860     Out << ' ';
3861     writeOperand(Operand, false);
3862     Out << '(';
3863     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3864       if (op)
3865         Out << ", ";
3866       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3867     }
3868 
3869     Out << ')';
3870     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3871       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3872 
3873     writeOperandBundles(II);
3874 
3875     Out << "\n          to ";
3876     writeOperand(II->getNormalDest(), true);
3877     Out << " unwind ";
3878     writeOperand(II->getUnwindDest(), true);
3879   } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
3880     Operand = CBI->getCalledValue();
3881     FunctionType *FTy = CBI->getFunctionType();
3882     Type *RetTy = FTy->getReturnType();
3883     const AttributeList &PAL = CBI->getAttributes();
3884 
3885     // Print the calling convention being used.
3886     if (CBI->getCallingConv() != CallingConv::C) {
3887       Out << " ";
3888       PrintCallingConv(CBI->getCallingConv(), Out);
3889     }
3890 
3891     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3892       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3893 
3894     // If possible, print out the short form of the callbr instruction. We can
3895     // only do this if the first argument is a pointer to a nonvararg function,
3896     // and if the return type is not a pointer to a function.
3897     //
3898     Out << ' ';
3899     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3900     Out << ' ';
3901     writeOperand(Operand, false);
3902     Out << '(';
3903     for (unsigned op = 0, Eop = CBI->getNumArgOperands(); op < Eop; ++op) {
3904       if (op)
3905         Out << ", ";
3906       writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttributes(op));
3907     }
3908 
3909     Out << ')';
3910     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3911       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3912 
3913     writeOperandBundles(CBI);
3914 
3915     Out << "\n          to ";
3916     writeOperand(CBI->getDefaultDest(), true);
3917     Out << " [";
3918     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
3919       if (i != 0)
3920         Out << ", ";
3921       writeOperand(CBI->getIndirectDest(i), true);
3922     }
3923     Out << ']';
3924   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3925     Out << ' ';
3926     if (AI->isUsedWithInAlloca())
3927       Out << "inalloca ";
3928     if (AI->isSwiftError())
3929       Out << "swifterror ";
3930     TypePrinter.print(AI->getAllocatedType(), Out);
3931 
3932     // Explicitly write the array size if the code is broken, if it's an array
3933     // allocation, or if the type is not canonical for scalar allocations.  The
3934     // latter case prevents the type from mutating when round-tripping through
3935     // assembly.
3936     if (!AI->getArraySize() || AI->isArrayAllocation() ||
3937         !AI->getArraySize()->getType()->isIntegerTy(32)) {
3938       Out << ", ";
3939       writeOperand(AI->getArraySize(), true);
3940     }
3941     if (AI->getAlignment()) {
3942       Out << ", align " << AI->getAlignment();
3943     }
3944 
3945     unsigned AddrSpace = AI->getType()->getAddressSpace();
3946     if (AddrSpace != 0) {
3947       Out << ", addrspace(" << AddrSpace << ')';
3948     }
3949   } else if (isa<CastInst>(I)) {
3950     if (Operand) {
3951       Out << ' ';
3952       writeOperand(Operand, true);   // Work with broken code
3953     }
3954     Out << " to ";
3955     TypePrinter.print(I.getType(), Out);
3956   } else if (isa<VAArgInst>(I)) {
3957     if (Operand) {
3958       Out << ' ';
3959       writeOperand(Operand, true);   // Work with broken code
3960     }
3961     Out << ", ";
3962     TypePrinter.print(I.getType(), Out);
3963   } else if (Operand) {   // Print the normal way.
3964     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3965       Out << ' ';
3966       TypePrinter.print(GEP->getSourceElementType(), Out);
3967       Out << ',';
3968     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3969       Out << ' ';
3970       TypePrinter.print(LI->getType(), Out);
3971       Out << ',';
3972     }
3973 
3974     // PrintAllTypes - Instructions who have operands of all the same type
3975     // omit the type from all but the first operand.  If the instruction has
3976     // different type operands (for example br), then they are all printed.
3977     bool PrintAllTypes = false;
3978     Type *TheType = Operand->getType();
3979 
3980     // Select, Store and ShuffleVector always print all types.
3981     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3982         || isa<ReturnInst>(I)) {
3983       PrintAllTypes = true;
3984     } else {
3985       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3986         Operand = I.getOperand(i);
3987         // note that Operand shouldn't be null, but the test helps make dump()
3988         // more tolerant of malformed IR
3989         if (Operand && Operand->getType() != TheType) {
3990           PrintAllTypes = true;    // We have differing types!  Print them all!
3991           break;
3992         }
3993       }
3994     }
3995 
3996     if (!PrintAllTypes) {
3997       Out << ' ';
3998       TypePrinter.print(TheType, Out);
3999     }
4000 
4001     Out << ' ';
4002     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4003       if (i) Out << ", ";
4004       writeOperand(I.getOperand(i), PrintAllTypes);
4005     }
4006   }
4007 
4008   // Print atomic ordering/alignment for memory operations
4009   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4010     if (LI->isAtomic())
4011       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4012     if (LI->getAlignment())
4013       Out << ", align " << LI->getAlignment();
4014   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4015     if (SI->isAtomic())
4016       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4017     if (SI->getAlignment())
4018       Out << ", align " << SI->getAlignment();
4019   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4020     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4021                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
4022   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4023     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4024                 RMWI->getSyncScopeID());
4025   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4026     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4027   }
4028 
4029   // Print Metadata info.
4030   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4031   I.getAllMetadata(InstMD);
4032   printMetadataAttachments(InstMD, ", ");
4033 
4034   // Print a nice comment.
4035   printInfoComment(I);
4036 }
4037 
4038 void AssemblyWriter::printMetadataAttachments(
4039     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4040     StringRef Separator) {
4041   if (MDs.empty())
4042     return;
4043 
4044   if (MDNames.empty())
4045     MDs[0].second->getContext().getMDKindNames(MDNames);
4046 
4047   for (const auto &I : MDs) {
4048     unsigned Kind = I.first;
4049     Out << Separator;
4050     if (Kind < MDNames.size()) {
4051       Out << "!";
4052       printMetadataIdentifier(MDNames[Kind], Out);
4053     } else
4054       Out << "!<unknown kind #" << Kind << ">";
4055     Out << ' ';
4056     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
4057   }
4058 }
4059 
4060 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4061   Out << '!' << Slot << " = ";
4062   printMDNodeBody(Node);
4063   Out << "\n";
4064 }
4065 
4066 void AssemblyWriter::writeAllMDNodes() {
4067   SmallVector<const MDNode *, 16> Nodes;
4068   Nodes.resize(Machine.mdn_size());
4069   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
4070        I != E; ++I)
4071     Nodes[I->second] = cast<MDNode>(I->first);
4072 
4073   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4074     writeMDNode(i, Nodes[i]);
4075   }
4076 }
4077 
4078 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4079   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
4080 }
4081 
4082 void AssemblyWriter::writeAllAttributeGroups() {
4083   std::vector<std::pair<AttributeSet, unsigned>> asVec;
4084   asVec.resize(Machine.as_size());
4085 
4086   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
4087        I != E; ++I)
4088     asVec[I->second] = *I;
4089 
4090   for (const auto &I : asVec)
4091     Out << "attributes #" << I.second << " = { "
4092         << I.first.getAsString(true) << " }\n";
4093 }
4094 
4095 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4096   bool IsInFunction = Machine.getFunction();
4097   if (IsInFunction)
4098     Out << "  ";
4099 
4100   Out << "uselistorder";
4101   if (const BasicBlock *BB =
4102           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4103     Out << "_bb ";
4104     writeOperand(BB->getParent(), false);
4105     Out << ", ";
4106     writeOperand(BB, false);
4107   } else {
4108     Out << " ";
4109     writeOperand(Order.V, true);
4110   }
4111   Out << ", { ";
4112 
4113   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4114   Out << Order.Shuffle[0];
4115   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4116     Out << ", " << Order.Shuffle[I];
4117   Out << " }\n";
4118 }
4119 
4120 void AssemblyWriter::printUseLists(const Function *F) {
4121   auto hasMore =
4122       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4123   if (!hasMore())
4124     // Nothing to do.
4125     return;
4126 
4127   Out << "\n; uselistorder directives\n";
4128   while (hasMore()) {
4129     printUseListOrder(UseListOrders.back());
4130     UseListOrders.pop_back();
4131   }
4132 }
4133 
4134 //===----------------------------------------------------------------------===//
4135 //                       External Interface declarations
4136 //===----------------------------------------------------------------------===//
4137 
4138 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4139                      bool ShouldPreserveUseListOrder,
4140                      bool IsForDebug) const {
4141   SlotTracker SlotTable(this->getParent());
4142   formatted_raw_ostream OS(ROS);
4143   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4144                    IsForDebug,
4145                    ShouldPreserveUseListOrder);
4146   W.printFunction(this);
4147 }
4148 
4149 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4150                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4151   SlotTracker SlotTable(this);
4152   formatted_raw_ostream OS(ROS);
4153   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4154                    ShouldPreserveUseListOrder);
4155   W.printModule(this);
4156 }
4157 
4158 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4159   SlotTracker SlotTable(getParent());
4160   formatted_raw_ostream OS(ROS);
4161   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4162   W.printNamedMDNode(this);
4163 }
4164 
4165 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4166                         bool IsForDebug) const {
4167   Optional<SlotTracker> LocalST;
4168   SlotTracker *SlotTable;
4169   if (auto *ST = MST.getMachine())
4170     SlotTable = ST;
4171   else {
4172     LocalST.emplace(getParent());
4173     SlotTable = &*LocalST;
4174   }
4175 
4176   formatted_raw_ostream OS(ROS);
4177   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4178   W.printNamedMDNode(this);
4179 }
4180 
4181 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4182   PrintLLVMName(ROS, getName(), ComdatPrefix);
4183   ROS << " = comdat ";
4184 
4185   switch (getSelectionKind()) {
4186   case Comdat::Any:
4187     ROS << "any";
4188     break;
4189   case Comdat::ExactMatch:
4190     ROS << "exactmatch";
4191     break;
4192   case Comdat::Largest:
4193     ROS << "largest";
4194     break;
4195   case Comdat::NoDuplicates:
4196     ROS << "noduplicates";
4197     break;
4198   case Comdat::SameSize:
4199     ROS << "samesize";
4200     break;
4201   }
4202 
4203   ROS << '\n';
4204 }
4205 
4206 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4207   TypePrinting TP;
4208   TP.print(const_cast<Type*>(this), OS);
4209 
4210   if (NoDetails)
4211     return;
4212 
4213   // If the type is a named struct type, print the body as well.
4214   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4215     if (!STy->isLiteral()) {
4216       OS << " = type ";
4217       TP.printStructBody(STy, OS);
4218     }
4219 }
4220 
4221 static bool isReferencingMDNode(const Instruction &I) {
4222   if (const auto *CI = dyn_cast<CallInst>(&I))
4223     if (Function *F = CI->getCalledFunction())
4224       if (F->isIntrinsic())
4225         for (auto &Op : I.operands())
4226           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4227             if (isa<MDNode>(V->getMetadata()))
4228               return true;
4229   return false;
4230 }
4231 
4232 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4233   bool ShouldInitializeAllMetadata = false;
4234   if (auto *I = dyn_cast<Instruction>(this))
4235     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4236   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4237     ShouldInitializeAllMetadata = true;
4238 
4239   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4240   print(ROS, MST, IsForDebug);
4241 }
4242 
4243 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4244                   bool IsForDebug) const {
4245   formatted_raw_ostream OS(ROS);
4246   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4247   SlotTracker &SlotTable =
4248       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4249   auto incorporateFunction = [&](const Function *F) {
4250     if (F)
4251       MST.incorporateFunction(*F);
4252   };
4253 
4254   if (const Instruction *I = dyn_cast<Instruction>(this)) {
4255     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4256     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4257     W.printInstruction(*I);
4258   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4259     incorporateFunction(BB->getParent());
4260     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4261     W.printBasicBlock(BB);
4262   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4263     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4264     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4265       W.printGlobal(V);
4266     else if (const Function *F = dyn_cast<Function>(GV))
4267       W.printFunction(F);
4268     else
4269       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4270   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4271     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4272   } else if (const Constant *C = dyn_cast<Constant>(this)) {
4273     TypePrinting TypePrinter;
4274     TypePrinter.print(C->getType(), OS);
4275     OS << ' ';
4276     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4277   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4278     this->printAsOperand(OS, /* PrintType */ true, MST);
4279   } else {
4280     llvm_unreachable("Unknown value to print out!");
4281   }
4282 }
4283 
4284 /// Print without a type, skipping the TypePrinting object.
4285 ///
4286 /// \return \c true iff printing was successful.
4287 static bool printWithoutType(const Value &V, raw_ostream &O,
4288                              SlotTracker *Machine, const Module *M) {
4289   if (V.hasName() || isa<GlobalValue>(V) ||
4290       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4291     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4292     return true;
4293   }
4294   return false;
4295 }
4296 
4297 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4298                                ModuleSlotTracker &MST) {
4299   TypePrinting TypePrinter(MST.getModule());
4300   if (PrintType) {
4301     TypePrinter.print(V.getType(), O);
4302     O << ' ';
4303   }
4304 
4305   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4306                          MST.getModule());
4307 }
4308 
4309 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4310                            const Module *M) const {
4311   if (!M)
4312     M = getModuleFromVal(this);
4313 
4314   if (!PrintType)
4315     if (printWithoutType(*this, O, nullptr, M))
4316       return;
4317 
4318   SlotTracker Machine(
4319       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4320   ModuleSlotTracker MST(Machine, M);
4321   printAsOperandImpl(*this, O, PrintType, MST);
4322 }
4323 
4324 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4325                            ModuleSlotTracker &MST) const {
4326   if (!PrintType)
4327     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4328       return;
4329 
4330   printAsOperandImpl(*this, O, PrintType, MST);
4331 }
4332 
4333 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4334                               ModuleSlotTracker &MST, const Module *M,
4335                               bool OnlyAsOperand) {
4336   formatted_raw_ostream OS(ROS);
4337 
4338   TypePrinting TypePrinter(M);
4339 
4340   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4341                          /* FromValue */ true);
4342 
4343   auto *N = dyn_cast<MDNode>(&MD);
4344   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4345     return;
4346 
4347   OS << " = ";
4348   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4349 }
4350 
4351 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4352   ModuleSlotTracker MST(M, isa<MDNode>(this));
4353   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4354 }
4355 
4356 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4357                               const Module *M) const {
4358   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4359 }
4360 
4361 void Metadata::print(raw_ostream &OS, const Module *M,
4362                      bool /*IsForDebug*/) const {
4363   ModuleSlotTracker MST(M, isa<MDNode>(this));
4364   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4365 }
4366 
4367 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4368                      const Module *M, bool /*IsForDebug*/) const {
4369   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4370 }
4371 
4372 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4373   SlotTracker SlotTable(this);
4374   formatted_raw_ostream OS(ROS);
4375   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4376   W.printModuleSummaryIndex();
4377 }
4378 
4379 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4380 // Value::dump - allow easy printing of Values from the debugger.
4381 LLVM_DUMP_METHOD
4382 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4383 
4384 // Type::dump - allow easy printing of Types from the debugger.
4385 LLVM_DUMP_METHOD
4386 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4387 
4388 // Module::dump() - Allow printing of Modules from the debugger.
4389 LLVM_DUMP_METHOD
4390 void Module::dump() const {
4391   print(dbgs(), nullptr,
4392         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4393 }
4394 
4395 // Allow printing of Comdats from the debugger.
4396 LLVM_DUMP_METHOD
4397 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4398 
4399 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4400 LLVM_DUMP_METHOD
4401 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4402 
4403 LLVM_DUMP_METHOD
4404 void Metadata::dump() const { dump(nullptr); }
4405 
4406 LLVM_DUMP_METHOD
4407 void Metadata::dump(const Module *M) const {
4408   print(dbgs(), M, /*IsForDebug=*/true);
4409   dbgs() << '\n';
4410 }
4411 
4412 // Allow printing of ModuleSummaryIndex from the debugger.
4413 LLVM_DUMP_METHOD
4414 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4415 #endif
4416