1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/IR/Writer.h
11 //
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include "llvm/BinaryFormat/Dwarf.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/AssemblyAnnotationWriter.h"
33 #include "llvm/IR/Attributes.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/CFG.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Comdat.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DebugInfoMetadata.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalAlias.h"
45 #include "llvm/IR/GlobalIFunc.h"
46 #include "llvm/IR/GlobalIndirectSymbol.h"
47 #include "llvm/IR/GlobalObject.h"
48 #include "llvm/IR/GlobalValue.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/IRPrintingPasses.h"
51 #include "llvm/IR/InlineAsm.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/LLVMContext.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/ModuleSlotTracker.h"
59 #include "llvm/IR/Operator.h"
60 #include "llvm/IR/Statepoint.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/TypeFinder.h"
63 #include "llvm/IR/Use.h"
64 #include "llvm/IR/UseListOrder.h"
65 #include "llvm/IR/User.h"
66 #include "llvm/IR/Value.h"
67 #include "llvm/Support/AtomicOrdering.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/Format.h"
73 #include "llvm/Support/FormattedStream.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cctype>
78 #include <cstddef>
79 #include <cstdint>
80 #include <iterator>
81 #include <memory>
82 #include <string>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 // Make virtual table appear in this compilation unit.
90 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
91 
92 //===----------------------------------------------------------------------===//
93 // Helper Functions
94 //===----------------------------------------------------------------------===//
95 
96 namespace {
97 
98 struct OrderMap {
99   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
100 
101   unsigned size() const { return IDs.size(); }
102   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
103 
104   std::pair<unsigned, bool> lookup(const Value *V) const {
105     return IDs.lookup(V);
106   }
107 
108   void index(const Value *V) {
109     // Explicitly sequence get-size and insert-value operations to avoid UB.
110     unsigned ID = IDs.size() + 1;
111     IDs[V].first = ID;
112   }
113 };
114 
115 } // end anonymous namespace
116 
117 static void orderValue(const Value *V, OrderMap &OM) {
118   if (OM.lookup(V).first)
119     return;
120 
121   if (const Constant *C = dyn_cast<Constant>(V))
122     if (C->getNumOperands() && !isa<GlobalValue>(C))
123       for (const Value *Op : C->operands())
124         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
125           orderValue(Op, OM);
126 
127   // Note: we cannot cache this lookup above, since inserting into the map
128   // changes the map's size, and thus affects the other IDs.
129   OM.index(V);
130 }
131 
132 static OrderMap orderModule(const Module *M) {
133   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
134   // and ValueEnumerator::incorporateFunction().
135   OrderMap OM;
136 
137   for (const GlobalVariable &G : M->globals()) {
138     if (G.hasInitializer())
139       if (!isa<GlobalValue>(G.getInitializer()))
140         orderValue(G.getInitializer(), OM);
141     orderValue(&G, OM);
142   }
143   for (const GlobalAlias &A : M->aliases()) {
144     if (!isa<GlobalValue>(A.getAliasee()))
145       orderValue(A.getAliasee(), OM);
146     orderValue(&A, OM);
147   }
148   for (const GlobalIFunc &I : M->ifuncs()) {
149     if (!isa<GlobalValue>(I.getResolver()))
150       orderValue(I.getResolver(), OM);
151     orderValue(&I, OM);
152   }
153   for (const Function &F : *M) {
154     for (const Use &U : F.operands())
155       if (!isa<GlobalValue>(U.get()))
156         orderValue(U.get(), OM);
157 
158     orderValue(&F, OM);
159 
160     if (F.isDeclaration())
161       continue;
162 
163     for (const Argument &A : F.args())
164       orderValue(&A, OM);
165     for (const BasicBlock &BB : F) {
166       orderValue(&BB, OM);
167       for (const Instruction &I : BB) {
168         for (const Value *Op : I.operands())
169           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
170               isa<InlineAsm>(*Op))
171             orderValue(Op, OM);
172         orderValue(&I, OM);
173       }
174     }
175   }
176   return OM;
177 }
178 
179 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
180                                          unsigned ID, const OrderMap &OM,
181                                          UseListOrderStack &Stack) {
182   // Predict use-list order for this one.
183   using Entry = std::pair<const Use *, unsigned>;
184   SmallVector<Entry, 64> List;
185   for (const Use &U : V->uses())
186     // Check if this user will be serialized.
187     if (OM.lookup(U.getUser()).first)
188       List.push_back(std::make_pair(&U, List.size()));
189 
190   if (List.size() < 2)
191     // We may have lost some users.
192     return;
193 
194   bool GetsReversed =
195       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
196   if (auto *BA = dyn_cast<BlockAddress>(V))
197     ID = OM.lookup(BA->getBasicBlock()).first;
198   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
199     const Use *LU = L.first;
200     const Use *RU = R.first;
201     if (LU == RU)
202       return false;
203 
204     auto LID = OM.lookup(LU->getUser()).first;
205     auto RID = OM.lookup(RU->getUser()).first;
206 
207     // If ID is 4, then expect: 7 6 5 1 2 3.
208     if (LID < RID) {
209       if (GetsReversed)
210         if (RID <= ID)
211           return true;
212       return false;
213     }
214     if (RID < LID) {
215       if (GetsReversed)
216         if (LID <= ID)
217           return false;
218       return true;
219     }
220 
221     // LID and RID are equal, so we have different operands of the same user.
222     // Assume operands are added in order for all instructions.
223     if (GetsReversed)
224       if (LID <= ID)
225         return LU->getOperandNo() < RU->getOperandNo();
226     return LU->getOperandNo() > RU->getOperandNo();
227   });
228 
229   if (std::is_sorted(
230           List.begin(), List.end(),
231           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
232     // Order is already correct.
233     return;
234 
235   // Store the shuffle.
236   Stack.emplace_back(V, F, List.size());
237   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
238   for (size_t I = 0, E = List.size(); I != E; ++I)
239     Stack.back().Shuffle[I] = List[I].second;
240 }
241 
242 static void predictValueUseListOrder(const Value *V, const Function *F,
243                                      OrderMap &OM, UseListOrderStack &Stack) {
244   auto &IDPair = OM[V];
245   assert(IDPair.first && "Unmapped value");
246   if (IDPair.second)
247     // Already predicted.
248     return;
249 
250   // Do the actual prediction.
251   IDPair.second = true;
252   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
253     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
254 
255   // Recursive descent into constants.
256   if (const Constant *C = dyn_cast<Constant>(V))
257     if (C->getNumOperands()) // Visit GlobalValues.
258       for (const Value *Op : C->operands())
259         if (isa<Constant>(Op)) // Visit GlobalValues.
260           predictValueUseListOrder(Op, F, OM, Stack);
261 }
262 
263 static UseListOrderStack predictUseListOrder(const Module *M) {
264   OrderMap OM = orderModule(M);
265 
266   // Use-list orders need to be serialized after all the users have been added
267   // to a value, or else the shuffles will be incomplete.  Store them per
268   // function in a stack.
269   //
270   // Aside from function order, the order of values doesn't matter much here.
271   UseListOrderStack Stack;
272 
273   // We want to visit the functions backward now so we can list function-local
274   // constants in the last Function they're used in.  Module-level constants
275   // have already been visited above.
276   for (const Function &F : make_range(M->rbegin(), M->rend())) {
277     if (F.isDeclaration())
278       continue;
279     for (const BasicBlock &BB : F)
280       predictValueUseListOrder(&BB, &F, OM, Stack);
281     for (const Argument &A : F.args())
282       predictValueUseListOrder(&A, &F, OM, Stack);
283     for (const BasicBlock &BB : F)
284       for (const Instruction &I : BB)
285         for (const Value *Op : I.operands())
286           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
287             predictValueUseListOrder(Op, &F, OM, Stack);
288     for (const BasicBlock &BB : F)
289       for (const Instruction &I : BB)
290         predictValueUseListOrder(&I, &F, OM, Stack);
291   }
292 
293   // Visit globals last.
294   for (const GlobalVariable &G : M->globals())
295     predictValueUseListOrder(&G, nullptr, OM, Stack);
296   for (const Function &F : *M)
297     predictValueUseListOrder(&F, nullptr, OM, Stack);
298   for (const GlobalAlias &A : M->aliases())
299     predictValueUseListOrder(&A, nullptr, OM, Stack);
300   for (const GlobalIFunc &I : M->ifuncs())
301     predictValueUseListOrder(&I, nullptr, OM, Stack);
302   for (const GlobalVariable &G : M->globals())
303     if (G.hasInitializer())
304       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
305   for (const GlobalAlias &A : M->aliases())
306     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
307   for (const GlobalIFunc &I : M->ifuncs())
308     predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
309   for (const Function &F : *M)
310     for (const Use &U : F.operands())
311       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
312 
313   return Stack;
314 }
315 
316 static const Module *getModuleFromVal(const Value *V) {
317   if (const Argument *MA = dyn_cast<Argument>(V))
318     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
319 
320   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
321     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
322 
323   if (const Instruction *I = dyn_cast<Instruction>(V)) {
324     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
325     return M ? M->getParent() : nullptr;
326   }
327 
328   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
329     return GV->getParent();
330 
331   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
332     for (const User *U : MAV->users())
333       if (isa<Instruction>(U))
334         if (const Module *M = getModuleFromVal(U))
335           return M;
336     return nullptr;
337   }
338 
339   return nullptr;
340 }
341 
342 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
343   switch (cc) {
344   default:                         Out << "cc" << cc; break;
345   case CallingConv::Fast:          Out << "fastcc"; break;
346   case CallingConv::Cold:          Out << "coldcc"; break;
347   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
348   case CallingConv::AnyReg:        Out << "anyregcc"; break;
349   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
350   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
351   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
352   case CallingConv::GHC:           Out << "ghccc"; break;
353   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
354   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
355   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
356   case CallingConv::X86_RegCall:   Out << "x86_regcallcc"; break;
357   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
358   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
359   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
360   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
361   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
362   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
363   case CallingConv::AVR_INTR:      Out << "avr_intrcc "; break;
364   case CallingConv::AVR_SIGNAL:    Out << "avr_signalcc "; break;
365   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
366   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
367   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
368   case CallingConv::Win64:         Out << "win64cc"; break;
369   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
370   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
371   case CallingConv::Swift:         Out << "swiftcc"; break;
372   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
373   case CallingConv::HHVM:          Out << "hhvmcc"; break;
374   case CallingConv::HHVM_C:        Out << "hhvm_ccc"; break;
375   case CallingConv::AMDGPU_VS:     Out << "amdgpu_vs"; break;
376   case CallingConv::AMDGPU_LS:     Out << "amdgpu_ls"; break;
377   case CallingConv::AMDGPU_HS:     Out << "amdgpu_hs"; break;
378   case CallingConv::AMDGPU_ES:     Out << "amdgpu_es"; break;
379   case CallingConv::AMDGPU_GS:     Out << "amdgpu_gs"; break;
380   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
381   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
382   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
383   }
384 }
385 
386 void llvm::PrintEscapedString(StringRef Name, raw_ostream &Out) {
387   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
388     unsigned char C = Name[i];
389     if (isprint(C) && C != '\\' && C != '"')
390       Out << C;
391     else
392       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
393   }
394 }
395 
396 enum PrefixType {
397   GlobalPrefix,
398   ComdatPrefix,
399   LabelPrefix,
400   LocalPrefix,
401   NoPrefix
402 };
403 
404 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
405   assert(!Name.empty() && "Cannot get empty name!");
406 
407   // Scan the name to see if it needs quotes first.
408   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
409   if (!NeedsQuotes) {
410     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
411       // By making this unsigned, the value passed in to isalnum will always be
412       // in the range 0-255.  This is important when building with MSVC because
413       // its implementation will assert.  This situation can arise when dealing
414       // with UTF-8 multibyte characters.
415       unsigned char C = Name[i];
416       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
417           C != '_') {
418         NeedsQuotes = true;
419         break;
420       }
421     }
422   }
423 
424   // If we didn't need any quotes, just write out the name in one blast.
425   if (!NeedsQuotes) {
426     OS << Name;
427     return;
428   }
429 
430   // Okay, we need quotes.  Output the quotes and escape any scary characters as
431   // needed.
432   OS << '"';
433   PrintEscapedString(Name, OS);
434   OS << '"';
435 }
436 
437 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
438 /// (if the string only contains simple characters) or is surrounded with ""'s
439 /// (if it has special chars in it). Print it out.
440 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
441   switch (Prefix) {
442   case NoPrefix:
443     break;
444   case GlobalPrefix:
445     OS << '@';
446     break;
447   case ComdatPrefix:
448     OS << '$';
449     break;
450   case LabelPrefix:
451     break;
452   case LocalPrefix:
453     OS << '%';
454     break;
455   }
456   printLLVMNameWithoutPrefix(OS, Name);
457 }
458 
459 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
460 /// (if the string only contains simple characters) or is surrounded with ""'s
461 /// (if it has special chars in it). Print it out.
462 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
463   PrintLLVMName(OS, V->getName(),
464                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
465 }
466 
467 namespace {
468 
469 class TypePrinting {
470 public:
471   /// NamedTypes - The named types that are used by the current module.
472   TypeFinder NamedTypes;
473 
474   /// NumberedTypes - The numbered types, along with their value.
475   DenseMap<StructType*, unsigned> NumberedTypes;
476 
477   TypePrinting() = default;
478   TypePrinting(const TypePrinting &) = delete;
479   TypePrinting &operator=(const TypePrinting &) = delete;
480 
481   void incorporateTypes(const Module &M);
482 
483   void print(Type *Ty, raw_ostream &OS);
484 
485   void printStructBody(StructType *Ty, raw_ostream &OS);
486 };
487 
488 } // end anonymous namespace
489 
490 void TypePrinting::incorporateTypes(const Module &M) {
491   NamedTypes.run(M, false);
492 
493   // The list of struct types we got back includes all the struct types, split
494   // the unnamed ones out to a numbering and remove the anonymous structs.
495   unsigned NextNumber = 0;
496 
497   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
498   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
499     StructType *STy = *I;
500 
501     // Ignore anonymous types.
502     if (STy->isLiteral())
503       continue;
504 
505     if (STy->getName().empty())
506       NumberedTypes[STy] = NextNumber++;
507     else
508       *NextToUse++ = STy;
509   }
510 
511   NamedTypes.erase(NextToUse, NamedTypes.end());
512 }
513 
514 
515 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
516 /// use of type names or up references to shorten the type name where possible.
517 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
518   switch (Ty->getTypeID()) {
519   case Type::VoidTyID:      OS << "void"; return;
520   case Type::HalfTyID:      OS << "half"; return;
521   case Type::FloatTyID:     OS << "float"; return;
522   case Type::DoubleTyID:    OS << "double"; return;
523   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
524   case Type::FP128TyID:     OS << "fp128"; return;
525   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
526   case Type::LabelTyID:     OS << "label"; return;
527   case Type::MetadataTyID:  OS << "metadata"; return;
528   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
529   case Type::TokenTyID:     OS << "token"; return;
530   case Type::IntegerTyID:
531     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
532     return;
533 
534   case Type::FunctionTyID: {
535     FunctionType *FTy = cast<FunctionType>(Ty);
536     print(FTy->getReturnType(), OS);
537     OS << " (";
538     for (FunctionType::param_iterator I = FTy->param_begin(),
539          E = FTy->param_end(); I != E; ++I) {
540       if (I != FTy->param_begin())
541         OS << ", ";
542       print(*I, OS);
543     }
544     if (FTy->isVarArg()) {
545       if (FTy->getNumParams()) OS << ", ";
546       OS << "...";
547     }
548     OS << ')';
549     return;
550   }
551   case Type::StructTyID: {
552     StructType *STy = cast<StructType>(Ty);
553 
554     if (STy->isLiteral())
555       return printStructBody(STy, OS);
556 
557     if (!STy->getName().empty())
558       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
559 
560     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
561     if (I != NumberedTypes.end())
562       OS << '%' << I->second;
563     else  // Not enumerated, print the hex address.
564       OS << "%\"type " << STy << '\"';
565     return;
566   }
567   case Type::PointerTyID: {
568     PointerType *PTy = cast<PointerType>(Ty);
569     print(PTy->getElementType(), OS);
570     if (unsigned AddressSpace = PTy->getAddressSpace())
571       OS << " addrspace(" << AddressSpace << ')';
572     OS << '*';
573     return;
574   }
575   case Type::ArrayTyID: {
576     ArrayType *ATy = cast<ArrayType>(Ty);
577     OS << '[' << ATy->getNumElements() << " x ";
578     print(ATy->getElementType(), OS);
579     OS << ']';
580     return;
581   }
582   case Type::VectorTyID: {
583     VectorType *PTy = cast<VectorType>(Ty);
584     OS << "<" << PTy->getNumElements() << " x ";
585     print(PTy->getElementType(), OS);
586     OS << '>';
587     return;
588   }
589   }
590   llvm_unreachable("Invalid TypeID");
591 }
592 
593 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
594   if (STy->isOpaque()) {
595     OS << "opaque";
596     return;
597   }
598 
599   if (STy->isPacked())
600     OS << '<';
601 
602   if (STy->getNumElements() == 0) {
603     OS << "{}";
604   } else {
605     StructType::element_iterator I = STy->element_begin();
606     OS << "{ ";
607     print(*I++, OS);
608     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
609       OS << ", ";
610       print(*I, OS);
611     }
612 
613     OS << " }";
614   }
615   if (STy->isPacked())
616     OS << '>';
617 }
618 
619 namespace llvm {
620 
621 //===----------------------------------------------------------------------===//
622 // SlotTracker Class: Enumerate slot numbers for unnamed values
623 //===----------------------------------------------------------------------===//
624 /// This class provides computation of slot numbers for LLVM Assembly writing.
625 ///
626 class SlotTracker {
627 public:
628   /// ValueMap - A mapping of Values to slot numbers.
629   using ValueMap = DenseMap<const Value *, unsigned>;
630 
631 private:
632   /// TheModule - The module for which we are holding slot numbers.
633   const Module* TheModule;
634 
635   /// TheFunction - The function for which we are holding slot numbers.
636   const Function* TheFunction = nullptr;
637   bool FunctionProcessed = false;
638   bool ShouldInitializeAllMetadata;
639 
640   /// mMap - The slot map for the module level data.
641   ValueMap mMap;
642   unsigned mNext = 0;
643 
644   /// fMap - The slot map for the function level data.
645   ValueMap fMap;
646   unsigned fNext = 0;
647 
648   /// mdnMap - Map for MDNodes.
649   DenseMap<const MDNode*, unsigned> mdnMap;
650   unsigned mdnNext = 0;
651 
652   /// asMap - The slot map for attribute sets.
653   DenseMap<AttributeSet, unsigned> asMap;
654   unsigned asNext = 0;
655 
656 public:
657   /// Construct from a module.
658   ///
659   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
660   /// functions, giving correct numbering for metadata referenced only from
661   /// within a function (even if no functions have been initialized).
662   explicit SlotTracker(const Module *M,
663                        bool ShouldInitializeAllMetadata = false);
664 
665   /// Construct from a function, starting out in incorp state.
666   ///
667   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
668   /// functions, giving correct numbering for metadata referenced only from
669   /// within a function (even if no functions have been initialized).
670   explicit SlotTracker(const Function *F,
671                        bool ShouldInitializeAllMetadata = false);
672 
673   SlotTracker(const SlotTracker &) = delete;
674   SlotTracker &operator=(const SlotTracker &) = delete;
675 
676   /// Return the slot number of the specified value in it's type
677   /// plane.  If something is not in the SlotTracker, return -1.
678   int getLocalSlot(const Value *V);
679   int getGlobalSlot(const GlobalValue *V);
680   int getMetadataSlot(const MDNode *N);
681   int getAttributeGroupSlot(AttributeSet AS);
682 
683   /// If you'd like to deal with a function instead of just a module, use
684   /// this method to get its data into the SlotTracker.
685   void incorporateFunction(const Function *F) {
686     TheFunction = F;
687     FunctionProcessed = false;
688   }
689 
690   const Function *getFunction() const { return TheFunction; }
691 
692   /// After calling incorporateFunction, use this method to remove the
693   /// most recently incorporated function from the SlotTracker. This
694   /// will reset the state of the machine back to just the module contents.
695   void purgeFunction();
696 
697   /// MDNode map iterators.
698   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
699 
700   mdn_iterator mdn_begin() { return mdnMap.begin(); }
701   mdn_iterator mdn_end() { return mdnMap.end(); }
702   unsigned mdn_size() const { return mdnMap.size(); }
703   bool mdn_empty() const { return mdnMap.empty(); }
704 
705   /// AttributeSet map iterators.
706   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
707 
708   as_iterator as_begin()   { return asMap.begin(); }
709   as_iterator as_end()     { return asMap.end(); }
710   unsigned as_size() const { return asMap.size(); }
711   bool as_empty() const    { return asMap.empty(); }
712 
713   /// This function does the actual initialization.
714   inline void initialize();
715 
716   // Implementation Details
717 private:
718   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
719   void CreateModuleSlot(const GlobalValue *V);
720 
721   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
722   void CreateMetadataSlot(const MDNode *N);
723 
724   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
725   void CreateFunctionSlot(const Value *V);
726 
727   /// \brief Insert the specified AttributeSet into the slot table.
728   void CreateAttributeSetSlot(AttributeSet AS);
729 
730   /// Add all of the module level global variables (and their initializers)
731   /// and function declarations, but not the contents of those functions.
732   void processModule();
733 
734   /// Add all of the functions arguments, basic blocks, and instructions.
735   void processFunction();
736 
737   /// Add the metadata directly attached to a GlobalObject.
738   void processGlobalObjectMetadata(const GlobalObject &GO);
739 
740   /// Add all of the metadata from a function.
741   void processFunctionMetadata(const Function &F);
742 
743   /// Add all of the metadata from an instruction.
744   void processInstructionMetadata(const Instruction &I);
745 };
746 
747 } // end namespace llvm
748 
749 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
750                                      const Function *F)
751     : M(M), F(F), Machine(&Machine) {}
752 
753 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
754                                      bool ShouldInitializeAllMetadata)
755     : ShouldCreateStorage(M),
756       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
757 
758 ModuleSlotTracker::~ModuleSlotTracker() = default;
759 
760 SlotTracker *ModuleSlotTracker::getMachine() {
761   if (!ShouldCreateStorage)
762     return Machine;
763 
764   ShouldCreateStorage = false;
765   MachineStorage =
766       llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
767   Machine = MachineStorage.get();
768   return Machine;
769 }
770 
771 void ModuleSlotTracker::incorporateFunction(const Function &F) {
772   // Using getMachine() may lazily create the slot tracker.
773   if (!getMachine())
774     return;
775 
776   // Nothing to do if this is the right function already.
777   if (this->F == &F)
778     return;
779   if (this->F)
780     Machine->purgeFunction();
781   Machine->incorporateFunction(&F);
782   this->F = &F;
783 }
784 
785 int ModuleSlotTracker::getLocalSlot(const Value *V) {
786   assert(F && "No function incorporated");
787   return Machine->getLocalSlot(V);
788 }
789 
790 static SlotTracker *createSlotTracker(const Value *V) {
791   if (const Argument *FA = dyn_cast<Argument>(V))
792     return new SlotTracker(FA->getParent());
793 
794   if (const Instruction *I = dyn_cast<Instruction>(V))
795     if (I->getParent())
796       return new SlotTracker(I->getParent()->getParent());
797 
798   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
799     return new SlotTracker(BB->getParent());
800 
801   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
802     return new SlotTracker(GV->getParent());
803 
804   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
805     return new SlotTracker(GA->getParent());
806 
807   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
808     return new SlotTracker(GIF->getParent());
809 
810   if (const Function *Func = dyn_cast<Function>(V))
811     return new SlotTracker(Func);
812 
813   return nullptr;
814 }
815 
816 #if 0
817 #define ST_DEBUG(X) dbgs() << X
818 #else
819 #define ST_DEBUG(X)
820 #endif
821 
822 // Module level constructor. Causes the contents of the Module (sans functions)
823 // to be added to the slot table.
824 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
825     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
826 
827 // Function level constructor. Causes the contents of the Module and the one
828 // function provided to be added to the slot table.
829 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
830     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
831       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
832 
833 inline void SlotTracker::initialize() {
834   if (TheModule) {
835     processModule();
836     TheModule = nullptr; ///< Prevent re-processing next time we're called.
837   }
838 
839   if (TheFunction && !FunctionProcessed)
840     processFunction();
841 }
842 
843 // Iterate through all the global variables, functions, and global
844 // variable initializers and create slots for them.
845 void SlotTracker::processModule() {
846   ST_DEBUG("begin processModule!\n");
847 
848   // Add all of the unnamed global variables to the value table.
849   for (const GlobalVariable &Var : TheModule->globals()) {
850     if (!Var.hasName())
851       CreateModuleSlot(&Var);
852     processGlobalObjectMetadata(Var);
853     auto Attrs = Var.getAttributes();
854     if (Attrs.hasAttributes())
855       CreateAttributeSetSlot(Attrs);
856   }
857 
858   for (const GlobalAlias &A : TheModule->aliases()) {
859     if (!A.hasName())
860       CreateModuleSlot(&A);
861   }
862 
863   for (const GlobalIFunc &I : TheModule->ifuncs()) {
864     if (!I.hasName())
865       CreateModuleSlot(&I);
866   }
867 
868   // Add metadata used by named metadata.
869   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
870     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
871       CreateMetadataSlot(NMD.getOperand(i));
872   }
873 
874   for (const Function &F : *TheModule) {
875     if (!F.hasName())
876       // Add all the unnamed functions to the table.
877       CreateModuleSlot(&F);
878 
879     if (ShouldInitializeAllMetadata)
880       processFunctionMetadata(F);
881 
882     // Add all the function attributes to the table.
883     // FIXME: Add attributes of other objects?
884     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
885     if (FnAttrs.hasAttributes())
886       CreateAttributeSetSlot(FnAttrs);
887   }
888 
889   ST_DEBUG("end processModule!\n");
890 }
891 
892 // Process the arguments, basic blocks, and instructions  of a function.
893 void SlotTracker::processFunction() {
894   ST_DEBUG("begin processFunction!\n");
895   fNext = 0;
896 
897   // Process function metadata if it wasn't hit at the module-level.
898   if (!ShouldInitializeAllMetadata)
899     processFunctionMetadata(*TheFunction);
900 
901   // Add all the function arguments with no names.
902   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
903       AE = TheFunction->arg_end(); AI != AE; ++AI)
904     if (!AI->hasName())
905       CreateFunctionSlot(&*AI);
906 
907   ST_DEBUG("Inserting Instructions:\n");
908 
909   // Add all of the basic blocks and instructions with no names.
910   for (auto &BB : *TheFunction) {
911     if (!BB.hasName())
912       CreateFunctionSlot(&BB);
913 
914     for (auto &I : BB) {
915       if (!I.getType()->isVoidTy() && !I.hasName())
916         CreateFunctionSlot(&I);
917 
918       // We allow direct calls to any llvm.foo function here, because the
919       // target may not be linked into the optimizer.
920       if (auto CS = ImmutableCallSite(&I)) {
921         // Add all the call attributes to the table.
922         AttributeSet Attrs = CS.getAttributes().getFnAttributes();
923         if (Attrs.hasAttributes())
924           CreateAttributeSetSlot(Attrs);
925       }
926     }
927   }
928 
929   FunctionProcessed = true;
930 
931   ST_DEBUG("end processFunction!\n");
932 }
933 
934 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
935   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
936   GO.getAllMetadata(MDs);
937   for (auto &MD : MDs)
938     CreateMetadataSlot(MD.second);
939 }
940 
941 void SlotTracker::processFunctionMetadata(const Function &F) {
942   processGlobalObjectMetadata(F);
943   for (auto &BB : F) {
944     for (auto &I : BB)
945       processInstructionMetadata(I);
946   }
947 }
948 
949 void SlotTracker::processInstructionMetadata(const Instruction &I) {
950   // Process metadata used directly by intrinsics.
951   if (const CallInst *CI = dyn_cast<CallInst>(&I))
952     if (Function *F = CI->getCalledFunction())
953       if (F->isIntrinsic())
954         for (auto &Op : I.operands())
955           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
956             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
957               CreateMetadataSlot(N);
958 
959   // Process metadata attached to this instruction.
960   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
961   I.getAllMetadata(MDs);
962   for (auto &MD : MDs)
963     CreateMetadataSlot(MD.second);
964 }
965 
966 /// Clean up after incorporating a function. This is the only way to get out of
967 /// the function incorporation state that affects get*Slot/Create*Slot. Function
968 /// incorporation state is indicated by TheFunction != 0.
969 void SlotTracker::purgeFunction() {
970   ST_DEBUG("begin purgeFunction!\n");
971   fMap.clear(); // Simply discard the function level map
972   TheFunction = nullptr;
973   FunctionProcessed = false;
974   ST_DEBUG("end purgeFunction!\n");
975 }
976 
977 /// getGlobalSlot - Get the slot number of a global value.
978 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
979   // Check for uninitialized state and do lazy initialization.
980   initialize();
981 
982   // Find the value in the module map
983   ValueMap::iterator MI = mMap.find(V);
984   return MI == mMap.end() ? -1 : (int)MI->second;
985 }
986 
987 /// getMetadataSlot - Get the slot number of a MDNode.
988 int SlotTracker::getMetadataSlot(const MDNode *N) {
989   // Check for uninitialized state and do lazy initialization.
990   initialize();
991 
992   // Find the MDNode in the module map
993   mdn_iterator MI = mdnMap.find(N);
994   return MI == mdnMap.end() ? -1 : (int)MI->second;
995 }
996 
997 /// getLocalSlot - Get the slot number for a value that is local to a function.
998 int SlotTracker::getLocalSlot(const Value *V) {
999   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1000 
1001   // Check for uninitialized state and do lazy initialization.
1002   initialize();
1003 
1004   ValueMap::iterator FI = fMap.find(V);
1005   return FI == fMap.end() ? -1 : (int)FI->second;
1006 }
1007 
1008 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1009   // Check for uninitialized state and do lazy initialization.
1010   initialize();
1011 
1012   // Find the AttributeSet in the module map.
1013   as_iterator AI = asMap.find(AS);
1014   return AI == asMap.end() ? -1 : (int)AI->second;
1015 }
1016 
1017 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1018 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1019   assert(V && "Can't insert a null Value into SlotTracker!");
1020   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1021   assert(!V->hasName() && "Doesn't need a slot!");
1022 
1023   unsigned DestSlot = mNext++;
1024   mMap[V] = DestSlot;
1025 
1026   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1027            DestSlot << " [");
1028   // G = Global, F = Function, A = Alias, I = IFunc, o = other
1029   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1030             (isa<Function>(V) ? 'F' :
1031              (isa<GlobalAlias>(V) ? 'A' :
1032               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1033 }
1034 
1035 /// CreateSlot - Create a new slot for the specified value if it has no name.
1036 void SlotTracker::CreateFunctionSlot(const Value *V) {
1037   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1038 
1039   unsigned DestSlot = fNext++;
1040   fMap[V] = DestSlot;
1041 
1042   // G = Global, F = Function, o = other
1043   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1044            DestSlot << " [o]\n");
1045 }
1046 
1047 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1048 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1049   assert(N && "Can't insert a null Value into SlotTracker!");
1050 
1051   // Don't make slots for DIExpressions. We just print them inline everywhere.
1052   if (isa<DIExpression>(N))
1053     return;
1054 
1055   unsigned DestSlot = mdnNext;
1056   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1057     return;
1058   ++mdnNext;
1059 
1060   // Recursively add any MDNodes referenced by operands.
1061   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1062     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1063       CreateMetadataSlot(Op);
1064 }
1065 
1066 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1067   assert(AS.hasAttributes() && "Doesn't need a slot!");
1068 
1069   as_iterator I = asMap.find(AS);
1070   if (I != asMap.end())
1071     return;
1072 
1073   unsigned DestSlot = asNext++;
1074   asMap[AS] = DestSlot;
1075 }
1076 
1077 //===----------------------------------------------------------------------===//
1078 // AsmWriter Implementation
1079 //===----------------------------------------------------------------------===//
1080 
1081 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1082                                    TypePrinting *TypePrinter,
1083                                    SlotTracker *Machine,
1084                                    const Module *Context);
1085 
1086 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1087                                    TypePrinting *TypePrinter,
1088                                    SlotTracker *Machine, const Module *Context,
1089                                    bool FromValue = false);
1090 
1091 static void writeAtomicRMWOperation(raw_ostream &Out,
1092                                     AtomicRMWInst::BinOp Op) {
1093   switch (Op) {
1094   default: Out << " <unknown operation " << Op << ">"; break;
1095   case AtomicRMWInst::Xchg: Out << " xchg"; break;
1096   case AtomicRMWInst::Add:  Out << " add"; break;
1097   case AtomicRMWInst::Sub:  Out << " sub"; break;
1098   case AtomicRMWInst::And:  Out << " and"; break;
1099   case AtomicRMWInst::Nand: Out << " nand"; break;
1100   case AtomicRMWInst::Or:   Out << " or"; break;
1101   case AtomicRMWInst::Xor:  Out << " xor"; break;
1102   case AtomicRMWInst::Max:  Out << " max"; break;
1103   case AtomicRMWInst::Min:  Out << " min"; break;
1104   case AtomicRMWInst::UMax: Out << " umax"; break;
1105   case AtomicRMWInst::UMin: Out << " umin"; break;
1106   }
1107 }
1108 
1109 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1110   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1111     // 'Fast' is an abbreviation for all fast-math-flags.
1112     if (FPO->isFast())
1113       Out << " fast";
1114     else {
1115       if (FPO->hasAllowReassoc())
1116         Out << " reassoc";
1117       if (FPO->hasNoNaNs())
1118         Out << " nnan";
1119       if (FPO->hasNoInfs())
1120         Out << " ninf";
1121       if (FPO->hasNoSignedZeros())
1122         Out << " nsz";
1123       if (FPO->hasAllowReciprocal())
1124         Out << " arcp";
1125       if (FPO->hasAllowContract())
1126         Out << " contract";
1127       if (FPO->hasApproxFunc())
1128         Out << " afn";
1129     }
1130   }
1131 
1132   if (const OverflowingBinaryOperator *OBO =
1133         dyn_cast<OverflowingBinaryOperator>(U)) {
1134     if (OBO->hasNoUnsignedWrap())
1135       Out << " nuw";
1136     if (OBO->hasNoSignedWrap())
1137       Out << " nsw";
1138   } else if (const PossiblyExactOperator *Div =
1139                dyn_cast<PossiblyExactOperator>(U)) {
1140     if (Div->isExact())
1141       Out << " exact";
1142   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1143     if (GEP->isInBounds())
1144       Out << " inbounds";
1145   }
1146 }
1147 
1148 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1149                                   TypePrinting &TypePrinter,
1150                                   SlotTracker *Machine,
1151                                   const Module *Context) {
1152   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1153     if (CI->getType()->isIntegerTy(1)) {
1154       Out << (CI->getZExtValue() ? "true" : "false");
1155       return;
1156     }
1157     Out << CI->getValue();
1158     return;
1159   }
1160 
1161   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1162     const APFloat &APF = CFP->getValueAPF();
1163     if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1164         &APF.getSemantics() == &APFloat::IEEEdouble()) {
1165       // We would like to output the FP constant value in exponential notation,
1166       // but we cannot do this if doing so will lose precision.  Check here to
1167       // make sure that we only output it in exponential format if we can parse
1168       // the value back and get the same value.
1169       //
1170       bool ignored;
1171       bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1172       bool isInf = APF.isInfinity();
1173       bool isNaN = APF.isNaN();
1174       if (!isInf && !isNaN) {
1175         double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
1176         SmallString<128> StrVal;
1177         APF.toString(StrVal, 6, 0, false);
1178         // Check to make sure that the stringized number is not some string like
1179         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
1180         // that the string matches the "[-+]?[0-9]" regex.
1181         //
1182         assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1183                 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1184                  (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1185                "[-+]?[0-9] regex does not match!");
1186         // Reparse stringized version!
1187         if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1188           Out << StrVal;
1189           return;
1190         }
1191       }
1192       // Otherwise we could not reparse it to exactly the same value, so we must
1193       // output the string in hexadecimal format!  Note that loading and storing
1194       // floating point types changes the bits of NaNs on some hosts, notably
1195       // x86, so we must not use these types.
1196       static_assert(sizeof(double) == sizeof(uint64_t),
1197                     "assuming that double is 64 bits!");
1198       APFloat apf = APF;
1199       // Floats are represented in ASCII IR as double, convert.
1200       if (!isDouble)
1201         apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1202                           &ignored);
1203       Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1204       return;
1205     }
1206 
1207     // Either half, or some form of long double.
1208     // These appear as a magic letter identifying the type, then a
1209     // fixed number of hex digits.
1210     Out << "0x";
1211     APInt API = APF.bitcastToAPInt();
1212     if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1213       Out << 'K';
1214       Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1215                                   /*Upper=*/true);
1216       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1217                                   /*Upper=*/true);
1218       return;
1219     } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1220       Out << 'L';
1221       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1222                                   /*Upper=*/true);
1223       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1224                                   /*Upper=*/true);
1225     } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1226       Out << 'M';
1227       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1228                                   /*Upper=*/true);
1229       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1230                                   /*Upper=*/true);
1231     } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1232       Out << 'H';
1233       Out << format_hex_no_prefix(API.getZExtValue(), 4,
1234                                   /*Upper=*/true);
1235     } else
1236       llvm_unreachable("Unsupported floating point type");
1237     return;
1238   }
1239 
1240   if (isa<ConstantAggregateZero>(CV)) {
1241     Out << "zeroinitializer";
1242     return;
1243   }
1244 
1245   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1246     Out << "blockaddress(";
1247     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1248                            Context);
1249     Out << ", ";
1250     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1251                            Context);
1252     Out << ")";
1253     return;
1254   }
1255 
1256   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1257     Type *ETy = CA->getType()->getElementType();
1258     Out << '[';
1259     TypePrinter.print(ETy, Out);
1260     Out << ' ';
1261     WriteAsOperandInternal(Out, CA->getOperand(0),
1262                            &TypePrinter, Machine,
1263                            Context);
1264     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1265       Out << ", ";
1266       TypePrinter.print(ETy, Out);
1267       Out << ' ';
1268       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1269                              Context);
1270     }
1271     Out << ']';
1272     return;
1273   }
1274 
1275   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1276     // As a special case, print the array as a string if it is an array of
1277     // i8 with ConstantInt values.
1278     if (CA->isString()) {
1279       Out << "c\"";
1280       PrintEscapedString(CA->getAsString(), Out);
1281       Out << '"';
1282       return;
1283     }
1284 
1285     Type *ETy = CA->getType()->getElementType();
1286     Out << '[';
1287     TypePrinter.print(ETy, Out);
1288     Out << ' ';
1289     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1290                            &TypePrinter, Machine,
1291                            Context);
1292     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1293       Out << ", ";
1294       TypePrinter.print(ETy, Out);
1295       Out << ' ';
1296       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1297                              Machine, Context);
1298     }
1299     Out << ']';
1300     return;
1301   }
1302 
1303   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1304     if (CS->getType()->isPacked())
1305       Out << '<';
1306     Out << '{';
1307     unsigned N = CS->getNumOperands();
1308     if (N) {
1309       Out << ' ';
1310       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1311       Out << ' ';
1312 
1313       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1314                              Context);
1315 
1316       for (unsigned i = 1; i < N; i++) {
1317         Out << ", ";
1318         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1319         Out << ' ';
1320 
1321         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1322                                Context);
1323       }
1324       Out << ' ';
1325     }
1326 
1327     Out << '}';
1328     if (CS->getType()->isPacked())
1329       Out << '>';
1330     return;
1331   }
1332 
1333   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1334     Type *ETy = CV->getType()->getVectorElementType();
1335     Out << '<';
1336     TypePrinter.print(ETy, Out);
1337     Out << ' ';
1338     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1339                            Machine, Context);
1340     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1341       Out << ", ";
1342       TypePrinter.print(ETy, Out);
1343       Out << ' ';
1344       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1345                              Machine, Context);
1346     }
1347     Out << '>';
1348     return;
1349   }
1350 
1351   if (isa<ConstantPointerNull>(CV)) {
1352     Out << "null";
1353     return;
1354   }
1355 
1356   if (isa<ConstantTokenNone>(CV)) {
1357     Out << "none";
1358     return;
1359   }
1360 
1361   if (isa<UndefValue>(CV)) {
1362     Out << "undef";
1363     return;
1364   }
1365 
1366   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1367     Out << CE->getOpcodeName();
1368     WriteOptimizationInfo(Out, CE);
1369     if (CE->isCompare())
1370       Out << ' ' << CmpInst::getPredicateName(
1371                         static_cast<CmpInst::Predicate>(CE->getPredicate()));
1372     Out << " (";
1373 
1374     Optional<unsigned> InRangeOp;
1375     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1376       TypePrinter.print(GEP->getSourceElementType(), Out);
1377       Out << ", ";
1378       InRangeOp = GEP->getInRangeIndex();
1379       if (InRangeOp)
1380         ++*InRangeOp;
1381     }
1382 
1383     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1384       if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1385         Out << "inrange ";
1386       TypePrinter.print((*OI)->getType(), Out);
1387       Out << ' ';
1388       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1389       if (OI+1 != CE->op_end())
1390         Out << ", ";
1391     }
1392 
1393     if (CE->hasIndices()) {
1394       ArrayRef<unsigned> Indices = CE->getIndices();
1395       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1396         Out << ", " << Indices[i];
1397     }
1398 
1399     if (CE->isCast()) {
1400       Out << " to ";
1401       TypePrinter.print(CE->getType(), Out);
1402     }
1403 
1404     Out << ')';
1405     return;
1406   }
1407 
1408   Out << "<placeholder or erroneous Constant>";
1409 }
1410 
1411 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1412                          TypePrinting *TypePrinter, SlotTracker *Machine,
1413                          const Module *Context) {
1414   Out << "!{";
1415   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1416     const Metadata *MD = Node->getOperand(mi);
1417     if (!MD)
1418       Out << "null";
1419     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1420       Value *V = MDV->getValue();
1421       TypePrinter->print(V->getType(), Out);
1422       Out << ' ';
1423       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1424     } else {
1425       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1426     }
1427     if (mi + 1 != me)
1428       Out << ", ";
1429   }
1430 
1431   Out << "}";
1432 }
1433 
1434 namespace {
1435 
1436 struct FieldSeparator {
1437   bool Skip = true;
1438   const char *Sep;
1439 
1440   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1441 };
1442 
1443 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1444   if (FS.Skip) {
1445     FS.Skip = false;
1446     return OS;
1447   }
1448   return OS << FS.Sep;
1449 }
1450 
1451 struct MDFieldPrinter {
1452   raw_ostream &Out;
1453   FieldSeparator FS;
1454   TypePrinting *TypePrinter = nullptr;
1455   SlotTracker *Machine = nullptr;
1456   const Module *Context = nullptr;
1457 
1458   explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
1459   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1460                  SlotTracker *Machine, const Module *Context)
1461       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1462   }
1463 
1464   void printTag(const DINode *N);
1465   void printMacinfoType(const DIMacroNode *N);
1466   void printChecksumKind(const DIFile *N);
1467   void printString(StringRef Name, StringRef Value,
1468                    bool ShouldSkipEmpty = true);
1469   void printMetadata(StringRef Name, const Metadata *MD,
1470                      bool ShouldSkipNull = true);
1471   template <class IntTy>
1472   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1473   void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1474   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1475   template <class IntTy, class Stringifier>
1476   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1477                       bool ShouldSkipZero = true);
1478   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1479 };
1480 
1481 } // end anonymous namespace
1482 
1483 void MDFieldPrinter::printTag(const DINode *N) {
1484   Out << FS << "tag: ";
1485   auto Tag = dwarf::TagString(N->getTag());
1486   if (!Tag.empty())
1487     Out << Tag;
1488   else
1489     Out << N->getTag();
1490 }
1491 
1492 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1493   Out << FS << "type: ";
1494   auto Type = dwarf::MacinfoString(N->getMacinfoType());
1495   if (!Type.empty())
1496     Out << Type;
1497   else
1498     Out << N->getMacinfoType();
1499 }
1500 
1501 void MDFieldPrinter::printChecksumKind(const DIFile *N) {
1502   if (N->getChecksumKind() == DIFile::CSK_None)
1503     // Skip CSK_None checksum kind.
1504     return;
1505   Out << FS << "checksumkind: " << N->getChecksumKindAsString();
1506 }
1507 
1508 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1509                                  bool ShouldSkipEmpty) {
1510   if (ShouldSkipEmpty && Value.empty())
1511     return;
1512 
1513   Out << FS << Name << ": \"";
1514   PrintEscapedString(Value, Out);
1515   Out << "\"";
1516 }
1517 
1518 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1519                                    TypePrinting *TypePrinter,
1520                                    SlotTracker *Machine,
1521                                    const Module *Context) {
1522   if (!MD) {
1523     Out << "null";
1524     return;
1525   }
1526   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1527 }
1528 
1529 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1530                                    bool ShouldSkipNull) {
1531   if (ShouldSkipNull && !MD)
1532     return;
1533 
1534   Out << FS << Name << ": ";
1535   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1536 }
1537 
1538 template <class IntTy>
1539 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1540   if (ShouldSkipZero && !Int)
1541     return;
1542 
1543   Out << FS << Name << ": " << Int;
1544 }
1545 
1546 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1547                                Optional<bool> Default) {
1548   if (Default && Value == *Default)
1549     return;
1550   Out << FS << Name << ": " << (Value ? "true" : "false");
1551 }
1552 
1553 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1554   if (!Flags)
1555     return;
1556 
1557   Out << FS << Name << ": ";
1558 
1559   SmallVector<DINode::DIFlags, 8> SplitFlags;
1560   auto Extra = DINode::splitFlags(Flags, SplitFlags);
1561 
1562   FieldSeparator FlagsFS(" | ");
1563   for (auto F : SplitFlags) {
1564     auto StringF = DINode::getFlagString(F);
1565     assert(!StringF.empty() && "Expected valid flag");
1566     Out << FlagsFS << StringF;
1567   }
1568   if (Extra || SplitFlags.empty())
1569     Out << FlagsFS << Extra;
1570 }
1571 
1572 void MDFieldPrinter::printEmissionKind(StringRef Name,
1573                                        DICompileUnit::DebugEmissionKind EK) {
1574   Out << FS << Name << ": " << DICompileUnit::EmissionKindString(EK);
1575 }
1576 
1577 template <class IntTy, class Stringifier>
1578 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1579                                     Stringifier toString, bool ShouldSkipZero) {
1580   if (!Value)
1581     return;
1582 
1583   Out << FS << Name << ": ";
1584   auto S = toString(Value);
1585   if (!S.empty())
1586     Out << S;
1587   else
1588     Out << Value;
1589 }
1590 
1591 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1592                                TypePrinting *TypePrinter, SlotTracker *Machine,
1593                                const Module *Context) {
1594   Out << "!GenericDINode(";
1595   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1596   Printer.printTag(N);
1597   Printer.printString("header", N->getHeader());
1598   if (N->getNumDwarfOperands()) {
1599     Out << Printer.FS << "operands: {";
1600     FieldSeparator IFS;
1601     for (auto &I : N->dwarf_operands()) {
1602       Out << IFS;
1603       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1604     }
1605     Out << "}";
1606   }
1607   Out << ")";
1608 }
1609 
1610 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1611                             TypePrinting *TypePrinter, SlotTracker *Machine,
1612                             const Module *Context) {
1613   Out << "!DILocation(";
1614   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1615   // Always output the line, since 0 is a relevant and important value for it.
1616   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1617   Printer.printInt("column", DL->getColumn());
1618   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1619   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1620   Out << ")";
1621 }
1622 
1623 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1624                             TypePrinting *, SlotTracker *, const Module *) {
1625   Out << "!DISubrange(";
1626   MDFieldPrinter Printer(Out);
1627   Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1628   Printer.printInt("lowerBound", N->getLowerBound());
1629   Out << ")";
1630 }
1631 
1632 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1633                               TypePrinting *, SlotTracker *, const Module *) {
1634   Out << "!DIEnumerator(";
1635   MDFieldPrinter Printer(Out);
1636   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1637   Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1638   Out << ")";
1639 }
1640 
1641 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1642                              TypePrinting *, SlotTracker *, const Module *) {
1643   Out << "!DIBasicType(";
1644   MDFieldPrinter Printer(Out);
1645   if (N->getTag() != dwarf::DW_TAG_base_type)
1646     Printer.printTag(N);
1647   Printer.printString("name", N->getName());
1648   Printer.printInt("size", N->getSizeInBits());
1649   Printer.printInt("align", N->getAlignInBits());
1650   Printer.printDwarfEnum("encoding", N->getEncoding(),
1651                          dwarf::AttributeEncodingString);
1652   Out << ")";
1653 }
1654 
1655 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1656                                TypePrinting *TypePrinter, SlotTracker *Machine,
1657                                const Module *Context) {
1658   Out << "!DIDerivedType(";
1659   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1660   Printer.printTag(N);
1661   Printer.printString("name", N->getName());
1662   Printer.printMetadata("scope", N->getRawScope());
1663   Printer.printMetadata("file", N->getRawFile());
1664   Printer.printInt("line", N->getLine());
1665   Printer.printMetadata("baseType", N->getRawBaseType(),
1666                         /* ShouldSkipNull */ false);
1667   Printer.printInt("size", N->getSizeInBits());
1668   Printer.printInt("align", N->getAlignInBits());
1669   Printer.printInt("offset", N->getOffsetInBits());
1670   Printer.printDIFlags("flags", N->getFlags());
1671   Printer.printMetadata("extraData", N->getRawExtraData());
1672   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1673     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
1674                      /* ShouldSkipZero */ false);
1675   Out << ")";
1676 }
1677 
1678 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1679                                  TypePrinting *TypePrinter,
1680                                  SlotTracker *Machine, const Module *Context) {
1681   Out << "!DICompositeType(";
1682   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1683   Printer.printTag(N);
1684   Printer.printString("name", N->getName());
1685   Printer.printMetadata("scope", N->getRawScope());
1686   Printer.printMetadata("file", N->getRawFile());
1687   Printer.printInt("line", N->getLine());
1688   Printer.printMetadata("baseType", N->getRawBaseType());
1689   Printer.printInt("size", N->getSizeInBits());
1690   Printer.printInt("align", N->getAlignInBits());
1691   Printer.printInt("offset", N->getOffsetInBits());
1692   Printer.printDIFlags("flags", N->getFlags());
1693   Printer.printMetadata("elements", N->getRawElements());
1694   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1695                          dwarf::LanguageString);
1696   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1697   Printer.printMetadata("templateParams", N->getRawTemplateParams());
1698   Printer.printString("identifier", N->getIdentifier());
1699   Out << ")";
1700 }
1701 
1702 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1703                                   TypePrinting *TypePrinter,
1704                                   SlotTracker *Machine, const Module *Context) {
1705   Out << "!DISubroutineType(";
1706   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1707   Printer.printDIFlags("flags", N->getFlags());
1708   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
1709   Printer.printMetadata("types", N->getRawTypeArray(),
1710                         /* ShouldSkipNull */ false);
1711   Out << ")";
1712 }
1713 
1714 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1715                         SlotTracker *, const Module *) {
1716   Out << "!DIFile(";
1717   MDFieldPrinter Printer(Out);
1718   Printer.printString("filename", N->getFilename(),
1719                       /* ShouldSkipEmpty */ false);
1720   Printer.printString("directory", N->getDirectory(),
1721                       /* ShouldSkipEmpty */ false);
1722   Printer.printChecksumKind(N);
1723   Printer.printString("checksum", N->getChecksum(), /* ShouldSkipEmpty */ true);
1724   Out << ")";
1725 }
1726 
1727 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1728                                TypePrinting *TypePrinter, SlotTracker *Machine,
1729                                const Module *Context) {
1730   Out << "!DICompileUnit(";
1731   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1732   Printer.printDwarfEnum("language", N->getSourceLanguage(),
1733                          dwarf::LanguageString, /* ShouldSkipZero */ false);
1734   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1735   Printer.printString("producer", N->getProducer());
1736   Printer.printBool("isOptimized", N->isOptimized());
1737   Printer.printString("flags", N->getFlags());
1738   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1739                    /* ShouldSkipZero */ false);
1740   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1741   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
1742   Printer.printMetadata("enums", N->getRawEnumTypes());
1743   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1744   Printer.printMetadata("globals", N->getRawGlobalVariables());
1745   Printer.printMetadata("imports", N->getRawImportedEntities());
1746   Printer.printMetadata("macros", N->getRawMacros());
1747   Printer.printInt("dwoId", N->getDWOId());
1748   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
1749   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
1750                     false);
1751   Printer.printBool("gnuPubnames", N->getGnuPubnames(), false);
1752   Out << ")";
1753 }
1754 
1755 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1756                               TypePrinting *TypePrinter, SlotTracker *Machine,
1757                               const Module *Context) {
1758   Out << "!DISubprogram(";
1759   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1760   Printer.printString("name", N->getName());
1761   Printer.printString("linkageName", N->getLinkageName());
1762   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1763   Printer.printMetadata("file", N->getRawFile());
1764   Printer.printInt("line", N->getLine());
1765   Printer.printMetadata("type", N->getRawType());
1766   Printer.printBool("isLocal", N->isLocalToUnit());
1767   Printer.printBool("isDefinition", N->isDefinition());
1768   Printer.printInt("scopeLine", N->getScopeLine());
1769   Printer.printMetadata("containingType", N->getRawContainingType());
1770   Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1771                          dwarf::VirtualityString);
1772   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
1773       N->getVirtualIndex() != 0)
1774     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
1775   Printer.printInt("thisAdjustment", N->getThisAdjustment());
1776   Printer.printDIFlags("flags", N->getFlags());
1777   Printer.printBool("isOptimized", N->isOptimized());
1778   Printer.printMetadata("unit", N->getRawUnit());
1779   Printer.printMetadata("templateParams", N->getRawTemplateParams());
1780   Printer.printMetadata("declaration", N->getRawDeclaration());
1781   Printer.printMetadata("variables", N->getRawVariables());
1782   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
1783   Out << ")";
1784 }
1785 
1786 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1787                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1788                                 const Module *Context) {
1789   Out << "!DILexicalBlock(";
1790   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1791   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1792   Printer.printMetadata("file", N->getRawFile());
1793   Printer.printInt("line", N->getLine());
1794   Printer.printInt("column", N->getColumn());
1795   Out << ")";
1796 }
1797 
1798 static void writeDILexicalBlockFile(raw_ostream &Out,
1799                                     const DILexicalBlockFile *N,
1800                                     TypePrinting *TypePrinter,
1801                                     SlotTracker *Machine,
1802                                     const Module *Context) {
1803   Out << "!DILexicalBlockFile(";
1804   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1805   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1806   Printer.printMetadata("file", N->getRawFile());
1807   Printer.printInt("discriminator", N->getDiscriminator(),
1808                    /* ShouldSkipZero */ false);
1809   Out << ")";
1810 }
1811 
1812 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1813                              TypePrinting *TypePrinter, SlotTracker *Machine,
1814                              const Module *Context) {
1815   Out << "!DINamespace(";
1816   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1817   Printer.printString("name", N->getName());
1818   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1819   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
1820   Out << ")";
1821 }
1822 
1823 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1824                          TypePrinting *TypePrinter, SlotTracker *Machine,
1825                          const Module *Context) {
1826   Out << "!DIMacro(";
1827   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1828   Printer.printMacinfoType(N);
1829   Printer.printInt("line", N->getLine());
1830   Printer.printString("name", N->getName());
1831   Printer.printString("value", N->getValue());
1832   Out << ")";
1833 }
1834 
1835 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1836                              TypePrinting *TypePrinter, SlotTracker *Machine,
1837                              const Module *Context) {
1838   Out << "!DIMacroFile(";
1839   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1840   Printer.printInt("line", N->getLine());
1841   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1842   Printer.printMetadata("nodes", N->getRawElements());
1843   Out << ")";
1844 }
1845 
1846 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1847                           TypePrinting *TypePrinter, SlotTracker *Machine,
1848                           const Module *Context) {
1849   Out << "!DIModule(";
1850   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1851   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1852   Printer.printString("name", N->getName());
1853   Printer.printString("configMacros", N->getConfigurationMacros());
1854   Printer.printString("includePath", N->getIncludePath());
1855   Printer.printString("isysroot", N->getISysRoot());
1856   Out << ")";
1857 }
1858 
1859 
1860 static void writeDITemplateTypeParameter(raw_ostream &Out,
1861                                          const DITemplateTypeParameter *N,
1862                                          TypePrinting *TypePrinter,
1863                                          SlotTracker *Machine,
1864                                          const Module *Context) {
1865   Out << "!DITemplateTypeParameter(";
1866   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1867   Printer.printString("name", N->getName());
1868   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1869   Out << ")";
1870 }
1871 
1872 static void writeDITemplateValueParameter(raw_ostream &Out,
1873                                           const DITemplateValueParameter *N,
1874                                           TypePrinting *TypePrinter,
1875                                           SlotTracker *Machine,
1876                                           const Module *Context) {
1877   Out << "!DITemplateValueParameter(";
1878   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1879   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1880     Printer.printTag(N);
1881   Printer.printString("name", N->getName());
1882   Printer.printMetadata("type", N->getRawType());
1883   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1884   Out << ")";
1885 }
1886 
1887 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1888                                   TypePrinting *TypePrinter,
1889                                   SlotTracker *Machine, const Module *Context) {
1890   Out << "!DIGlobalVariable(";
1891   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1892   Printer.printString("name", N->getName());
1893   Printer.printString("linkageName", N->getLinkageName());
1894   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1895   Printer.printMetadata("file", N->getRawFile());
1896   Printer.printInt("line", N->getLine());
1897   Printer.printMetadata("type", N->getRawType());
1898   Printer.printBool("isLocal", N->isLocalToUnit());
1899   Printer.printBool("isDefinition", N->isDefinition());
1900   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1901   Printer.printInt("align", N->getAlignInBits());
1902   Out << ")";
1903 }
1904 
1905 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1906                                  TypePrinting *TypePrinter,
1907                                  SlotTracker *Machine, const Module *Context) {
1908   Out << "!DILocalVariable(";
1909   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1910   Printer.printString("name", N->getName());
1911   Printer.printInt("arg", N->getArg());
1912   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1913   Printer.printMetadata("file", N->getRawFile());
1914   Printer.printInt("line", N->getLine());
1915   Printer.printMetadata("type", N->getRawType());
1916   Printer.printDIFlags("flags", N->getFlags());
1917   Printer.printInt("align", N->getAlignInBits());
1918   Out << ")";
1919 }
1920 
1921 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1922                               TypePrinting *TypePrinter, SlotTracker *Machine,
1923                               const Module *Context) {
1924   Out << "!DIExpression(";
1925   FieldSeparator FS;
1926   if (N->isValid()) {
1927     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1928       auto OpStr = dwarf::OperationEncodingString(I->getOp());
1929       assert(!OpStr.empty() && "Expected valid opcode");
1930 
1931       Out << FS << OpStr;
1932       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1933         Out << FS << I->getArg(A);
1934     }
1935   } else {
1936     for (const auto &I : N->getElements())
1937       Out << FS << I;
1938   }
1939   Out << ")";
1940 }
1941 
1942 static void writeDIGlobalVariableExpression(raw_ostream &Out,
1943                                             const DIGlobalVariableExpression *N,
1944                                             TypePrinting *TypePrinter,
1945                                             SlotTracker *Machine,
1946                                             const Module *Context) {
1947   Out << "!DIGlobalVariableExpression(";
1948   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1949   Printer.printMetadata("var", N->getVariable());
1950   Printer.printMetadata("expr", N->getExpression());
1951   Out << ")";
1952 }
1953 
1954 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1955                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1956                                 const Module *Context) {
1957   Out << "!DIObjCProperty(";
1958   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1959   Printer.printString("name", N->getName());
1960   Printer.printMetadata("file", N->getRawFile());
1961   Printer.printInt("line", N->getLine());
1962   Printer.printString("setter", N->getSetterName());
1963   Printer.printString("getter", N->getGetterName());
1964   Printer.printInt("attributes", N->getAttributes());
1965   Printer.printMetadata("type", N->getRawType());
1966   Out << ")";
1967 }
1968 
1969 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1970                                   TypePrinting *TypePrinter,
1971                                   SlotTracker *Machine, const Module *Context) {
1972   Out << "!DIImportedEntity(";
1973   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1974   Printer.printTag(N);
1975   Printer.printString("name", N->getName());
1976   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1977   Printer.printMetadata("entity", N->getRawEntity());
1978   Printer.printMetadata("file", N->getRawFile());
1979   Printer.printInt("line", N->getLine());
1980   Out << ")";
1981 }
1982 
1983 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1984                                     TypePrinting *TypePrinter,
1985                                     SlotTracker *Machine,
1986                                     const Module *Context) {
1987   if (Node->isDistinct())
1988     Out << "distinct ";
1989   else if (Node->isTemporary())
1990     Out << "<temporary!> "; // Handle broken code.
1991 
1992   switch (Node->getMetadataID()) {
1993   default:
1994     llvm_unreachable("Expected uniquable MDNode");
1995 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1996   case Metadata::CLASS##Kind:                                                  \
1997     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
1998     break;
1999 #include "llvm/IR/Metadata.def"
2000   }
2001 }
2002 
2003 // Full implementation of printing a Value as an operand with support for
2004 // TypePrinting, etc.
2005 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2006                                    TypePrinting *TypePrinter,
2007                                    SlotTracker *Machine,
2008                                    const Module *Context) {
2009   if (V->hasName()) {
2010     PrintLLVMName(Out, V);
2011     return;
2012   }
2013 
2014   const Constant *CV = dyn_cast<Constant>(V);
2015   if (CV && !isa<GlobalValue>(CV)) {
2016     assert(TypePrinter && "Constants require TypePrinting!");
2017     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
2018     return;
2019   }
2020 
2021   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2022     Out << "asm ";
2023     if (IA->hasSideEffects())
2024       Out << "sideeffect ";
2025     if (IA->isAlignStack())
2026       Out << "alignstack ";
2027     // We don't emit the AD_ATT dialect as it's the assumed default.
2028     if (IA->getDialect() == InlineAsm::AD_Intel)
2029       Out << "inteldialect ";
2030     Out << '"';
2031     PrintEscapedString(IA->getAsmString(), Out);
2032     Out << "\", \"";
2033     PrintEscapedString(IA->getConstraintString(), Out);
2034     Out << '"';
2035     return;
2036   }
2037 
2038   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2039     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2040                            Context, /* FromValue */ true);
2041     return;
2042   }
2043 
2044   char Prefix = '%';
2045   int Slot;
2046   // If we have a SlotTracker, use it.
2047   if (Machine) {
2048     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2049       Slot = Machine->getGlobalSlot(GV);
2050       Prefix = '@';
2051     } else {
2052       Slot = Machine->getLocalSlot(V);
2053 
2054       // If the local value didn't succeed, then we may be referring to a value
2055       // from a different function.  Translate it, as this can happen when using
2056       // address of blocks.
2057       if (Slot == -1)
2058         if ((Machine = createSlotTracker(V))) {
2059           Slot = Machine->getLocalSlot(V);
2060           delete Machine;
2061         }
2062     }
2063   } else if ((Machine = createSlotTracker(V))) {
2064     // Otherwise, create one to get the # and then destroy it.
2065     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2066       Slot = Machine->getGlobalSlot(GV);
2067       Prefix = '@';
2068     } else {
2069       Slot = Machine->getLocalSlot(V);
2070     }
2071     delete Machine;
2072     Machine = nullptr;
2073   } else {
2074     Slot = -1;
2075   }
2076 
2077   if (Slot != -1)
2078     Out << Prefix << Slot;
2079   else
2080     Out << "<badref>";
2081 }
2082 
2083 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2084                                    TypePrinting *TypePrinter,
2085                                    SlotTracker *Machine, const Module *Context,
2086                                    bool FromValue) {
2087   // Write DIExpressions inline when used as a value. Improves readability of
2088   // debug info intrinsics.
2089   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2090     writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2091     return;
2092   }
2093 
2094   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2095     std::unique_ptr<SlotTracker> MachineStorage;
2096     if (!Machine) {
2097       MachineStorage = make_unique<SlotTracker>(Context);
2098       Machine = MachineStorage.get();
2099     }
2100     int Slot = Machine->getMetadataSlot(N);
2101     if (Slot == -1)
2102       // Give the pointer value instead of "badref", since this comes up all
2103       // the time when debugging.
2104       Out << "<" << N << ">";
2105     else
2106       Out << '!' << Slot;
2107     return;
2108   }
2109 
2110   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2111     Out << "!\"";
2112     PrintEscapedString(MDS->getString(), Out);
2113     Out << '"';
2114     return;
2115   }
2116 
2117   auto *V = cast<ValueAsMetadata>(MD);
2118   assert(TypePrinter && "TypePrinter required for metadata values");
2119   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2120          "Unexpected function-local metadata outside of value argument");
2121 
2122   TypePrinter->print(V->getValue()->getType(), Out);
2123   Out << ' ';
2124   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2125 }
2126 
2127 namespace {
2128 
2129 class AssemblyWriter {
2130   formatted_raw_ostream &Out;
2131   const Module *TheModule;
2132   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2133   SlotTracker &Machine;
2134   TypePrinting TypePrinter;
2135   AssemblyAnnotationWriter *AnnotationWriter;
2136   SetVector<const Comdat *> Comdats;
2137   bool IsForDebug;
2138   bool ShouldPreserveUseListOrder;
2139   UseListOrderStack UseListOrders;
2140   SmallVector<StringRef, 8> MDNames;
2141   /// Synchronization scope names registered with LLVMContext.
2142   SmallVector<StringRef, 8> SSNs;
2143 
2144 public:
2145   /// Construct an AssemblyWriter with an external SlotTracker
2146   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2147                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2148                  bool ShouldPreserveUseListOrder = false);
2149 
2150   void printMDNodeBody(const MDNode *MD);
2151   void printNamedMDNode(const NamedMDNode *NMD);
2152 
2153   void printModule(const Module *M);
2154 
2155   void writeOperand(const Value *Op, bool PrintType);
2156   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2157   void writeOperandBundles(ImmutableCallSite CS);
2158   void writeSyncScope(const LLVMContext &Context,
2159                       SyncScope::ID SSID);
2160   void writeAtomic(const LLVMContext &Context,
2161                    AtomicOrdering Ordering,
2162                    SyncScope::ID SSID);
2163   void writeAtomicCmpXchg(const LLVMContext &Context,
2164                           AtomicOrdering SuccessOrdering,
2165                           AtomicOrdering FailureOrdering,
2166                           SyncScope::ID SSID);
2167 
2168   void writeAllMDNodes();
2169   void writeMDNode(unsigned Slot, const MDNode *Node);
2170   void writeAllAttributeGroups();
2171 
2172   void printTypeIdentities();
2173   void printGlobal(const GlobalVariable *GV);
2174   void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2175   void printComdat(const Comdat *C);
2176   void printFunction(const Function *F);
2177   void printArgument(const Argument *FA, AttributeSet Attrs);
2178   void printBasicBlock(const BasicBlock *BB);
2179   void printInstructionLine(const Instruction &I);
2180   void printInstruction(const Instruction &I);
2181 
2182   void printUseListOrder(const UseListOrder &Order);
2183   void printUseLists(const Function *F);
2184 
2185 private:
2186   /// \brief Print out metadata attachments.
2187   void printMetadataAttachments(
2188       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2189       StringRef Separator);
2190 
2191   // printInfoComment - Print a little comment after the instruction indicating
2192   // which slot it occupies.
2193   void printInfoComment(const Value &V);
2194 
2195   // printGCRelocateComment - print comment after call to the gc.relocate
2196   // intrinsic indicating base and derived pointer names.
2197   void printGCRelocateComment(const GCRelocateInst &Relocate);
2198 };
2199 
2200 } // end anonymous namespace
2201 
2202 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2203                                const Module *M, AssemblyAnnotationWriter *AAW,
2204                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2205     : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2206       IsForDebug(IsForDebug),
2207       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2208   if (!TheModule)
2209     return;
2210   TypePrinter.incorporateTypes(*TheModule);
2211   for (const GlobalObject &GO : TheModule->global_objects())
2212     if (const Comdat *C = GO.getComdat())
2213       Comdats.insert(C);
2214 }
2215 
2216 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2217   if (!Operand) {
2218     Out << "<null operand!>";
2219     return;
2220   }
2221   if (PrintType) {
2222     TypePrinter.print(Operand->getType(), Out);
2223     Out << ' ';
2224   }
2225   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2226 }
2227 
2228 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2229                                     SyncScope::ID SSID) {
2230   switch (SSID) {
2231   case SyncScope::System: {
2232     break;
2233   }
2234   default: {
2235     if (SSNs.empty())
2236       Context.getSyncScopeNames(SSNs);
2237 
2238     Out << " syncscope(\"";
2239     PrintEscapedString(SSNs[SSID], Out);
2240     Out << "\")";
2241     break;
2242   }
2243   }
2244 }
2245 
2246 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2247                                  AtomicOrdering Ordering,
2248                                  SyncScope::ID SSID) {
2249   if (Ordering == AtomicOrdering::NotAtomic)
2250     return;
2251 
2252   writeSyncScope(Context, SSID);
2253   Out << " " << toIRString(Ordering);
2254 }
2255 
2256 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2257                                         AtomicOrdering SuccessOrdering,
2258                                         AtomicOrdering FailureOrdering,
2259                                         SyncScope::ID SSID) {
2260   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2261          FailureOrdering != AtomicOrdering::NotAtomic);
2262 
2263   writeSyncScope(Context, SSID);
2264   Out << " " << toIRString(SuccessOrdering);
2265   Out << " " << toIRString(FailureOrdering);
2266 }
2267 
2268 void AssemblyWriter::writeParamOperand(const Value *Operand,
2269                                        AttributeSet Attrs) {
2270   if (!Operand) {
2271     Out << "<null operand!>";
2272     return;
2273   }
2274 
2275   // Print the type
2276   TypePrinter.print(Operand->getType(), Out);
2277   // Print parameter attributes list
2278   if (Attrs.hasAttributes())
2279     Out << ' ' << Attrs.getAsString();
2280   Out << ' ';
2281   // Print the operand
2282   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2283 }
2284 
2285 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2286   if (!CS.hasOperandBundles())
2287     return;
2288 
2289   Out << " [ ";
2290 
2291   bool FirstBundle = true;
2292   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2293     OperandBundleUse BU = CS.getOperandBundleAt(i);
2294 
2295     if (!FirstBundle)
2296       Out << ", ";
2297     FirstBundle = false;
2298 
2299     Out << '"';
2300     PrintEscapedString(BU.getTagName(), Out);
2301     Out << '"';
2302 
2303     Out << '(';
2304 
2305     bool FirstInput = true;
2306     for (const auto &Input : BU.Inputs) {
2307       if (!FirstInput)
2308         Out << ", ";
2309       FirstInput = false;
2310 
2311       TypePrinter.print(Input->getType(), Out);
2312       Out << " ";
2313       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2314     }
2315 
2316     Out << ')';
2317   }
2318 
2319   Out << " ]";
2320 }
2321 
2322 void AssemblyWriter::printModule(const Module *M) {
2323   Machine.initialize();
2324 
2325   if (ShouldPreserveUseListOrder)
2326     UseListOrders = predictUseListOrder(M);
2327 
2328   if (!M->getModuleIdentifier().empty() &&
2329       // Don't print the ID if it will start a new line (which would
2330       // require a comment char before it).
2331       M->getModuleIdentifier().find('\n') == std::string::npos)
2332     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2333 
2334   if (!M->getSourceFileName().empty()) {
2335     Out << "source_filename = \"";
2336     PrintEscapedString(M->getSourceFileName(), Out);
2337     Out << "\"\n";
2338   }
2339 
2340   const std::string &DL = M->getDataLayoutStr();
2341   if (!DL.empty())
2342     Out << "target datalayout = \"" << DL << "\"\n";
2343   if (!M->getTargetTriple().empty())
2344     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2345 
2346   if (!M->getModuleInlineAsm().empty()) {
2347     Out << '\n';
2348 
2349     // Split the string into lines, to make it easier to read the .ll file.
2350     StringRef Asm = M->getModuleInlineAsm();
2351     do {
2352       StringRef Front;
2353       std::tie(Front, Asm) = Asm.split('\n');
2354 
2355       // We found a newline, print the portion of the asm string from the
2356       // last newline up to this newline.
2357       Out << "module asm \"";
2358       PrintEscapedString(Front, Out);
2359       Out << "\"\n";
2360     } while (!Asm.empty());
2361   }
2362 
2363   printTypeIdentities();
2364 
2365   // Output all comdats.
2366   if (!Comdats.empty())
2367     Out << '\n';
2368   for (const Comdat *C : Comdats) {
2369     printComdat(C);
2370     if (C != Comdats.back())
2371       Out << '\n';
2372   }
2373 
2374   // Output all globals.
2375   if (!M->global_empty()) Out << '\n';
2376   for (const GlobalVariable &GV : M->globals()) {
2377     printGlobal(&GV); Out << '\n';
2378   }
2379 
2380   // Output all aliases.
2381   if (!M->alias_empty()) Out << "\n";
2382   for (const GlobalAlias &GA : M->aliases())
2383     printIndirectSymbol(&GA);
2384 
2385   // Output all ifuncs.
2386   if (!M->ifunc_empty()) Out << "\n";
2387   for (const GlobalIFunc &GI : M->ifuncs())
2388     printIndirectSymbol(&GI);
2389 
2390   // Output global use-lists.
2391   printUseLists(nullptr);
2392 
2393   // Output all of the functions.
2394   for (const Function &F : *M)
2395     printFunction(&F);
2396   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2397 
2398   // Output all attribute groups.
2399   if (!Machine.as_empty()) {
2400     Out << '\n';
2401     writeAllAttributeGroups();
2402   }
2403 
2404   // Output named metadata.
2405   if (!M->named_metadata_empty()) Out << '\n';
2406 
2407   for (const NamedMDNode &Node : M->named_metadata())
2408     printNamedMDNode(&Node);
2409 
2410   // Output metadata.
2411   if (!Machine.mdn_empty()) {
2412     Out << '\n';
2413     writeAllMDNodes();
2414   }
2415 }
2416 
2417 static void printMetadataIdentifier(StringRef Name,
2418                                     formatted_raw_ostream &Out) {
2419   if (Name.empty()) {
2420     Out << "<empty name> ";
2421   } else {
2422     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2423         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2424       Out << Name[0];
2425     else
2426       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2427     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2428       unsigned char C = Name[i];
2429       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2430           C == '.' || C == '_')
2431         Out << C;
2432       else
2433         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2434     }
2435   }
2436 }
2437 
2438 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2439   Out << '!';
2440   printMetadataIdentifier(NMD->getName(), Out);
2441   Out << " = !{";
2442   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2443     if (i)
2444       Out << ", ";
2445 
2446     // Write DIExpressions inline.
2447     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
2448     MDNode *Op = NMD->getOperand(i);
2449     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
2450       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
2451       continue;
2452     }
2453 
2454     int Slot = Machine.getMetadataSlot(Op);
2455     if (Slot == -1)
2456       Out << "<badref>";
2457     else
2458       Out << '!' << Slot;
2459   }
2460   Out << "}\n";
2461 }
2462 
2463 static const char *getLinkagePrintName(GlobalValue::LinkageTypes LT) {
2464   switch (LT) {
2465   case GlobalValue::ExternalLinkage:
2466     return "";
2467   case GlobalValue::PrivateLinkage:
2468     return "private ";
2469   case GlobalValue::InternalLinkage:
2470     return "internal ";
2471   case GlobalValue::LinkOnceAnyLinkage:
2472     return "linkonce ";
2473   case GlobalValue::LinkOnceODRLinkage:
2474     return "linkonce_odr ";
2475   case GlobalValue::WeakAnyLinkage:
2476     return "weak ";
2477   case GlobalValue::WeakODRLinkage:
2478     return "weak_odr ";
2479   case GlobalValue::CommonLinkage:
2480     return "common ";
2481   case GlobalValue::AppendingLinkage:
2482     return "appending ";
2483   case GlobalValue::ExternalWeakLinkage:
2484     return "extern_weak ";
2485   case GlobalValue::AvailableExternallyLinkage:
2486     return "available_externally ";
2487   }
2488   llvm_unreachable("invalid linkage");
2489 }
2490 
2491 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2492                             formatted_raw_ostream &Out) {
2493   switch (Vis) {
2494   case GlobalValue::DefaultVisibility: break;
2495   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
2496   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2497   }
2498 }
2499 
2500 static void PrintDSOLocation(const GlobalValue &GV,
2501                              formatted_raw_ostream &Out) {
2502   // GVs with local linkage are implicitly dso_local, so we don't print it.
2503   if (GV.isDSOLocal() && !GV.hasLocalLinkage())
2504     Out << "dso_local ";
2505 }
2506 
2507 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2508                                  formatted_raw_ostream &Out) {
2509   switch (SCT) {
2510   case GlobalValue::DefaultStorageClass: break;
2511   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2512   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2513   }
2514 }
2515 
2516 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2517                                   formatted_raw_ostream &Out) {
2518   switch (TLM) {
2519     case GlobalVariable::NotThreadLocal:
2520       break;
2521     case GlobalVariable::GeneralDynamicTLSModel:
2522       Out << "thread_local ";
2523       break;
2524     case GlobalVariable::LocalDynamicTLSModel:
2525       Out << "thread_local(localdynamic) ";
2526       break;
2527     case GlobalVariable::InitialExecTLSModel:
2528       Out << "thread_local(initialexec) ";
2529       break;
2530     case GlobalVariable::LocalExecTLSModel:
2531       Out << "thread_local(localexec) ";
2532       break;
2533   }
2534 }
2535 
2536 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
2537   switch (UA) {
2538   case GlobalVariable::UnnamedAddr::None:
2539     return "";
2540   case GlobalVariable::UnnamedAddr::Local:
2541     return "local_unnamed_addr";
2542   case GlobalVariable::UnnamedAddr::Global:
2543     return "unnamed_addr";
2544   }
2545   llvm_unreachable("Unknown UnnamedAddr");
2546 }
2547 
2548 static void maybePrintComdat(formatted_raw_ostream &Out,
2549                              const GlobalObject &GO) {
2550   const Comdat *C = GO.getComdat();
2551   if (!C)
2552     return;
2553 
2554   if (isa<GlobalVariable>(GO))
2555     Out << ',';
2556   Out << " comdat";
2557 
2558   if (GO.getName() == C->getName())
2559     return;
2560 
2561   Out << '(';
2562   PrintLLVMName(Out, C->getName(), ComdatPrefix);
2563   Out << ')';
2564 }
2565 
2566 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2567   if (GV->isMaterializable())
2568     Out << "; Materializable\n";
2569 
2570   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2571   Out << " = ";
2572 
2573   if (!GV->hasInitializer() && GV->hasExternalLinkage())
2574     Out << "external ";
2575 
2576   Out << getLinkagePrintName(GV->getLinkage());
2577   PrintDSOLocation(*GV, Out);
2578   PrintVisibility(GV->getVisibility(), Out);
2579   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2580   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2581   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
2582   if (!UA.empty())
2583       Out << UA << ' ';
2584 
2585   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2586     Out << "addrspace(" << AddressSpace << ") ";
2587   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2588   Out << (GV->isConstant() ? "constant " : "global ");
2589   TypePrinter.print(GV->getValueType(), Out);
2590 
2591   if (GV->hasInitializer()) {
2592     Out << ' ';
2593     writeOperand(GV->getInitializer(), false);
2594   }
2595 
2596   if (GV->hasSection()) {
2597     Out << ", section \"";
2598     PrintEscapedString(GV->getSection(), Out);
2599     Out << '"';
2600   }
2601   maybePrintComdat(Out, *GV);
2602   if (GV->getAlignment())
2603     Out << ", align " << GV->getAlignment();
2604 
2605   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2606   GV->getAllMetadata(MDs);
2607   printMetadataAttachments(MDs, ", ");
2608 
2609   auto Attrs = GV->getAttributes();
2610   if (Attrs.hasAttributes())
2611     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
2612 
2613   printInfoComment(*GV);
2614 }
2615 
2616 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
2617   if (GIS->isMaterializable())
2618     Out << "; Materializable\n";
2619 
2620   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
2621   Out << " = ";
2622 
2623   Out << getLinkagePrintName(GIS->getLinkage());
2624   PrintDSOLocation(*GIS, Out);
2625   PrintVisibility(GIS->getVisibility(), Out);
2626   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
2627   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
2628   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
2629   if (!UA.empty())
2630       Out << UA << ' ';
2631 
2632   if (isa<GlobalAlias>(GIS))
2633     Out << "alias ";
2634   else if (isa<GlobalIFunc>(GIS))
2635     Out << "ifunc ";
2636   else
2637     llvm_unreachable("Not an alias or ifunc!");
2638 
2639   TypePrinter.print(GIS->getValueType(), Out);
2640 
2641   Out << ", ";
2642 
2643   const Constant *IS = GIS->getIndirectSymbol();
2644 
2645   if (!IS) {
2646     TypePrinter.print(GIS->getType(), Out);
2647     Out << " <<NULL ALIASEE>>";
2648   } else {
2649     writeOperand(IS, !isa<ConstantExpr>(IS));
2650   }
2651 
2652   printInfoComment(*GIS);
2653   Out << '\n';
2654 }
2655 
2656 void AssemblyWriter::printComdat(const Comdat *C) {
2657   C->print(Out);
2658 }
2659 
2660 void AssemblyWriter::printTypeIdentities() {
2661   if (TypePrinter.NumberedTypes.empty() &&
2662       TypePrinter.NamedTypes.empty())
2663     return;
2664 
2665   Out << '\n';
2666 
2667   // We know all the numbers that each type is used and we know that it is a
2668   // dense assignment.  Convert the map to an index table.
2669   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2670   for (DenseMap<StructType*, unsigned>::iterator I =
2671        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2672        I != E; ++I) {
2673     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2674     NumberedTypes[I->second] = I->first;
2675   }
2676 
2677   // Emit all numbered types.
2678   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2679     Out << '%' << i << " = type ";
2680 
2681     // Make sure we print out at least one level of the type structure, so
2682     // that we do not get %2 = type %2
2683     TypePrinter.printStructBody(NumberedTypes[i], Out);
2684     Out << '\n';
2685   }
2686 
2687   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2688     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2689     Out << " = type ";
2690 
2691     // Make sure we print out at least one level of the type structure, so
2692     // that we do not get %FILE = type %FILE
2693     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2694     Out << '\n';
2695   }
2696 }
2697 
2698 /// printFunction - Print all aspects of a function.
2699 void AssemblyWriter::printFunction(const Function *F) {
2700   // Print out the return type and name.
2701   Out << '\n';
2702 
2703   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2704 
2705   if (F->isMaterializable())
2706     Out << "; Materializable\n";
2707 
2708   const AttributeList &Attrs = F->getAttributes();
2709   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
2710     AttributeSet AS = Attrs.getFnAttributes();
2711     std::string AttrStr;
2712 
2713     for (const Attribute &Attr : AS) {
2714       if (!Attr.isStringAttribute()) {
2715         if (!AttrStr.empty()) AttrStr += ' ';
2716         AttrStr += Attr.getAsString();
2717       }
2718     }
2719 
2720     if (!AttrStr.empty())
2721       Out << "; Function Attrs: " << AttrStr << '\n';
2722   }
2723 
2724   Machine.incorporateFunction(F);
2725 
2726   if (F->isDeclaration()) {
2727     Out << "declare";
2728     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2729     F->getAllMetadata(MDs);
2730     printMetadataAttachments(MDs, " ");
2731     Out << ' ';
2732   } else
2733     Out << "define ";
2734 
2735   Out << getLinkagePrintName(F->getLinkage());
2736   PrintDSOLocation(*F, Out);
2737   PrintVisibility(F->getVisibility(), Out);
2738   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2739 
2740   // Print the calling convention.
2741   if (F->getCallingConv() != CallingConv::C) {
2742     PrintCallingConv(F->getCallingConv(), Out);
2743     Out << " ";
2744   }
2745 
2746   FunctionType *FT = F->getFunctionType();
2747   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
2748     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
2749   TypePrinter.print(F->getReturnType(), Out);
2750   Out << ' ';
2751   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2752   Out << '(';
2753 
2754   // Loop over the arguments, printing them...
2755   if (F->isDeclaration() && !IsForDebug) {
2756     // We're only interested in the type here - don't print argument names.
2757     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2758       // Insert commas as we go... the first arg doesn't get a comma
2759       if (I)
2760         Out << ", ";
2761       // Output type...
2762       TypePrinter.print(FT->getParamType(I), Out);
2763 
2764       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
2765       if (ArgAttrs.hasAttributes())
2766         Out << ' ' << ArgAttrs.getAsString();
2767     }
2768   } else {
2769     // The arguments are meaningful here, print them in detail.
2770     for (const Argument &Arg : F->args()) {
2771       // Insert commas as we go... the first arg doesn't get a comma
2772       if (Arg.getArgNo() != 0)
2773         Out << ", ";
2774       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
2775     }
2776   }
2777 
2778   // Finish printing arguments...
2779   if (FT->isVarArg()) {
2780     if (FT->getNumParams()) Out << ", ";
2781     Out << "...";  // Output varargs portion of signature!
2782   }
2783   Out << ')';
2784   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
2785   if (!UA.empty())
2786     Out << ' ' << UA;
2787   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
2788     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2789   if (F->hasSection()) {
2790     Out << " section \"";
2791     PrintEscapedString(F->getSection(), Out);
2792     Out << '"';
2793   }
2794   maybePrintComdat(Out, *F);
2795   if (F->getAlignment())
2796     Out << " align " << F->getAlignment();
2797   if (F->hasGC())
2798     Out << " gc \"" << F->getGC() << '"';
2799   if (F->hasPrefixData()) {
2800     Out << " prefix ";
2801     writeOperand(F->getPrefixData(), true);
2802   }
2803   if (F->hasPrologueData()) {
2804     Out << " prologue ";
2805     writeOperand(F->getPrologueData(), true);
2806   }
2807   if (F->hasPersonalityFn()) {
2808     Out << " personality ";
2809     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2810   }
2811 
2812   if (F->isDeclaration()) {
2813     Out << '\n';
2814   } else {
2815     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2816     F->getAllMetadata(MDs);
2817     printMetadataAttachments(MDs, " ");
2818 
2819     Out << " {";
2820     // Output all of the function's basic blocks.
2821     for (const BasicBlock &BB : *F)
2822       printBasicBlock(&BB);
2823 
2824     // Output the function's use-lists.
2825     printUseLists(F);
2826 
2827     Out << "}\n";
2828   }
2829 
2830   Machine.purgeFunction();
2831 }
2832 
2833 /// printArgument - This member is called for every argument that is passed into
2834 /// the function.  Simply print it out
2835 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
2836   // Output type...
2837   TypePrinter.print(Arg->getType(), Out);
2838 
2839   // Output parameter attributes list
2840   if (Attrs.hasAttributes())
2841     Out << ' ' << Attrs.getAsString();
2842 
2843   // Output name, if available...
2844   if (Arg->hasName()) {
2845     Out << ' ';
2846     PrintLLVMName(Out, Arg);
2847   }
2848 }
2849 
2850 /// printBasicBlock - This member is called for each basic block in a method.
2851 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2852   if (BB->hasName()) {              // Print out the label if it exists...
2853     Out << "\n";
2854     PrintLLVMName(Out, BB->getName(), LabelPrefix);
2855     Out << ':';
2856   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
2857     Out << "\n; <label>:";
2858     int Slot = Machine.getLocalSlot(BB);
2859     if (Slot != -1)
2860       Out << Slot << ":";
2861     else
2862       Out << "<badref>";
2863   }
2864 
2865   if (!BB->getParent()) {
2866     Out.PadToColumn(50);
2867     Out << "; Error: Block without parent!";
2868   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
2869     // Output predecessors for the block.
2870     Out.PadToColumn(50);
2871     Out << ";";
2872     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2873 
2874     if (PI == PE) {
2875       Out << " No predecessors!";
2876     } else {
2877       Out << " preds = ";
2878       writeOperand(*PI, false);
2879       for (++PI; PI != PE; ++PI) {
2880         Out << ", ";
2881         writeOperand(*PI, false);
2882       }
2883     }
2884   }
2885 
2886   Out << "\n";
2887 
2888   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2889 
2890   // Output all of the instructions in the basic block...
2891   for (const Instruction &I : *BB) {
2892     printInstructionLine(I);
2893   }
2894 
2895   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2896 }
2897 
2898 /// printInstructionLine - Print an instruction and a newline character.
2899 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2900   printInstruction(I);
2901   Out << '\n';
2902 }
2903 
2904 /// printGCRelocateComment - print comment after call to the gc.relocate
2905 /// intrinsic indicating base and derived pointer names.
2906 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
2907   Out << " ; (";
2908   writeOperand(Relocate.getBasePtr(), false);
2909   Out << ", ";
2910   writeOperand(Relocate.getDerivedPtr(), false);
2911   Out << ")";
2912 }
2913 
2914 /// printInfoComment - Print a little comment after the instruction indicating
2915 /// which slot it occupies.
2916 void AssemblyWriter::printInfoComment(const Value &V) {
2917   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
2918     printGCRelocateComment(*Relocate);
2919 
2920   if (AnnotationWriter)
2921     AnnotationWriter->printInfoComment(V, Out);
2922 }
2923 
2924 // This member is called for each Instruction in a function..
2925 void AssemblyWriter::printInstruction(const Instruction &I) {
2926   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2927 
2928   // Print out indentation for an instruction.
2929   Out << "  ";
2930 
2931   // Print out name if it exists...
2932   if (I.hasName()) {
2933     PrintLLVMName(Out, &I);
2934     Out << " = ";
2935   } else if (!I.getType()->isVoidTy()) {
2936     // Print out the def slot taken.
2937     int SlotNum = Machine.getLocalSlot(&I);
2938     if (SlotNum == -1)
2939       Out << "<badref> = ";
2940     else
2941       Out << '%' << SlotNum << " = ";
2942   }
2943 
2944   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2945     if (CI->isMustTailCall())
2946       Out << "musttail ";
2947     else if (CI->isTailCall())
2948       Out << "tail ";
2949     else if (CI->isNoTailCall())
2950       Out << "notail ";
2951   }
2952 
2953   // Print out the opcode...
2954   Out << I.getOpcodeName();
2955 
2956   // If this is an atomic load or store, print out the atomic marker.
2957   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
2958       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2959     Out << " atomic";
2960 
2961   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2962     Out << " weak";
2963 
2964   // If this is a volatile operation, print out the volatile marker.
2965   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
2966       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2967       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2968       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2969     Out << " volatile";
2970 
2971   // Print out optimization information.
2972   WriteOptimizationInfo(Out, &I);
2973 
2974   // Print out the compare instruction predicates
2975   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2976     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
2977 
2978   // Print out the atomicrmw operation
2979   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2980     writeAtomicRMWOperation(Out, RMWI->getOperation());
2981 
2982   // Print out the type of the operands...
2983   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2984 
2985   // Special case conditional branches to swizzle the condition out to the front
2986   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2987     const BranchInst &BI(cast<BranchInst>(I));
2988     Out << ' ';
2989     writeOperand(BI.getCondition(), true);
2990     Out << ", ";
2991     writeOperand(BI.getSuccessor(0), true);
2992     Out << ", ";
2993     writeOperand(BI.getSuccessor(1), true);
2994 
2995   } else if (isa<SwitchInst>(I)) {
2996     const SwitchInst& SI(cast<SwitchInst>(I));
2997     // Special case switch instruction to get formatting nice and correct.
2998     Out << ' ';
2999     writeOperand(SI.getCondition(), true);
3000     Out << ", ";
3001     writeOperand(SI.getDefaultDest(), true);
3002     Out << " [";
3003     for (auto Case : SI.cases()) {
3004       Out << "\n    ";
3005       writeOperand(Case.getCaseValue(), true);
3006       Out << ", ";
3007       writeOperand(Case.getCaseSuccessor(), true);
3008     }
3009     Out << "\n  ]";
3010   } else if (isa<IndirectBrInst>(I)) {
3011     // Special case indirectbr instruction to get formatting nice and correct.
3012     Out << ' ';
3013     writeOperand(Operand, true);
3014     Out << ", [";
3015 
3016     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3017       if (i != 1)
3018         Out << ", ";
3019       writeOperand(I.getOperand(i), true);
3020     }
3021     Out << ']';
3022   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3023     Out << ' ';
3024     TypePrinter.print(I.getType(), Out);
3025     Out << ' ';
3026 
3027     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3028       if (op) Out << ", ";
3029       Out << "[ ";
3030       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3031       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3032     }
3033   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3034     Out << ' ';
3035     writeOperand(I.getOperand(0), true);
3036     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3037       Out << ", " << *i;
3038   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3039     Out << ' ';
3040     writeOperand(I.getOperand(0), true); Out << ", ";
3041     writeOperand(I.getOperand(1), true);
3042     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3043       Out << ", " << *i;
3044   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3045     Out << ' ';
3046     TypePrinter.print(I.getType(), Out);
3047     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3048       Out << '\n';
3049 
3050     if (LPI->isCleanup())
3051       Out << "          cleanup";
3052 
3053     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3054       if (i != 0 || LPI->isCleanup()) Out << "\n";
3055       if (LPI->isCatch(i))
3056         Out << "          catch ";
3057       else
3058         Out << "          filter ";
3059 
3060       writeOperand(LPI->getClause(i), true);
3061     }
3062   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3063     Out << " within ";
3064     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3065     Out << " [";
3066     unsigned Op = 0;
3067     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3068       if (Op > 0)
3069         Out << ", ";
3070       writeOperand(PadBB, /*PrintType=*/true);
3071       ++Op;
3072     }
3073     Out << "] unwind ";
3074     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3075       writeOperand(UnwindDest, /*PrintType=*/true);
3076     else
3077       Out << "to caller";
3078   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3079     Out << " within ";
3080     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3081     Out << " [";
3082     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3083          ++Op) {
3084       if (Op > 0)
3085         Out << ", ";
3086       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3087     }
3088     Out << ']';
3089   } else if (isa<ReturnInst>(I) && !Operand) {
3090     Out << " void";
3091   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3092     Out << " from ";
3093     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3094 
3095     Out << " to ";
3096     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3097   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3098     Out << " from ";
3099     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3100 
3101     Out << " unwind ";
3102     if (CRI->hasUnwindDest())
3103       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3104     else
3105       Out << "to caller";
3106   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3107     // Print the calling convention being used.
3108     if (CI->getCallingConv() != CallingConv::C) {
3109       Out << " ";
3110       PrintCallingConv(CI->getCallingConv(), Out);
3111     }
3112 
3113     Operand = CI->getCalledValue();
3114     FunctionType *FTy = CI->getFunctionType();
3115     Type *RetTy = FTy->getReturnType();
3116     const AttributeList &PAL = CI->getAttributes();
3117 
3118     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3119       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3120 
3121     // If possible, print out the short form of the call instruction.  We can
3122     // only do this if the first argument is a pointer to a nonvararg function,
3123     // and if the return type is not a pointer to a function.
3124     //
3125     Out << ' ';
3126     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3127     Out << ' ';
3128     writeOperand(Operand, false);
3129     Out << '(';
3130     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3131       if (op > 0)
3132         Out << ", ";
3133       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3134     }
3135 
3136     // Emit an ellipsis if this is a musttail call in a vararg function.  This
3137     // is only to aid readability, musttail calls forward varargs by default.
3138     if (CI->isMustTailCall() && CI->getParent() &&
3139         CI->getParent()->getParent() &&
3140         CI->getParent()->getParent()->isVarArg())
3141       Out << ", ...";
3142 
3143     Out << ')';
3144     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3145       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3146 
3147     writeOperandBundles(CI);
3148   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3149     Operand = II->getCalledValue();
3150     FunctionType *FTy = II->getFunctionType();
3151     Type *RetTy = FTy->getReturnType();
3152     const AttributeList &PAL = II->getAttributes();
3153 
3154     // Print the calling convention being used.
3155     if (II->getCallingConv() != CallingConv::C) {
3156       Out << " ";
3157       PrintCallingConv(II->getCallingConv(), Out);
3158     }
3159 
3160     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3161       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3162 
3163     // If possible, print out the short form of the invoke instruction. We can
3164     // only do this if the first argument is a pointer to a nonvararg function,
3165     // and if the return type is not a pointer to a function.
3166     //
3167     Out << ' ';
3168     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3169     Out << ' ';
3170     writeOperand(Operand, false);
3171     Out << '(';
3172     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3173       if (op)
3174         Out << ", ";
3175       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3176     }
3177 
3178     Out << ')';
3179     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3180       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3181 
3182     writeOperandBundles(II);
3183 
3184     Out << "\n          to ";
3185     writeOperand(II->getNormalDest(), true);
3186     Out << " unwind ";
3187     writeOperand(II->getUnwindDest(), true);
3188   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3189     Out << ' ';
3190     if (AI->isUsedWithInAlloca())
3191       Out << "inalloca ";
3192     if (AI->isSwiftError())
3193       Out << "swifterror ";
3194     TypePrinter.print(AI->getAllocatedType(), Out);
3195 
3196     // Explicitly write the array size if the code is broken, if it's an array
3197     // allocation, or if the type is not canonical for scalar allocations.  The
3198     // latter case prevents the type from mutating when round-tripping through
3199     // assembly.
3200     if (!AI->getArraySize() || AI->isArrayAllocation() ||
3201         !AI->getArraySize()->getType()->isIntegerTy(32)) {
3202       Out << ", ";
3203       writeOperand(AI->getArraySize(), true);
3204     }
3205     if (AI->getAlignment()) {
3206       Out << ", align " << AI->getAlignment();
3207     }
3208 
3209     unsigned AddrSpace = AI->getType()->getAddressSpace();
3210     if (AddrSpace != 0) {
3211       Out << ", addrspace(" << AddrSpace << ')';
3212     }
3213   } else if (isa<CastInst>(I)) {
3214     if (Operand) {
3215       Out << ' ';
3216       writeOperand(Operand, true);   // Work with broken code
3217     }
3218     Out << " to ";
3219     TypePrinter.print(I.getType(), Out);
3220   } else if (isa<VAArgInst>(I)) {
3221     if (Operand) {
3222       Out << ' ';
3223       writeOperand(Operand, true);   // Work with broken code
3224     }
3225     Out << ", ";
3226     TypePrinter.print(I.getType(), Out);
3227   } else if (Operand) {   // Print the normal way.
3228     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3229       Out << ' ';
3230       TypePrinter.print(GEP->getSourceElementType(), Out);
3231       Out << ',';
3232     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3233       Out << ' ';
3234       TypePrinter.print(LI->getType(), Out);
3235       Out << ',';
3236     }
3237 
3238     // PrintAllTypes - Instructions who have operands of all the same type
3239     // omit the type from all but the first operand.  If the instruction has
3240     // different type operands (for example br), then they are all printed.
3241     bool PrintAllTypes = false;
3242     Type *TheType = Operand->getType();
3243 
3244     // Select, Store and ShuffleVector always print all types.
3245     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3246         || isa<ReturnInst>(I)) {
3247       PrintAllTypes = true;
3248     } else {
3249       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3250         Operand = I.getOperand(i);
3251         // note that Operand shouldn't be null, but the test helps make dump()
3252         // more tolerant of malformed IR
3253         if (Operand && Operand->getType() != TheType) {
3254           PrintAllTypes = true;    // We have differing types!  Print them all!
3255           break;
3256         }
3257       }
3258     }
3259 
3260     if (!PrintAllTypes) {
3261       Out << ' ';
3262       TypePrinter.print(TheType, Out);
3263     }
3264 
3265     Out << ' ';
3266     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3267       if (i) Out << ", ";
3268       writeOperand(I.getOperand(i), PrintAllTypes);
3269     }
3270   }
3271 
3272   // Print atomic ordering/alignment for memory operations
3273   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3274     if (LI->isAtomic())
3275       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
3276     if (LI->getAlignment())
3277       Out << ", align " << LI->getAlignment();
3278   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3279     if (SI->isAtomic())
3280       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
3281     if (SI->getAlignment())
3282       Out << ", align " << SI->getAlignment();
3283   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3284     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
3285                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
3286   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3287     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
3288                 RMWI->getSyncScopeID());
3289   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3290     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
3291   }
3292 
3293   // Print Metadata info.
3294   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3295   I.getAllMetadata(InstMD);
3296   printMetadataAttachments(InstMD, ", ");
3297 
3298   // Print a nice comment.
3299   printInfoComment(I);
3300 }
3301 
3302 void AssemblyWriter::printMetadataAttachments(
3303     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3304     StringRef Separator) {
3305   if (MDs.empty())
3306     return;
3307 
3308   if (MDNames.empty())
3309     MDs[0].second->getContext().getMDKindNames(MDNames);
3310 
3311   for (const auto &I : MDs) {
3312     unsigned Kind = I.first;
3313     Out << Separator;
3314     if (Kind < MDNames.size()) {
3315       Out << "!";
3316       printMetadataIdentifier(MDNames[Kind], Out);
3317     } else
3318       Out << "!<unknown kind #" << Kind << ">";
3319     Out << ' ';
3320     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3321   }
3322 }
3323 
3324 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3325   Out << '!' << Slot << " = ";
3326   printMDNodeBody(Node);
3327   Out << "\n";
3328 }
3329 
3330 void AssemblyWriter::writeAllMDNodes() {
3331   SmallVector<const MDNode *, 16> Nodes;
3332   Nodes.resize(Machine.mdn_size());
3333   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3334        I != E; ++I)
3335     Nodes[I->second] = cast<MDNode>(I->first);
3336 
3337   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3338     writeMDNode(i, Nodes[i]);
3339   }
3340 }
3341 
3342 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3343   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3344 }
3345 
3346 void AssemblyWriter::writeAllAttributeGroups() {
3347   std::vector<std::pair<AttributeSet, unsigned>> asVec;
3348   asVec.resize(Machine.as_size());
3349 
3350   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3351        I != E; ++I)
3352     asVec[I->second] = *I;
3353 
3354   for (const auto &I : asVec)
3355     Out << "attributes #" << I.second << " = { "
3356         << I.first.getAsString(true) << " }\n";
3357 }
3358 
3359 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3360   bool IsInFunction = Machine.getFunction();
3361   if (IsInFunction)
3362     Out << "  ";
3363 
3364   Out << "uselistorder";
3365   if (const BasicBlock *BB =
3366           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3367     Out << "_bb ";
3368     writeOperand(BB->getParent(), false);
3369     Out << ", ";
3370     writeOperand(BB, false);
3371   } else {
3372     Out << " ";
3373     writeOperand(Order.V, true);
3374   }
3375   Out << ", { ";
3376 
3377   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3378   Out << Order.Shuffle[0];
3379   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3380     Out << ", " << Order.Shuffle[I];
3381   Out << " }\n";
3382 }
3383 
3384 void AssemblyWriter::printUseLists(const Function *F) {
3385   auto hasMore =
3386       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3387   if (!hasMore())
3388     // Nothing to do.
3389     return;
3390 
3391   Out << "\n; uselistorder directives\n";
3392   while (hasMore()) {
3393     printUseListOrder(UseListOrders.back());
3394     UseListOrders.pop_back();
3395   }
3396 }
3397 
3398 //===----------------------------------------------------------------------===//
3399 //                       External Interface declarations
3400 //===----------------------------------------------------------------------===//
3401 
3402 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3403                      bool ShouldPreserveUseListOrder,
3404                      bool IsForDebug) const {
3405   SlotTracker SlotTable(this->getParent());
3406   formatted_raw_ostream OS(ROS);
3407   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
3408                    IsForDebug,
3409                    ShouldPreserveUseListOrder);
3410   W.printFunction(this);
3411 }
3412 
3413 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3414                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3415   SlotTracker SlotTable(this);
3416   formatted_raw_ostream OS(ROS);
3417   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3418                    ShouldPreserveUseListOrder);
3419   W.printModule(this);
3420 }
3421 
3422 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3423   SlotTracker SlotTable(getParent());
3424   formatted_raw_ostream OS(ROS);
3425   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3426   W.printNamedMDNode(this);
3427 }
3428 
3429 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3430                         bool IsForDebug) const {
3431   Optional<SlotTracker> LocalST;
3432   SlotTracker *SlotTable;
3433   if (auto *ST = MST.getMachine())
3434     SlotTable = ST;
3435   else {
3436     LocalST.emplace(getParent());
3437     SlotTable = &*LocalST;
3438   }
3439 
3440   formatted_raw_ostream OS(ROS);
3441   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
3442   W.printNamedMDNode(this);
3443 }
3444 
3445 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3446   PrintLLVMName(ROS, getName(), ComdatPrefix);
3447   ROS << " = comdat ";
3448 
3449   switch (getSelectionKind()) {
3450   case Comdat::Any:
3451     ROS << "any";
3452     break;
3453   case Comdat::ExactMatch:
3454     ROS << "exactmatch";
3455     break;
3456   case Comdat::Largest:
3457     ROS << "largest";
3458     break;
3459   case Comdat::NoDuplicates:
3460     ROS << "noduplicates";
3461     break;
3462   case Comdat::SameSize:
3463     ROS << "samesize";
3464     break;
3465   }
3466 
3467   ROS << '\n';
3468 }
3469 
3470 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
3471   TypePrinting TP;
3472   TP.print(const_cast<Type*>(this), OS);
3473 
3474   if (NoDetails)
3475     return;
3476 
3477   // If the type is a named struct type, print the body as well.
3478   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3479     if (!STy->isLiteral()) {
3480       OS << " = type ";
3481       TP.printStructBody(STy, OS);
3482     }
3483 }
3484 
3485 static bool isReferencingMDNode(const Instruction &I) {
3486   if (const auto *CI = dyn_cast<CallInst>(&I))
3487     if (Function *F = CI->getCalledFunction())
3488       if (F->isIntrinsic())
3489         for (auto &Op : I.operands())
3490           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3491             if (isa<MDNode>(V->getMetadata()))
3492               return true;
3493   return false;
3494 }
3495 
3496 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3497   bool ShouldInitializeAllMetadata = false;
3498   if (auto *I = dyn_cast<Instruction>(this))
3499     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3500   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3501     ShouldInitializeAllMetadata = true;
3502 
3503   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3504   print(ROS, MST, IsForDebug);
3505 }
3506 
3507 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3508                   bool IsForDebug) const {
3509   formatted_raw_ostream OS(ROS);
3510   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3511   SlotTracker &SlotTable =
3512       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3513   auto incorporateFunction = [&](const Function *F) {
3514     if (F)
3515       MST.incorporateFunction(*F);
3516   };
3517 
3518   if (const Instruction *I = dyn_cast<Instruction>(this)) {
3519     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3520     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3521     W.printInstruction(*I);
3522   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3523     incorporateFunction(BB->getParent());
3524     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3525     W.printBasicBlock(BB);
3526   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3527     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3528     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3529       W.printGlobal(V);
3530     else if (const Function *F = dyn_cast<Function>(GV))
3531       W.printFunction(F);
3532     else
3533       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
3534   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3535     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3536   } else if (const Constant *C = dyn_cast<Constant>(this)) {
3537     TypePrinting TypePrinter;
3538     TypePrinter.print(C->getType(), OS);
3539     OS << ' ';
3540     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3541   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3542     this->printAsOperand(OS, /* PrintType */ true, MST);
3543   } else {
3544     llvm_unreachable("Unknown value to print out!");
3545   }
3546 }
3547 
3548 /// Print without a type, skipping the TypePrinting object.
3549 ///
3550 /// \return \c true iff printing was successful.
3551 static bool printWithoutType(const Value &V, raw_ostream &O,
3552                              SlotTracker *Machine, const Module *M) {
3553   if (V.hasName() || isa<GlobalValue>(V) ||
3554       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3555     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3556     return true;
3557   }
3558   return false;
3559 }
3560 
3561 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3562                                ModuleSlotTracker &MST) {
3563   TypePrinting TypePrinter;
3564   if (const Module *M = MST.getModule())
3565     TypePrinter.incorporateTypes(*M);
3566   if (PrintType) {
3567     TypePrinter.print(V.getType(), O);
3568     O << ' ';
3569   }
3570 
3571   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3572                          MST.getModule());
3573 }
3574 
3575 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3576                            const Module *M) const {
3577   if (!M)
3578     M = getModuleFromVal(this);
3579 
3580   if (!PrintType)
3581     if (printWithoutType(*this, O, nullptr, M))
3582       return;
3583 
3584   SlotTracker Machine(
3585       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3586   ModuleSlotTracker MST(Machine, M);
3587   printAsOperandImpl(*this, O, PrintType, MST);
3588 }
3589 
3590 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3591                            ModuleSlotTracker &MST) const {
3592   if (!PrintType)
3593     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3594       return;
3595 
3596   printAsOperandImpl(*this, O, PrintType, MST);
3597 }
3598 
3599 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3600                               ModuleSlotTracker &MST, const Module *M,
3601                               bool OnlyAsOperand) {
3602   formatted_raw_ostream OS(ROS);
3603 
3604   TypePrinting TypePrinter;
3605   if (M)
3606     TypePrinter.incorporateTypes(*M);
3607 
3608   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3609                          /* FromValue */ true);
3610 
3611   auto *N = dyn_cast<MDNode>(&MD);
3612   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
3613     return;
3614 
3615   OS << " = ";
3616   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3617 }
3618 
3619 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3620   ModuleSlotTracker MST(M, isa<MDNode>(this));
3621   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3622 }
3623 
3624 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3625                               const Module *M) const {
3626   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3627 }
3628 
3629 void Metadata::print(raw_ostream &OS, const Module *M,
3630                      bool /*IsForDebug*/) const {
3631   ModuleSlotTracker MST(M, isa<MDNode>(this));
3632   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3633 }
3634 
3635 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3636                      const Module *M, bool /*IsForDebug*/) const {
3637   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3638 }
3639 
3640 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3641 // Value::dump - allow easy printing of Values from the debugger.
3642 LLVM_DUMP_METHOD
3643 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3644 
3645 // Type::dump - allow easy printing of Types from the debugger.
3646 LLVM_DUMP_METHOD
3647 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3648 
3649 // Module::dump() - Allow printing of Modules from the debugger.
3650 LLVM_DUMP_METHOD
3651 void Module::dump() const {
3652   print(dbgs(), nullptr,
3653         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3654 }
3655 
3656 // \brief Allow printing of Comdats from the debugger.
3657 LLVM_DUMP_METHOD
3658 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3659 
3660 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3661 LLVM_DUMP_METHOD
3662 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3663 
3664 LLVM_DUMP_METHOD
3665 void Metadata::dump() const { dump(nullptr); }
3666 
3667 LLVM_DUMP_METHOD
3668 void Metadata::dump(const Module *M) const {
3669   print(dbgs(), M, /*IsForDebug=*/true);
3670   dbgs() << '\n';
3671 }
3672 #endif
3673