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