]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/IR/AsmWriter.cpp
Merge ^/head r316992 through r317215.
[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_GS:     Out << "amdgpu_gs"; break;
336   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
337   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
338   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
339   }
340 }
341
342 void llvm::PrintEscapedString(StringRef Name, raw_ostream &Out) {
343   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
344     unsigned char C = Name[i];
345     if (isprint(C) && C != '\\' && C != '"')
346       Out << C;
347     else
348       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
349   }
350 }
351
352 enum PrefixType {
353   GlobalPrefix,
354   ComdatPrefix,
355   LabelPrefix,
356   LocalPrefix,
357   NoPrefix
358 };
359
360 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
361   assert(!Name.empty() && "Cannot get empty name!");
362
363   // Scan the name to see if it needs quotes first.
364   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
365   if (!NeedsQuotes) {
366     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
367       // By making this unsigned, the value passed in to isalnum will always be
368       // in the range 0-255.  This is important when building with MSVC because
369       // its implementation will assert.  This situation can arise when dealing
370       // with UTF-8 multibyte characters.
371       unsigned char C = Name[i];
372       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
373           C != '_') {
374         NeedsQuotes = true;
375         break;
376       }
377     }
378   }
379
380   // If we didn't need any quotes, just write out the name in one blast.
381   if (!NeedsQuotes) {
382     OS << Name;
383     return;
384   }
385
386   // Okay, we need quotes.  Output the quotes and escape any scary characters as
387   // needed.
388   OS << '"';
389   PrintEscapedString(Name, OS);
390   OS << '"';
391 }
392
393 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
394 /// (if the string only contains simple characters) or is surrounded with ""'s
395 /// (if it has special chars in it). Print it out.
396 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
397   switch (Prefix) {
398   case NoPrefix:
399     break;
400   case GlobalPrefix:
401     OS << '@';
402     break;
403   case ComdatPrefix:
404     OS << '$';
405     break;
406   case LabelPrefix:
407     break;
408   case LocalPrefix:
409     OS << '%';
410     break;
411   }
412   printLLVMNameWithoutPrefix(OS, Name);
413 }
414
415 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
416 /// (if the string only contains simple characters) or is surrounded with ""'s
417 /// (if it has special chars in it). Print it out.
418 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
419   PrintLLVMName(OS, V->getName(),
420                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
421 }
422
423
424 namespace {
425 class TypePrinting {
426   TypePrinting(const TypePrinting &) = delete;
427   void operator=(const TypePrinting&) = delete;
428 public:
429
430   /// NamedTypes - The named types that are used by the current module.
431   TypeFinder NamedTypes;
432
433   /// NumberedTypes - The numbered types, along with their value.
434   DenseMap<StructType*, unsigned> NumberedTypes;
435
436   TypePrinting() = default;
437
438   void incorporateTypes(const Module &M);
439
440   void print(Type *Ty, raw_ostream &OS);
441
442   void printStructBody(StructType *Ty, raw_ostream &OS);
443 };
444 } // namespace
445
446 void TypePrinting::incorporateTypes(const Module &M) {
447   NamedTypes.run(M, false);
448
449   // The list of struct types we got back includes all the struct types, split
450   // the unnamed ones out to a numbering and remove the anonymous structs.
451   unsigned NextNumber = 0;
452
453   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
454   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
455     StructType *STy = *I;
456
457     // Ignore anonymous types.
458     if (STy->isLiteral())
459       continue;
460
461     if (STy->getName().empty())
462       NumberedTypes[STy] = NextNumber++;
463     else
464       *NextToUse++ = STy;
465   }
466
467   NamedTypes.erase(NextToUse, NamedTypes.end());
468 }
469
470
471 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
472 /// use of type names or up references to shorten the type name where possible.
473 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
474   switch (Ty->getTypeID()) {
475   case Type::VoidTyID:      OS << "void"; return;
476   case Type::HalfTyID:      OS << "half"; return;
477   case Type::FloatTyID:     OS << "float"; return;
478   case Type::DoubleTyID:    OS << "double"; return;
479   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
480   case Type::FP128TyID:     OS << "fp128"; return;
481   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
482   case Type::LabelTyID:     OS << "label"; return;
483   case Type::MetadataTyID:  OS << "metadata"; return;
484   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
485   case Type::TokenTyID:     OS << "token"; return;
486   case Type::IntegerTyID:
487     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
488     return;
489
490   case Type::FunctionTyID: {
491     FunctionType *FTy = cast<FunctionType>(Ty);
492     print(FTy->getReturnType(), OS);
493     OS << " (";
494     for (FunctionType::param_iterator I = FTy->param_begin(),
495          E = FTy->param_end(); I != E; ++I) {
496       if (I != FTy->param_begin())
497         OS << ", ";
498       print(*I, OS);
499     }
500     if (FTy->isVarArg()) {
501       if (FTy->getNumParams()) OS << ", ";
502       OS << "...";
503     }
504     OS << ')';
505     return;
506   }
507   case Type::StructTyID: {
508     StructType *STy = cast<StructType>(Ty);
509
510     if (STy->isLiteral())
511       return printStructBody(STy, OS);
512
513     if (!STy->getName().empty())
514       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
515
516     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
517     if (I != NumberedTypes.end())
518       OS << '%' << I->second;
519     else  // Not enumerated, print the hex address.
520       OS << "%\"type " << STy << '\"';
521     return;
522   }
523   case Type::PointerTyID: {
524     PointerType *PTy = cast<PointerType>(Ty);
525     print(PTy->getElementType(), OS);
526     if (unsigned AddressSpace = PTy->getAddressSpace())
527       OS << " addrspace(" << AddressSpace << ')';
528     OS << '*';
529     return;
530   }
531   case Type::ArrayTyID: {
532     ArrayType *ATy = cast<ArrayType>(Ty);
533     OS << '[' << ATy->getNumElements() << " x ";
534     print(ATy->getElementType(), OS);
535     OS << ']';
536     return;
537   }
538   case Type::VectorTyID: {
539     VectorType *PTy = cast<VectorType>(Ty);
540     OS << "<" << PTy->getNumElements() << " x ";
541     print(PTy->getElementType(), OS);
542     OS << '>';
543     return;
544   }
545   }
546   llvm_unreachable("Invalid TypeID");
547 }
548
549 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
550   if (STy->isOpaque()) {
551     OS << "opaque";
552     return;
553   }
554
555   if (STy->isPacked())
556     OS << '<';
557
558   if (STy->getNumElements() == 0) {
559     OS << "{}";
560   } else {
561     StructType::element_iterator I = STy->element_begin();
562     OS << "{ ";
563     print(*I++, OS);
564     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
565       OS << ", ";
566       print(*I, OS);
567     }
568
569     OS << " }";
570   }
571   if (STy->isPacked())
572     OS << '>';
573 }
574
575 namespace llvm {
576 //===----------------------------------------------------------------------===//
577 // SlotTracker Class: Enumerate slot numbers for unnamed values
578 //===----------------------------------------------------------------------===//
579 /// This class provides computation of slot numbers for LLVM Assembly writing.
580 ///
581 class SlotTracker {
582 public:
583   /// ValueMap - A mapping of Values to slot numbers.
584   typedef DenseMap<const Value*, unsigned> ValueMap;
585
586 private:
587   /// TheModule - The module for which we are holding slot numbers.
588   const Module* TheModule;
589
590   /// TheFunction - The function for which we are holding slot numbers.
591   const Function* TheFunction;
592   bool FunctionProcessed;
593   bool ShouldInitializeAllMetadata;
594
595   /// mMap - The slot map for the module level data.
596   ValueMap mMap;
597   unsigned mNext;
598
599   /// fMap - The slot map for the function level data.
600   ValueMap fMap;
601   unsigned fNext;
602
603   /// mdnMap - Map for MDNodes.
604   DenseMap<const MDNode*, unsigned> mdnMap;
605   unsigned mdnNext;
606
607   /// asMap - The slot map for attribute sets.
608   DenseMap<AttributeSet, unsigned> asMap;
609   unsigned asNext;
610 public:
611   /// Construct from a module.
612   ///
613   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
614   /// functions, giving correct numbering for metadata referenced only from
615   /// within a function (even if no functions have been initialized).
616   explicit SlotTracker(const Module *M,
617                        bool ShouldInitializeAllMetadata = false);
618   /// Construct from a function, starting out in incorp state.
619   ///
620   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
621   /// functions, giving correct numbering for metadata referenced only from
622   /// within a function (even if no functions have been initialized).
623   explicit SlotTracker(const Function *F,
624                        bool ShouldInitializeAllMetadata = false);
625
626   /// Return the slot number of the specified value in it's type
627   /// plane.  If something is not in the SlotTracker, return -1.
628   int getLocalSlot(const Value *V);
629   int getGlobalSlot(const GlobalValue *V);
630   int getMetadataSlot(const MDNode *N);
631   int getAttributeGroupSlot(AttributeSet AS);
632
633   /// If you'd like to deal with a function instead of just a module, use
634   /// this method to get its data into the SlotTracker.
635   void incorporateFunction(const Function *F) {
636     TheFunction = F;
637     FunctionProcessed = false;
638   }
639
640   const Function *getFunction() const { return TheFunction; }
641
642   /// After calling incorporateFunction, use this method to remove the
643   /// most recently incorporated function from the SlotTracker. This
644   /// will reset the state of the machine back to just the module contents.
645   void purgeFunction();
646
647   /// MDNode map iterators.
648   typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
649   mdn_iterator mdn_begin() { return mdnMap.begin(); }
650   mdn_iterator mdn_end() { return mdnMap.end(); }
651   unsigned mdn_size() const { return mdnMap.size(); }
652   bool mdn_empty() const { return mdnMap.empty(); }
653
654   /// AttributeSet map iterators.
655   typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
656   as_iterator as_begin()   { return asMap.begin(); }
657   as_iterator as_end()     { return asMap.end(); }
658   unsigned as_size() const { return asMap.size(); }
659   bool as_empty() const    { return asMap.empty(); }
660
661   /// This function does the actual initialization.
662   inline void initialize();
663
664   // Implementation Details
665 private:
666   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
667   void CreateModuleSlot(const GlobalValue *V);
668
669   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
670   void CreateMetadataSlot(const MDNode *N);
671
672   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
673   void CreateFunctionSlot(const Value *V);
674
675   /// \brief Insert the specified AttributeSet into the slot table.
676   void CreateAttributeSetSlot(AttributeSet AS);
677
678   /// Add all of the module level global variables (and their initializers)
679   /// and function declarations, but not the contents of those functions.
680   void processModule();
681
682   /// Add all of the functions arguments, basic blocks, and instructions.
683   void processFunction();
684
685   /// Add the metadata directly attached to a GlobalObject.
686   void processGlobalObjectMetadata(const GlobalObject &GO);
687
688   /// Add all of the metadata from a function.
689   void processFunctionMetadata(const Function &F);
690
691   /// Add all of the metadata from an instruction.
692   void processInstructionMetadata(const Instruction &I);
693
694   SlotTracker(const SlotTracker &) = delete;
695   void operator=(const SlotTracker &) = delete;
696 };
697 } // namespace llvm
698
699 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
700                                      const Function *F)
701     : M(M), F(F), Machine(&Machine) {}
702
703 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
704                                      bool ShouldInitializeAllMetadata)
705     : ShouldCreateStorage(M),
706       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
707
708 ModuleSlotTracker::~ModuleSlotTracker() {}
709
710 SlotTracker *ModuleSlotTracker::getMachine() {
711   if (!ShouldCreateStorage)
712     return Machine;
713
714   ShouldCreateStorage = false;
715   MachineStorage =
716       llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
717   Machine = MachineStorage.get();
718   return Machine;
719 }
720
721 void ModuleSlotTracker::incorporateFunction(const Function &F) {
722   // Using getMachine() may lazily create the slot tracker.
723   if (!getMachine())
724     return;
725
726   // Nothing to do if this is the right function already.
727   if (this->F == &F)
728     return;
729   if (this->F)
730     Machine->purgeFunction();
731   Machine->incorporateFunction(&F);
732   this->F = &F;
733 }
734
735 int ModuleSlotTracker::getLocalSlot(const Value *V) {
736   assert(F && "No function incorporated");
737   return Machine->getLocalSlot(V);
738 }
739
740 static SlotTracker *createSlotTracker(const Value *V) {
741   if (const Argument *FA = dyn_cast<Argument>(V))
742     return new SlotTracker(FA->getParent());
743
744   if (const Instruction *I = dyn_cast<Instruction>(V))
745     if (I->getParent())
746       return new SlotTracker(I->getParent()->getParent());
747
748   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
749     return new SlotTracker(BB->getParent());
750
751   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
752     return new SlotTracker(GV->getParent());
753
754   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
755     return new SlotTracker(GA->getParent());
756
757   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
758     return new SlotTracker(GIF->getParent());
759
760   if (const Function *Func = dyn_cast<Function>(V))
761     return new SlotTracker(Func);
762
763   return nullptr;
764 }
765
766 #if 0
767 #define ST_DEBUG(X) dbgs() << X
768 #else
769 #define ST_DEBUG(X)
770 #endif
771
772 // Module level constructor. Causes the contents of the Module (sans functions)
773 // to be added to the slot table.
774 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
775     : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
776       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
777       fNext(0), mdnNext(0), asNext(0) {}
778
779 // Function level constructor. Causes the contents of the Module and the one
780 // function provided to be added to the slot table.
781 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
782     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
783       FunctionProcessed(false),
784       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
785       fNext(0), mdnNext(0), asNext(0) {}
786
787 inline void SlotTracker::initialize() {
788   if (TheModule) {
789     processModule();
790     TheModule = nullptr; ///< Prevent re-processing next time we're called.
791   }
792
793   if (TheFunction && !FunctionProcessed)
794     processFunction();
795 }
796
797 // Iterate through all the global variables, functions, and global
798 // variable initializers and create slots for them.
799 void SlotTracker::processModule() {
800   ST_DEBUG("begin processModule!\n");
801
802   // Add all of the unnamed global variables to the value table.
803   for (const GlobalVariable &Var : TheModule->globals()) {
804     if (!Var.hasName())
805       CreateModuleSlot(&Var);
806     processGlobalObjectMetadata(Var);
807   }
808
809   for (const GlobalAlias &A : TheModule->aliases()) {
810     if (!A.hasName())
811       CreateModuleSlot(&A);
812   }
813
814   for (const GlobalIFunc &I : TheModule->ifuncs()) {
815     if (!I.hasName())
816       CreateModuleSlot(&I);
817   }
818
819   // Add metadata used by named metadata.
820   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
821     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
822       CreateMetadataSlot(NMD.getOperand(i));
823   }
824
825   for (const Function &F : *TheModule) {
826     if (!F.hasName())
827       // Add all the unnamed functions to the table.
828       CreateModuleSlot(&F);
829
830     if (ShouldInitializeAllMetadata)
831       processFunctionMetadata(F);
832
833     // Add all the function attributes to the table.
834     // FIXME: Add attributes of other objects?
835     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
836     if (FnAttrs.hasAttributes())
837       CreateAttributeSetSlot(FnAttrs);
838   }
839
840   ST_DEBUG("end processModule!\n");
841 }
842
843 // Process the arguments, basic blocks, and instructions  of a function.
844 void SlotTracker::processFunction() {
845   ST_DEBUG("begin processFunction!\n");
846   fNext = 0;
847
848   // Process function metadata if it wasn't hit at the module-level.
849   if (!ShouldInitializeAllMetadata)
850     processFunctionMetadata(*TheFunction);
851
852   // Add all the function arguments with no names.
853   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
854       AE = TheFunction->arg_end(); AI != AE; ++AI)
855     if (!AI->hasName())
856       CreateFunctionSlot(&*AI);
857
858   ST_DEBUG("Inserting Instructions:\n");
859
860   // Add all of the basic blocks and instructions with no names.
861   for (auto &BB : *TheFunction) {
862     if (!BB.hasName())
863       CreateFunctionSlot(&BB);
864
865     for (auto &I : BB) {
866       if (!I.getType()->isVoidTy() && !I.hasName())
867         CreateFunctionSlot(&I);
868
869       // We allow direct calls to any llvm.foo function here, because the
870       // target may not be linked into the optimizer.
871       if (auto CS = ImmutableCallSite(&I)) {
872         // Add all the call attributes to the table.
873         AttributeSet Attrs = CS.getAttributes().getFnAttributes();
874         if (Attrs.hasAttributes())
875           CreateAttributeSetSlot(Attrs);
876       }
877     }
878   }
879
880   FunctionProcessed = true;
881
882   ST_DEBUG("end processFunction!\n");
883 }
884
885 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
886   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
887   GO.getAllMetadata(MDs);
888   for (auto &MD : MDs)
889     CreateMetadataSlot(MD.second);
890 }
891
892 void SlotTracker::processFunctionMetadata(const Function &F) {
893   processGlobalObjectMetadata(F);
894   for (auto &BB : F) {
895     for (auto &I : BB)
896       processInstructionMetadata(I);
897   }
898 }
899
900 void SlotTracker::processInstructionMetadata(const Instruction &I) {
901   // Process metadata used directly by intrinsics.
902   if (const CallInst *CI = dyn_cast<CallInst>(&I))
903     if (Function *F = CI->getCalledFunction())
904       if (F->isIntrinsic())
905         for (auto &Op : I.operands())
906           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
907             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
908               CreateMetadataSlot(N);
909
910   // Process metadata attached to this instruction.
911   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
912   I.getAllMetadata(MDs);
913   for (auto &MD : MDs)
914     CreateMetadataSlot(MD.second);
915 }
916
917 /// Clean up after incorporating a function. This is the only way to get out of
918 /// the function incorporation state that affects get*Slot/Create*Slot. Function
919 /// incorporation state is indicated by TheFunction != 0.
920 void SlotTracker::purgeFunction() {
921   ST_DEBUG("begin purgeFunction!\n");
922   fMap.clear(); // Simply discard the function level map
923   TheFunction = nullptr;
924   FunctionProcessed = false;
925   ST_DEBUG("end purgeFunction!\n");
926 }
927
928 /// getGlobalSlot - Get the slot number of a global value.
929 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
930   // Check for uninitialized state and do lazy initialization.
931   initialize();
932
933   // Find the value in the module map
934   ValueMap::iterator MI = mMap.find(V);
935   return MI == mMap.end() ? -1 : (int)MI->second;
936 }
937
938 /// getMetadataSlot - Get the slot number of a MDNode.
939 int SlotTracker::getMetadataSlot(const MDNode *N) {
940   // Check for uninitialized state and do lazy initialization.
941   initialize();
942
943   // Find the MDNode in the module map
944   mdn_iterator MI = mdnMap.find(N);
945   return MI == mdnMap.end() ? -1 : (int)MI->second;
946 }
947
948
949 /// getLocalSlot - Get the slot number for a value that is local to a function.
950 int SlotTracker::getLocalSlot(const Value *V) {
951   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
952
953   // Check for uninitialized state and do lazy initialization.
954   initialize();
955
956   ValueMap::iterator FI = fMap.find(V);
957   return FI == fMap.end() ? -1 : (int)FI->second;
958 }
959
960 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
961   // Check for uninitialized state and do lazy initialization.
962   initialize();
963
964   // Find the AttributeSet in the module map.
965   as_iterator AI = asMap.find(AS);
966   return AI == asMap.end() ? -1 : (int)AI->second;
967 }
968
969 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
970 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
971   assert(V && "Can't insert a null Value into SlotTracker!");
972   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
973   assert(!V->hasName() && "Doesn't need a slot!");
974
975   unsigned DestSlot = mNext++;
976   mMap[V] = DestSlot;
977
978   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
979            DestSlot << " [");
980   // G = Global, F = Function, A = Alias, I = IFunc, o = other
981   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
982             (isa<Function>(V) ? 'F' :
983              (isa<GlobalAlias>(V) ? 'A' :
984               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
985 }
986
987 /// CreateSlot - Create a new slot for the specified value if it has no name.
988 void SlotTracker::CreateFunctionSlot(const Value *V) {
989   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
990
991   unsigned DestSlot = fNext++;
992   fMap[V] = DestSlot;
993
994   // G = Global, F = Function, o = other
995   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
996            DestSlot << " [o]\n");
997 }
998
999 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1000 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1001   assert(N && "Can't insert a null Value into SlotTracker!");
1002
1003   unsigned DestSlot = mdnNext;
1004   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1005     return;
1006   ++mdnNext;
1007
1008   // Recursively add any MDNodes referenced by operands.
1009   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1010     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1011       CreateMetadataSlot(Op);
1012 }
1013
1014 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1015   assert(AS.hasAttributes() && "Doesn't need a slot!");
1016
1017   as_iterator I = asMap.find(AS);
1018   if (I != asMap.end())
1019     return;
1020
1021   unsigned DestSlot = asNext++;
1022   asMap[AS] = DestSlot;
1023 }
1024
1025 //===----------------------------------------------------------------------===//
1026 // AsmWriter Implementation
1027 //===----------------------------------------------------------------------===//
1028
1029 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1030                                    TypePrinting *TypePrinter,
1031                                    SlotTracker *Machine,
1032                                    const Module *Context);
1033
1034 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1035                                    TypePrinting *TypePrinter,
1036                                    SlotTracker *Machine, const Module *Context,
1037                                    bool FromValue = false);
1038
1039 static void writeAtomicRMWOperation(raw_ostream &Out,
1040                                     AtomicRMWInst::BinOp Op) {
1041   switch (Op) {
1042   default: Out << " <unknown operation " << Op << ">"; break;
1043   case AtomicRMWInst::Xchg: Out << " xchg"; break;
1044   case AtomicRMWInst::Add:  Out << " add"; break;
1045   case AtomicRMWInst::Sub:  Out << " sub"; break;
1046   case AtomicRMWInst::And:  Out << " and"; break;
1047   case AtomicRMWInst::Nand: Out << " nand"; break;
1048   case AtomicRMWInst::Or:   Out << " or"; break;
1049   case AtomicRMWInst::Xor:  Out << " xor"; break;
1050   case AtomicRMWInst::Max:  Out << " max"; break;
1051   case AtomicRMWInst::Min:  Out << " min"; break;
1052   case AtomicRMWInst::UMax: Out << " umax"; break;
1053   case AtomicRMWInst::UMin: Out << " umin"; break;
1054   }
1055 }
1056
1057 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1058   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1059     // Unsafe algebra implies all the others, no need to write them all out
1060     if (FPO->hasUnsafeAlgebra())
1061       Out << " fast";
1062     else {
1063       if (FPO->hasNoNaNs())
1064         Out << " nnan";
1065       if (FPO->hasNoInfs())
1066         Out << " ninf";
1067       if (FPO->hasNoSignedZeros())
1068         Out << " nsz";
1069       if (FPO->hasAllowReciprocal())
1070         Out << " arcp";
1071       if (FPO->hasAllowContract())
1072         Out << " contract";
1073     }
1074   }
1075
1076   if (const OverflowingBinaryOperator *OBO =
1077         dyn_cast<OverflowingBinaryOperator>(U)) {
1078     if (OBO->hasNoUnsignedWrap())
1079       Out << " nuw";
1080     if (OBO->hasNoSignedWrap())
1081       Out << " nsw";
1082   } else if (const PossiblyExactOperator *Div =
1083                dyn_cast<PossiblyExactOperator>(U)) {
1084     if (Div->isExact())
1085       Out << " exact";
1086   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1087     if (GEP->isInBounds())
1088       Out << " inbounds";
1089   }
1090 }
1091
1092 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1093                                   TypePrinting &TypePrinter,
1094                                   SlotTracker *Machine,
1095                                   const Module *Context) {
1096   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1097     if (CI->getType()->isIntegerTy(1)) {
1098       Out << (CI->getZExtValue() ? "true" : "false");
1099       return;
1100     }
1101     Out << CI->getValue();
1102     return;
1103   }
1104
1105   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1106     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle() ||
1107         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble()) {
1108       // We would like to output the FP constant value in exponential notation,
1109       // but we cannot do this if doing so will lose precision.  Check here to
1110       // make sure that we only output it in exponential format if we can parse
1111       // the value back and get the same value.
1112       //
1113       bool ignored;
1114       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble();
1115       bool isInf = CFP->getValueAPF().isInfinity();
1116       bool isNaN = CFP->getValueAPF().isNaN();
1117       if (!isInf && !isNaN) {
1118         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1119                                 CFP->getValueAPF().convertToFloat();
1120         SmallString<128> StrVal;
1121         raw_svector_ostream(StrVal) << Val;
1122
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         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1128             ((StrVal[0] == '-' || StrVal[0] == '+') &&
1129              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1130           // Reparse stringized version!
1131           if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1132             Out << StrVal;
1133             return;
1134           }
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 = CFP->getValueAPF();
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 = CFP->getValueAPF().bitcastToAPInt();
1157     if (&CFP->getValueAPF().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 (&CFP->getValueAPF().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 (&CFP->getValueAPF().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 (&CFP->getValueAPF().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   Out << ")";
1724 }
1725
1726 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1727                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1728                                 const Module *Context) {
1729   Out << "!DILexicalBlock(";
1730   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1731   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1732   Printer.printMetadata("file", N->getRawFile());
1733   Printer.printInt("line", N->getLine());
1734   Printer.printInt("column", N->getColumn());
1735   Out << ")";
1736 }
1737
1738 static void writeDILexicalBlockFile(raw_ostream &Out,
1739                                     const DILexicalBlockFile *N,
1740                                     TypePrinting *TypePrinter,
1741                                     SlotTracker *Machine,
1742                                     const Module *Context) {
1743   Out << "!DILexicalBlockFile(";
1744   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1745   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1746   Printer.printMetadata("file", N->getRawFile());
1747   Printer.printInt("discriminator", N->getDiscriminator(),
1748                    /* ShouldSkipZero */ false);
1749   Out << ")";
1750 }
1751
1752 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1753                              TypePrinting *TypePrinter, SlotTracker *Machine,
1754                              const Module *Context) {
1755   Out << "!DINamespace(";
1756   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1757   Printer.printString("name", N->getName());
1758   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1759   Printer.printMetadata("file", N->getRawFile());
1760   Printer.printInt("line", N->getLine());
1761   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
1762   Out << ")";
1763 }
1764
1765 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1766                          TypePrinting *TypePrinter, SlotTracker *Machine,
1767                          const Module *Context) {
1768   Out << "!DIMacro(";
1769   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1770   Printer.printMacinfoType(N);
1771   Printer.printInt("line", N->getLine());
1772   Printer.printString("name", N->getName());
1773   Printer.printString("value", N->getValue());
1774   Out << ")";
1775 }
1776
1777 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1778                              TypePrinting *TypePrinter, SlotTracker *Machine,
1779                              const Module *Context) {
1780   Out << "!DIMacroFile(";
1781   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1782   Printer.printInt("line", N->getLine());
1783   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1784   Printer.printMetadata("nodes", N->getRawElements());
1785   Out << ")";
1786 }
1787
1788 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1789                           TypePrinting *TypePrinter, SlotTracker *Machine,
1790                           const Module *Context) {
1791   Out << "!DIModule(";
1792   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1793   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1794   Printer.printString("name", N->getName());
1795   Printer.printString("configMacros", N->getConfigurationMacros());
1796   Printer.printString("includePath", N->getIncludePath());
1797   Printer.printString("isysroot", N->getISysRoot());
1798   Out << ")";
1799 }
1800
1801
1802 static void writeDITemplateTypeParameter(raw_ostream &Out,
1803                                          const DITemplateTypeParameter *N,
1804                                          TypePrinting *TypePrinter,
1805                                          SlotTracker *Machine,
1806                                          const Module *Context) {
1807   Out << "!DITemplateTypeParameter(";
1808   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1809   Printer.printString("name", N->getName());
1810   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1811   Out << ")";
1812 }
1813
1814 static void writeDITemplateValueParameter(raw_ostream &Out,
1815                                           const DITemplateValueParameter *N,
1816                                           TypePrinting *TypePrinter,
1817                                           SlotTracker *Machine,
1818                                           const Module *Context) {
1819   Out << "!DITemplateValueParameter(";
1820   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1821   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1822     Printer.printTag(N);
1823   Printer.printString("name", N->getName());
1824   Printer.printMetadata("type", N->getRawType());
1825   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1826   Out << ")";
1827 }
1828
1829 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1830                                   TypePrinting *TypePrinter,
1831                                   SlotTracker *Machine, const Module *Context) {
1832   Out << "!DIGlobalVariable(";
1833   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1834   Printer.printString("name", N->getName());
1835   Printer.printString("linkageName", N->getLinkageName());
1836   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1837   Printer.printMetadata("file", N->getRawFile());
1838   Printer.printInt("line", N->getLine());
1839   Printer.printMetadata("type", N->getRawType());
1840   Printer.printBool("isLocal", N->isLocalToUnit());
1841   Printer.printBool("isDefinition", N->isDefinition());
1842   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1843   Printer.printInt("align", N->getAlignInBits());
1844   Out << ")";
1845 }
1846
1847 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1848                                  TypePrinting *TypePrinter,
1849                                  SlotTracker *Machine, const Module *Context) {
1850   Out << "!DILocalVariable(";
1851   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1852   Printer.printString("name", N->getName());
1853   Printer.printInt("arg", N->getArg());
1854   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1855   Printer.printMetadata("file", N->getRawFile());
1856   Printer.printInt("line", N->getLine());
1857   Printer.printMetadata("type", N->getRawType());
1858   Printer.printDIFlags("flags", N->getFlags());
1859   Printer.printInt("align", N->getAlignInBits());
1860   Out << ")";
1861 }
1862
1863 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1864                               TypePrinting *TypePrinter, SlotTracker *Machine,
1865                               const Module *Context) {
1866   Out << "!DIExpression(";
1867   FieldSeparator FS;
1868   if (N->isValid()) {
1869     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1870       auto OpStr = dwarf::OperationEncodingString(I->getOp());
1871       assert(!OpStr.empty() && "Expected valid opcode");
1872
1873       Out << FS << OpStr;
1874       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1875         Out << FS << I->getArg(A);
1876     }
1877   } else {
1878     for (const auto &I : N->getElements())
1879       Out << FS << I;
1880   }
1881   Out << ")";
1882 }
1883
1884 static void writeDIGlobalVariableExpression(raw_ostream &Out,
1885                                             const DIGlobalVariableExpression *N,
1886                                             TypePrinting *TypePrinter,
1887                                             SlotTracker *Machine,
1888                                             const Module *Context) {
1889   Out << "!DIGlobalVariableExpression(";
1890   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1891   Printer.printMetadata("var", N->getVariable());
1892   Printer.printMetadata("expr", N->getExpression());
1893   Out << ")";
1894 }
1895
1896 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1897                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1898                                 const Module *Context) {
1899   Out << "!DIObjCProperty(";
1900   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1901   Printer.printString("name", N->getName());
1902   Printer.printMetadata("file", N->getRawFile());
1903   Printer.printInt("line", N->getLine());
1904   Printer.printString("setter", N->getSetterName());
1905   Printer.printString("getter", N->getGetterName());
1906   Printer.printInt("attributes", N->getAttributes());
1907   Printer.printMetadata("type", N->getRawType());
1908   Out << ")";
1909 }
1910
1911 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1912                                   TypePrinting *TypePrinter,
1913                                   SlotTracker *Machine, const Module *Context) {
1914   Out << "!DIImportedEntity(";
1915   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1916   Printer.printTag(N);
1917   Printer.printString("name", N->getName());
1918   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1919   Printer.printMetadata("entity", N->getRawEntity());
1920   Printer.printInt("line", N->getLine());
1921   Out << ")";
1922 }
1923
1924
1925 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1926                                     TypePrinting *TypePrinter,
1927                                     SlotTracker *Machine,
1928                                     const Module *Context) {
1929   if (Node->isDistinct())
1930     Out << "distinct ";
1931   else if (Node->isTemporary())
1932     Out << "<temporary!> "; // Handle broken code.
1933
1934   switch (Node->getMetadataID()) {
1935   default:
1936     llvm_unreachable("Expected uniquable MDNode");
1937 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1938   case Metadata::CLASS##Kind:                                                  \
1939     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
1940     break;
1941 #include "llvm/IR/Metadata.def"
1942   }
1943 }
1944
1945 // Full implementation of printing a Value as an operand with support for
1946 // TypePrinting, etc.
1947 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1948                                    TypePrinting *TypePrinter,
1949                                    SlotTracker *Machine,
1950                                    const Module *Context) {
1951   if (V->hasName()) {
1952     PrintLLVMName(Out, V);
1953     return;
1954   }
1955
1956   const Constant *CV = dyn_cast<Constant>(V);
1957   if (CV && !isa<GlobalValue>(CV)) {
1958     assert(TypePrinter && "Constants require TypePrinting!");
1959     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1960     return;
1961   }
1962
1963   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1964     Out << "asm ";
1965     if (IA->hasSideEffects())
1966       Out << "sideeffect ";
1967     if (IA->isAlignStack())
1968       Out << "alignstack ";
1969     // We don't emit the AD_ATT dialect as it's the assumed default.
1970     if (IA->getDialect() == InlineAsm::AD_Intel)
1971       Out << "inteldialect ";
1972     Out << '"';
1973     PrintEscapedString(IA->getAsmString(), Out);
1974     Out << "\", \"";
1975     PrintEscapedString(IA->getConstraintString(), Out);
1976     Out << '"';
1977     return;
1978   }
1979
1980   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1981     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1982                            Context, /* FromValue */ true);
1983     return;
1984   }
1985
1986   char Prefix = '%';
1987   int Slot;
1988   // If we have a SlotTracker, use it.
1989   if (Machine) {
1990     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1991       Slot = Machine->getGlobalSlot(GV);
1992       Prefix = '@';
1993     } else {
1994       Slot = Machine->getLocalSlot(V);
1995
1996       // If the local value didn't succeed, then we may be referring to a value
1997       // from a different function.  Translate it, as this can happen when using
1998       // address of blocks.
1999       if (Slot == -1)
2000         if ((Machine = createSlotTracker(V))) {
2001           Slot = Machine->getLocalSlot(V);
2002           delete Machine;
2003         }
2004     }
2005   } else if ((Machine = createSlotTracker(V))) {
2006     // Otherwise, create one to get the # and then destroy it.
2007     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2008       Slot = Machine->getGlobalSlot(GV);
2009       Prefix = '@';
2010     } else {
2011       Slot = Machine->getLocalSlot(V);
2012     }
2013     delete Machine;
2014     Machine = nullptr;
2015   } else {
2016     Slot = -1;
2017   }
2018
2019   if (Slot != -1)
2020     Out << Prefix << Slot;
2021   else
2022     Out << "<badref>";
2023 }
2024
2025 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2026                                    TypePrinting *TypePrinter,
2027                                    SlotTracker *Machine, const Module *Context,
2028                                    bool FromValue) {
2029   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2030     std::unique_ptr<SlotTracker> MachineStorage;
2031     if (!Machine) {
2032       MachineStorage = make_unique<SlotTracker>(Context);
2033       Machine = MachineStorage.get();
2034     }
2035     int Slot = Machine->getMetadataSlot(N);
2036     if (Slot == -1)
2037       // Give the pointer value instead of "badref", since this comes up all
2038       // the time when debugging.
2039       Out << "<" << N << ">";
2040     else
2041       Out << '!' << Slot;
2042     return;
2043   }
2044
2045   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2046     Out << "!\"";
2047     PrintEscapedString(MDS->getString(), Out);
2048     Out << '"';
2049     return;
2050   }
2051
2052   auto *V = cast<ValueAsMetadata>(MD);
2053   assert(TypePrinter && "TypePrinter required for metadata values");
2054   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2055          "Unexpected function-local metadata outside of value argument");
2056
2057   TypePrinter->print(V->getValue()->getType(), Out);
2058   Out << ' ';
2059   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2060 }
2061
2062 namespace {
2063 class AssemblyWriter {
2064   formatted_raw_ostream &Out;
2065   const Module *TheModule;
2066   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2067   SlotTracker &Machine;
2068   TypePrinting TypePrinter;
2069   AssemblyAnnotationWriter *AnnotationWriter;
2070   SetVector<const Comdat *> Comdats;
2071   bool IsForDebug;
2072   bool ShouldPreserveUseListOrder;
2073   UseListOrderStack UseListOrders;
2074   SmallVector<StringRef, 8> MDNames;
2075
2076 public:
2077   /// Construct an AssemblyWriter with an external SlotTracker
2078   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2079                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2080                  bool ShouldPreserveUseListOrder = false);
2081
2082   void printMDNodeBody(const MDNode *MD);
2083   void printNamedMDNode(const NamedMDNode *NMD);
2084
2085   void printModule(const Module *M);
2086
2087   void writeOperand(const Value *Op, bool PrintType);
2088   void writeParamOperand(const Value *Operand, AttributeList Attrs,
2089                          unsigned Idx);
2090   void writeOperandBundles(ImmutableCallSite CS);
2091   void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2092   void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2093                           AtomicOrdering FailureOrdering,
2094                           SynchronizationScope SynchScope);
2095
2096   void writeAllMDNodes();
2097   void writeMDNode(unsigned Slot, const MDNode *Node);
2098   void writeAllAttributeGroups();
2099
2100   void printTypeIdentities();
2101   void printGlobal(const GlobalVariable *GV);
2102   void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2103   void printComdat(const Comdat *C);
2104   void printFunction(const Function *F);
2105   void printArgument(const Argument *FA, AttributeList Attrs, unsigned Idx);
2106   void printBasicBlock(const BasicBlock *BB);
2107   void printInstructionLine(const Instruction &I);
2108   void printInstruction(const Instruction &I);
2109
2110   void printUseListOrder(const UseListOrder &Order);
2111   void printUseLists(const Function *F);
2112
2113 private:
2114   /// \brief Print out metadata attachments.
2115   void printMetadataAttachments(
2116       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2117       StringRef Separator);
2118
2119   // printInfoComment - Print a little comment after the instruction indicating
2120   // which slot it occupies.
2121   void printInfoComment(const Value &V);
2122
2123   // printGCRelocateComment - print comment after call to the gc.relocate
2124   // intrinsic indicating base and derived pointer names.
2125   void printGCRelocateComment(const GCRelocateInst &Relocate);
2126 };
2127 } // namespace
2128
2129 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2130                                const Module *M, AssemblyAnnotationWriter *AAW,
2131                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2132     : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2133       IsForDebug(IsForDebug),
2134       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2135   if (!TheModule)
2136     return;
2137   TypePrinter.incorporateTypes(*TheModule);
2138   for (const GlobalObject &GO : TheModule->global_objects())
2139     if (const Comdat *C = GO.getComdat())
2140       Comdats.insert(C);
2141 }
2142
2143 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2144   if (!Operand) {
2145     Out << "<null operand!>";
2146     return;
2147   }
2148   if (PrintType) {
2149     TypePrinter.print(Operand->getType(), Out);
2150     Out << ' ';
2151   }
2152   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2153 }
2154
2155 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2156                                  SynchronizationScope SynchScope) {
2157   if (Ordering == AtomicOrdering::NotAtomic)
2158     return;
2159
2160   switch (SynchScope) {
2161   case SingleThread: Out << " singlethread"; break;
2162   case CrossThread: break;
2163   }
2164
2165   Out << " " << toIRString(Ordering);
2166 }
2167
2168 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2169                                         AtomicOrdering FailureOrdering,
2170                                         SynchronizationScope SynchScope) {
2171   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2172          FailureOrdering != AtomicOrdering::NotAtomic);
2173
2174   switch (SynchScope) {
2175   case SingleThread: Out << " singlethread"; break;
2176   case CrossThread: break;
2177   }
2178
2179   Out << " " << toIRString(SuccessOrdering);
2180   Out << " " << toIRString(FailureOrdering);
2181 }
2182
2183 void AssemblyWriter::writeParamOperand(const Value *Operand,
2184                                        AttributeList Attrs, unsigned Idx) {
2185   if (!Operand) {
2186     Out << "<null operand!>";
2187     return;
2188   }
2189
2190   // Print the type
2191   TypePrinter.print(Operand->getType(), Out);
2192   // Print parameter attributes list
2193   if (Attrs.hasAttributes(Idx))
2194     Out << ' ' << Attrs.getAsString(Idx);
2195   Out << ' ';
2196   // Print the operand
2197   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2198 }
2199
2200 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2201   if (!CS.hasOperandBundles())
2202     return;
2203
2204   Out << " [ ";
2205
2206   bool FirstBundle = true;
2207   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2208     OperandBundleUse BU = CS.getOperandBundleAt(i);
2209
2210     if (!FirstBundle)
2211       Out << ", ";
2212     FirstBundle = false;
2213
2214     Out << '"';
2215     PrintEscapedString(BU.getTagName(), Out);
2216     Out << '"';
2217
2218     Out << '(';
2219
2220     bool FirstInput = true;
2221     for (const auto &Input : BU.Inputs) {
2222       if (!FirstInput)
2223         Out << ", ";
2224       FirstInput = false;
2225
2226       TypePrinter.print(Input->getType(), Out);
2227       Out << " ";
2228       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2229     }
2230
2231     Out << ')';
2232   }
2233
2234   Out << " ]";
2235 }
2236
2237 void AssemblyWriter::printModule(const Module *M) {
2238   Machine.initialize();
2239
2240   if (ShouldPreserveUseListOrder)
2241     UseListOrders = predictUseListOrder(M);
2242
2243   if (!M->getModuleIdentifier().empty() &&
2244       // Don't print the ID if it will start a new line (which would
2245       // require a comment char before it).
2246       M->getModuleIdentifier().find('\n') == std::string::npos)
2247     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2248
2249   if (!M->getSourceFileName().empty()) {
2250     Out << "source_filename = \"";
2251     PrintEscapedString(M->getSourceFileName(), Out);
2252     Out << "\"\n";
2253   }
2254
2255   const std::string &DL = M->getDataLayoutStr();
2256   if (!DL.empty())
2257     Out << "target datalayout = \"" << DL << "\"\n";
2258   if (!M->getTargetTriple().empty())
2259     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2260
2261   if (!M->getModuleInlineAsm().empty()) {
2262     Out << '\n';
2263
2264     // Split the string into lines, to make it easier to read the .ll file.
2265     StringRef Asm = M->getModuleInlineAsm();
2266     do {
2267       StringRef Front;
2268       std::tie(Front, Asm) = Asm.split('\n');
2269
2270       // We found a newline, print the portion of the asm string from the
2271       // last newline up to this newline.
2272       Out << "module asm \"";
2273       PrintEscapedString(Front, Out);
2274       Out << "\"\n";
2275     } while (!Asm.empty());
2276   }
2277
2278   printTypeIdentities();
2279
2280   // Output all comdats.
2281   if (!Comdats.empty())
2282     Out << '\n';
2283   for (const Comdat *C : Comdats) {
2284     printComdat(C);
2285     if (C != Comdats.back())
2286       Out << '\n';
2287   }
2288
2289   // Output all globals.
2290   if (!M->global_empty()) Out << '\n';
2291   for (const GlobalVariable &GV : M->globals()) {
2292     printGlobal(&GV); Out << '\n';
2293   }
2294
2295   // Output all aliases.
2296   if (!M->alias_empty()) Out << "\n";
2297   for (const GlobalAlias &GA : M->aliases())
2298     printIndirectSymbol(&GA);
2299
2300   // Output all ifuncs.
2301   if (!M->ifunc_empty()) Out << "\n";
2302   for (const GlobalIFunc &GI : M->ifuncs())
2303     printIndirectSymbol(&GI);
2304
2305   // Output global use-lists.
2306   printUseLists(nullptr);
2307
2308   // Output all of the functions.
2309   for (const Function &F : *M)
2310     printFunction(&F);
2311   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2312
2313   // Output all attribute groups.
2314   if (!Machine.as_empty()) {
2315     Out << '\n';
2316     writeAllAttributeGroups();
2317   }
2318
2319   // Output named metadata.
2320   if (!M->named_metadata_empty()) Out << '\n';
2321
2322   for (const NamedMDNode &Node : M->named_metadata())
2323     printNamedMDNode(&Node);
2324
2325   // Output metadata.
2326   if (!Machine.mdn_empty()) {
2327     Out << '\n';
2328     writeAllMDNodes();
2329   }
2330 }
2331
2332 static void printMetadataIdentifier(StringRef Name,
2333                                     formatted_raw_ostream &Out) {
2334   if (Name.empty()) {
2335     Out << "<empty name> ";
2336   } else {
2337     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2338         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2339       Out << Name[0];
2340     else
2341       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2342     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2343       unsigned char C = Name[i];
2344       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2345           C == '.' || C == '_')
2346         Out << C;
2347       else
2348         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2349     }
2350   }
2351 }
2352
2353 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2354   Out << '!';
2355   printMetadataIdentifier(NMD->getName(), Out);
2356   Out << " = !{";
2357   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2358     if (i)
2359       Out << ", ";
2360     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2361     if (Slot == -1)
2362       Out << "<badref>";
2363     else
2364       Out << '!' << Slot;
2365   }
2366   Out << "}\n";
2367 }
2368
2369 static const char *getLinkagePrintName(GlobalValue::LinkageTypes LT) {
2370   switch (LT) {
2371   case GlobalValue::ExternalLinkage:
2372     return "";
2373   case GlobalValue::PrivateLinkage:
2374     return "private ";
2375   case GlobalValue::InternalLinkage:
2376     return "internal ";
2377   case GlobalValue::LinkOnceAnyLinkage:
2378     return "linkonce ";
2379   case GlobalValue::LinkOnceODRLinkage:
2380     return "linkonce_odr ";
2381   case GlobalValue::WeakAnyLinkage:
2382     return "weak ";
2383   case GlobalValue::WeakODRLinkage:
2384     return "weak_odr ";
2385   case GlobalValue::CommonLinkage:
2386     return "common ";
2387   case GlobalValue::AppendingLinkage:
2388     return "appending ";
2389   case GlobalValue::ExternalWeakLinkage:
2390     return "extern_weak ";
2391   case GlobalValue::AvailableExternallyLinkage:
2392     return "available_externally ";
2393   }
2394   llvm_unreachable("invalid linkage");
2395 }
2396
2397 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2398                             formatted_raw_ostream &Out) {
2399   switch (Vis) {
2400   case GlobalValue::DefaultVisibility: break;
2401   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
2402   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2403   }
2404 }
2405
2406 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2407                                  formatted_raw_ostream &Out) {
2408   switch (SCT) {
2409   case GlobalValue::DefaultStorageClass: break;
2410   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2411   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2412   }
2413 }
2414
2415 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2416                                   formatted_raw_ostream &Out) {
2417   switch (TLM) {
2418     case GlobalVariable::NotThreadLocal:
2419       break;
2420     case GlobalVariable::GeneralDynamicTLSModel:
2421       Out << "thread_local ";
2422       break;
2423     case GlobalVariable::LocalDynamicTLSModel:
2424       Out << "thread_local(localdynamic) ";
2425       break;
2426     case GlobalVariable::InitialExecTLSModel:
2427       Out << "thread_local(initialexec) ";
2428       break;
2429     case GlobalVariable::LocalExecTLSModel:
2430       Out << "thread_local(localexec) ";
2431       break;
2432   }
2433 }
2434
2435 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
2436   switch (UA) {
2437   case GlobalVariable::UnnamedAddr::None:
2438     return "";
2439   case GlobalVariable::UnnamedAddr::Local:
2440     return "local_unnamed_addr";
2441   case GlobalVariable::UnnamedAddr::Global:
2442     return "unnamed_addr";
2443   }
2444   llvm_unreachable("Unknown UnnamedAddr");
2445 }
2446
2447 static void maybePrintComdat(formatted_raw_ostream &Out,
2448                              const GlobalObject &GO) {
2449   const Comdat *C = GO.getComdat();
2450   if (!C)
2451     return;
2452
2453   if (isa<GlobalVariable>(GO))
2454     Out << ',';
2455   Out << " comdat";
2456
2457   if (GO.getName() == C->getName())
2458     return;
2459
2460   Out << '(';
2461   PrintLLVMName(Out, C->getName(), ComdatPrefix);
2462   Out << ')';
2463 }
2464
2465 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2466   if (GV->isMaterializable())
2467     Out << "; Materializable\n";
2468
2469   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2470   Out << " = ";
2471
2472   if (!GV->hasInitializer() && GV->hasExternalLinkage())
2473     Out << "external ";
2474
2475   Out << getLinkagePrintName(GV->getLinkage());
2476   PrintVisibility(GV->getVisibility(), Out);
2477   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2478   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2479   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
2480   if (!UA.empty())
2481       Out << UA << ' ';
2482
2483   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2484     Out << "addrspace(" << AddressSpace << ") ";
2485   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2486   Out << (GV->isConstant() ? "constant " : "global ");
2487   TypePrinter.print(GV->getValueType(), Out);
2488
2489   if (GV->hasInitializer()) {
2490     Out << ' ';
2491     writeOperand(GV->getInitializer(), false);
2492   }
2493
2494   if (GV->hasSection()) {
2495     Out << ", section \"";
2496     PrintEscapedString(GV->getSection(), Out);
2497     Out << '"';
2498   }
2499   maybePrintComdat(Out, *GV);
2500   if (GV->getAlignment())
2501     Out << ", align " << GV->getAlignment();
2502
2503   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2504   GV->getAllMetadata(MDs);
2505   printMetadataAttachments(MDs, ", ");
2506
2507   printInfoComment(*GV);
2508 }
2509
2510 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
2511   if (GIS->isMaterializable())
2512     Out << "; Materializable\n";
2513
2514   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
2515   Out << " = ";
2516
2517   Out << getLinkagePrintName(GIS->getLinkage());
2518   PrintVisibility(GIS->getVisibility(), Out);
2519   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
2520   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
2521   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
2522   if (!UA.empty())
2523       Out << UA << ' ';
2524
2525   if (isa<GlobalAlias>(GIS))
2526     Out << "alias ";
2527   else if (isa<GlobalIFunc>(GIS))
2528     Out << "ifunc ";
2529   else
2530     llvm_unreachable("Not an alias or ifunc!");
2531
2532   TypePrinter.print(GIS->getValueType(), Out);
2533
2534   Out << ", ";
2535
2536   const Constant *IS = GIS->getIndirectSymbol();
2537
2538   if (!IS) {
2539     TypePrinter.print(GIS->getType(), Out);
2540     Out << " <<NULL ALIASEE>>";
2541   } else {
2542     writeOperand(IS, !isa<ConstantExpr>(IS));
2543   }
2544
2545   printInfoComment(*GIS);
2546   Out << '\n';
2547 }
2548
2549 void AssemblyWriter::printComdat(const Comdat *C) {
2550   C->print(Out);
2551 }
2552
2553 void AssemblyWriter::printTypeIdentities() {
2554   if (TypePrinter.NumberedTypes.empty() &&
2555       TypePrinter.NamedTypes.empty())
2556     return;
2557
2558   Out << '\n';
2559
2560   // We know all the numbers that each type is used and we know that it is a
2561   // dense assignment.  Convert the map to an index table.
2562   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2563   for (DenseMap<StructType*, unsigned>::iterator I =
2564        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2565        I != E; ++I) {
2566     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2567     NumberedTypes[I->second] = I->first;
2568   }
2569
2570   // Emit all numbered types.
2571   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2572     Out << '%' << i << " = type ";
2573
2574     // Make sure we print out at least one level of the type structure, so
2575     // that we do not get %2 = type %2
2576     TypePrinter.printStructBody(NumberedTypes[i], Out);
2577     Out << '\n';
2578   }
2579
2580   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2581     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2582     Out << " = type ";
2583
2584     // Make sure we print out at least one level of the type structure, so
2585     // that we do not get %FILE = type %FILE
2586     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2587     Out << '\n';
2588   }
2589 }
2590
2591 /// printFunction - Print all aspects of a function.
2592 ///
2593 void AssemblyWriter::printFunction(const Function *F) {
2594   // Print out the return type and name.
2595   Out << '\n';
2596
2597   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2598
2599   if (F->isMaterializable())
2600     Out << "; Materializable\n";
2601
2602   const AttributeList &Attrs = F->getAttributes();
2603   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
2604     AttributeSet AS = Attrs.getFnAttributes();
2605     std::string AttrStr;
2606
2607     for (const Attribute &Attr : AS) {
2608       if (!Attr.isStringAttribute()) {
2609         if (!AttrStr.empty()) AttrStr += ' ';
2610         AttrStr += Attr.getAsString();
2611       }
2612     }
2613
2614     if (!AttrStr.empty())
2615       Out << "; Function Attrs: " << AttrStr << '\n';
2616   }
2617
2618   Machine.incorporateFunction(F);
2619
2620   if (F->isDeclaration()) {
2621     Out << "declare";
2622     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2623     F->getAllMetadata(MDs);
2624     printMetadataAttachments(MDs, " ");
2625     Out << ' ';
2626   } else
2627     Out << "define ";
2628
2629   Out << getLinkagePrintName(F->getLinkage());
2630   PrintVisibility(F->getVisibility(), Out);
2631   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2632
2633   // Print the calling convention.
2634   if (F->getCallingConv() != CallingConv::C) {
2635     PrintCallingConv(F->getCallingConv(), Out);
2636     Out << " ";
2637   }
2638
2639   FunctionType *FT = F->getFunctionType();
2640   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
2641     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
2642   TypePrinter.print(F->getReturnType(), Out);
2643   Out << ' ';
2644   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2645   Out << '(';
2646
2647   // Loop over the arguments, printing them...
2648   if (F->isDeclaration() && !IsForDebug) {
2649     // We're only interested in the type here - don't print argument names.
2650     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2651       // Insert commas as we go... the first arg doesn't get a comma
2652       if (I)
2653         Out << ", ";
2654       // Output type...
2655       TypePrinter.print(FT->getParamType(I), Out);
2656
2657       if (Attrs.hasAttributes(I + 1))
2658         Out << ' ' << Attrs.getAsString(I + 1);
2659     }
2660   } else {
2661     // The arguments are meaningful here, print them in detail.
2662     unsigned Idx = 1;
2663     for (const Argument &Arg : F->args()) {
2664       // Insert commas as we go... the first arg doesn't get a comma
2665       if (Idx != 1)
2666         Out << ", ";
2667       printArgument(&Arg, Attrs, Idx++);
2668     }
2669   }
2670
2671   // Finish printing arguments...
2672   if (FT->isVarArg()) {
2673     if (FT->getNumParams()) Out << ", ";
2674     Out << "...";  // Output varargs portion of signature!
2675   }
2676   Out << ')';
2677   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
2678   if (!UA.empty())
2679     Out << ' ' << UA;
2680   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
2681     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2682   if (F->hasSection()) {
2683     Out << " section \"";
2684     PrintEscapedString(F->getSection(), Out);
2685     Out << '"';
2686   }
2687   maybePrintComdat(Out, *F);
2688   if (F->getAlignment())
2689     Out << " align " << F->getAlignment();
2690   if (F->hasGC())
2691     Out << " gc \"" << F->getGC() << '"';
2692   if (F->hasPrefixData()) {
2693     Out << " prefix ";
2694     writeOperand(F->getPrefixData(), true);
2695   }
2696   if (F->hasPrologueData()) {
2697     Out << " prologue ";
2698     writeOperand(F->getPrologueData(), true);
2699   }
2700   if (F->hasPersonalityFn()) {
2701     Out << " personality ";
2702     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2703   }
2704
2705   if (F->isDeclaration()) {
2706     Out << '\n';
2707   } else {
2708     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2709     F->getAllMetadata(MDs);
2710     printMetadataAttachments(MDs, " ");
2711
2712     Out << " {";
2713     // Output all of the function's basic blocks.
2714     for (const BasicBlock &BB : *F)
2715       printBasicBlock(&BB);
2716
2717     // Output the function's use-lists.
2718     printUseLists(F);
2719
2720     Out << "}\n";
2721   }
2722
2723   Machine.purgeFunction();
2724 }
2725
2726 /// printArgument - This member is called for every argument that is passed into
2727 /// the function.  Simply print it out
2728 ///
2729 void AssemblyWriter::printArgument(const Argument *Arg, AttributeList Attrs,
2730                                    unsigned Idx) {
2731   // Output type...
2732   TypePrinter.print(Arg->getType(), Out);
2733
2734   // Output parameter attributes list
2735   if (Attrs.hasAttributes(Idx))
2736     Out << ' ' << Attrs.getAsString(Idx);
2737
2738   // Output name, if available...
2739   if (Arg->hasName()) {
2740     Out << ' ';
2741     PrintLLVMName(Out, Arg);
2742   }
2743 }
2744
2745 /// printBasicBlock - This member is called for each basic block in a method.
2746 ///
2747 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2748   if (BB->hasName()) {              // Print out the label if it exists...
2749     Out << "\n";
2750     PrintLLVMName(Out, BB->getName(), LabelPrefix);
2751     Out << ':';
2752   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
2753     Out << "\n; <label>:";
2754     int Slot = Machine.getLocalSlot(BB);
2755     if (Slot != -1)
2756       Out << Slot << ":";
2757     else
2758       Out << "<badref>";
2759   }
2760
2761   if (!BB->getParent()) {
2762     Out.PadToColumn(50);
2763     Out << "; Error: Block without parent!";
2764   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
2765     // Output predecessors for the block.
2766     Out.PadToColumn(50);
2767     Out << ";";
2768     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2769
2770     if (PI == PE) {
2771       Out << " No predecessors!";
2772     } else {
2773       Out << " preds = ";
2774       writeOperand(*PI, false);
2775       for (++PI; PI != PE; ++PI) {
2776         Out << ", ";
2777         writeOperand(*PI, false);
2778       }
2779     }
2780   }
2781
2782   Out << "\n";
2783
2784   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2785
2786   // Output all of the instructions in the basic block...
2787   for (const Instruction &I : *BB) {
2788     printInstructionLine(I);
2789   }
2790
2791   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2792 }
2793
2794 /// printInstructionLine - Print an instruction and a newline character.
2795 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2796   printInstruction(I);
2797   Out << '\n';
2798 }
2799
2800 /// printGCRelocateComment - print comment after call to the gc.relocate
2801 /// intrinsic indicating base and derived pointer names.
2802 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
2803   Out << " ; (";
2804   writeOperand(Relocate.getBasePtr(), false);
2805   Out << ", ";
2806   writeOperand(Relocate.getDerivedPtr(), false);
2807   Out << ")";
2808 }
2809
2810 /// printInfoComment - Print a little comment after the instruction indicating
2811 /// which slot it occupies.
2812 ///
2813 void AssemblyWriter::printInfoComment(const Value &V) {
2814   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
2815     printGCRelocateComment(*Relocate);
2816
2817   if (AnnotationWriter)
2818     AnnotationWriter->printInfoComment(V, Out);
2819 }
2820
2821 // This member is called for each Instruction in a function..
2822 void AssemblyWriter::printInstruction(const Instruction &I) {
2823   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2824
2825   // Print out indentation for an instruction.
2826   Out << "  ";
2827
2828   // Print out name if it exists...
2829   if (I.hasName()) {
2830     PrintLLVMName(Out, &I);
2831     Out << " = ";
2832   } else if (!I.getType()->isVoidTy()) {
2833     // Print out the def slot taken.
2834     int SlotNum = Machine.getLocalSlot(&I);
2835     if (SlotNum == -1)
2836       Out << "<badref> = ";
2837     else
2838       Out << '%' << SlotNum << " = ";
2839   }
2840
2841   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2842     if (CI->isMustTailCall())
2843       Out << "musttail ";
2844     else if (CI->isTailCall())
2845       Out << "tail ";
2846     else if (CI->isNoTailCall())
2847       Out << "notail ";
2848   }
2849
2850   // Print out the opcode...
2851   Out << I.getOpcodeName();
2852
2853   // If this is an atomic load or store, print out the atomic marker.
2854   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
2855       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2856     Out << " atomic";
2857
2858   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2859     Out << " weak";
2860
2861   // If this is a volatile operation, print out the volatile marker.
2862   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
2863       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2864       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2865       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2866     Out << " volatile";
2867
2868   // Print out optimization information.
2869   WriteOptimizationInfo(Out, &I);
2870
2871   // Print out the compare instruction predicates
2872   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2873     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
2874
2875   // Print out the atomicrmw operation
2876   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2877     writeAtomicRMWOperation(Out, RMWI->getOperation());
2878
2879   // Print out the type of the operands...
2880   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2881
2882   // Special case conditional branches to swizzle the condition out to the front
2883   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2884     const BranchInst &BI(cast<BranchInst>(I));
2885     Out << ' ';
2886     writeOperand(BI.getCondition(), true);
2887     Out << ", ";
2888     writeOperand(BI.getSuccessor(0), true);
2889     Out << ", ";
2890     writeOperand(BI.getSuccessor(1), true);
2891
2892   } else if (isa<SwitchInst>(I)) {
2893     const SwitchInst& SI(cast<SwitchInst>(I));
2894     // Special case switch instruction to get formatting nice and correct.
2895     Out << ' ';
2896     writeOperand(SI.getCondition(), true);
2897     Out << ", ";
2898     writeOperand(SI.getDefaultDest(), true);
2899     Out << " [";
2900     for (auto Case : SI.cases()) {
2901       Out << "\n    ";
2902       writeOperand(Case.getCaseValue(), true);
2903       Out << ", ";
2904       writeOperand(Case.getCaseSuccessor(), true);
2905     }
2906     Out << "\n  ]";
2907   } else if (isa<IndirectBrInst>(I)) {
2908     // Special case indirectbr instruction to get formatting nice and correct.
2909     Out << ' ';
2910     writeOperand(Operand, true);
2911     Out << ", [";
2912
2913     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2914       if (i != 1)
2915         Out << ", ";
2916       writeOperand(I.getOperand(i), true);
2917     }
2918     Out << ']';
2919   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2920     Out << ' ';
2921     TypePrinter.print(I.getType(), Out);
2922     Out << ' ';
2923
2924     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2925       if (op) Out << ", ";
2926       Out << "[ ";
2927       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2928       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2929     }
2930   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2931     Out << ' ';
2932     writeOperand(I.getOperand(0), true);
2933     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2934       Out << ", " << *i;
2935   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2936     Out << ' ';
2937     writeOperand(I.getOperand(0), true); Out << ", ";
2938     writeOperand(I.getOperand(1), true);
2939     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2940       Out << ", " << *i;
2941   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2942     Out << ' ';
2943     TypePrinter.print(I.getType(), Out);
2944     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2945       Out << '\n';
2946
2947     if (LPI->isCleanup())
2948       Out << "          cleanup";
2949
2950     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2951       if (i != 0 || LPI->isCleanup()) Out << "\n";
2952       if (LPI->isCatch(i))
2953         Out << "          catch ";
2954       else
2955         Out << "          filter ";
2956
2957       writeOperand(LPI->getClause(i), true);
2958     }
2959   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
2960     Out << " within ";
2961     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
2962     Out << " [";
2963     unsigned Op = 0;
2964     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
2965       if (Op > 0)
2966         Out << ", ";
2967       writeOperand(PadBB, /*PrintType=*/true);
2968       ++Op;
2969     }
2970     Out << "] unwind ";
2971     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
2972       writeOperand(UnwindDest, /*PrintType=*/true);
2973     else
2974       Out << "to caller";
2975   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
2976     Out << " within ";
2977     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
2978     Out << " [";
2979     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
2980          ++Op) {
2981       if (Op > 0)
2982         Out << ", ";
2983       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
2984     }
2985     Out << ']';
2986   } else if (isa<ReturnInst>(I) && !Operand) {
2987     Out << " void";
2988   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2989     Out << " from ";
2990     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
2991
2992     Out << " to ";
2993     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
2994   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2995     Out << " from ";
2996     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
2997
2998     Out << " unwind ";
2999     if (CRI->hasUnwindDest())
3000       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3001     else
3002       Out << "to caller";
3003   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3004     // Print the calling convention being used.
3005     if (CI->getCallingConv() != CallingConv::C) {
3006       Out << " ";
3007       PrintCallingConv(CI->getCallingConv(), Out);
3008     }
3009
3010     Operand = CI->getCalledValue();
3011     FunctionType *FTy = CI->getFunctionType();
3012     Type *RetTy = FTy->getReturnType();
3013     const AttributeList &PAL = CI->getAttributes();
3014
3015     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3016       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3017
3018     // If possible, print out the short form of the call instruction.  We can
3019     // only do this if the first argument is a pointer to a nonvararg function,
3020     // and if the return type is not a pointer to a function.
3021     //
3022     Out << ' ';
3023     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3024     Out << ' ';
3025     writeOperand(Operand, false);
3026     Out << '(';
3027     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3028       if (op > 0)
3029         Out << ", ";
3030       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
3031     }
3032
3033     // Emit an ellipsis if this is a musttail call in a vararg function.  This
3034     // is only to aid readability, musttail calls forward varargs by default.
3035     if (CI->isMustTailCall() && CI->getParent() &&
3036         CI->getParent()->getParent() &&
3037         CI->getParent()->getParent()->isVarArg())
3038       Out << ", ...";
3039
3040     Out << ')';
3041     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3042       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3043
3044     writeOperandBundles(CI);
3045
3046   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3047     Operand = II->getCalledValue();
3048     FunctionType *FTy = II->getFunctionType();
3049     Type *RetTy = FTy->getReturnType();
3050     const AttributeList &PAL = II->getAttributes();
3051
3052     // Print the calling convention being used.
3053     if (II->getCallingConv() != CallingConv::C) {
3054       Out << " ";
3055       PrintCallingConv(II->getCallingConv(), Out);
3056     }
3057
3058     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3059       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3060
3061     // If possible, print out the short form of the invoke instruction. We can
3062     // only do this if the first argument is a pointer to a nonvararg function,
3063     // and if the return type is not a pointer to a function.
3064     //
3065     Out << ' ';
3066     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3067     Out << ' ';
3068     writeOperand(Operand, false);
3069     Out << '(';
3070     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3071       if (op)
3072         Out << ", ";
3073       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
3074     }
3075
3076     Out << ')';
3077     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3078       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3079
3080     writeOperandBundles(II);
3081
3082     Out << "\n          to ";
3083     writeOperand(II->getNormalDest(), true);
3084     Out << " unwind ";
3085     writeOperand(II->getUnwindDest(), true);
3086
3087   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3088     Out << ' ';
3089     if (AI->isUsedWithInAlloca())
3090       Out << "inalloca ";
3091     if (AI->isSwiftError())
3092       Out << "swifterror ";
3093     TypePrinter.print(AI->getAllocatedType(), Out);
3094
3095     // Explicitly write the array size if the code is broken, if it's an array
3096     // allocation, or if the type is not canonical for scalar allocations.  The
3097     // latter case prevents the type from mutating when round-tripping through
3098     // assembly.
3099     if (!AI->getArraySize() || AI->isArrayAllocation() ||
3100         !AI->getArraySize()->getType()->isIntegerTy(32)) {
3101       Out << ", ";
3102       writeOperand(AI->getArraySize(), true);
3103     }
3104     if (AI->getAlignment()) {
3105       Out << ", align " << AI->getAlignment();
3106     }
3107
3108     unsigned AddrSpace = AI->getType()->getAddressSpace();
3109     if (AddrSpace != 0) {
3110       Out << ", addrspace(" << AddrSpace << ')';
3111     }
3112
3113   } else if (isa<CastInst>(I)) {
3114     if (Operand) {
3115       Out << ' ';
3116       writeOperand(Operand, true);   // Work with broken code
3117     }
3118     Out << " to ";
3119     TypePrinter.print(I.getType(), Out);
3120   } else if (isa<VAArgInst>(I)) {
3121     if (Operand) {
3122       Out << ' ';
3123       writeOperand(Operand, true);   // Work with broken code
3124     }
3125     Out << ", ";
3126     TypePrinter.print(I.getType(), Out);
3127   } else if (Operand) {   // Print the normal way.
3128     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3129       Out << ' ';
3130       TypePrinter.print(GEP->getSourceElementType(), Out);
3131       Out << ',';
3132     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3133       Out << ' ';
3134       TypePrinter.print(LI->getType(), Out);
3135       Out << ',';
3136     }
3137
3138     // PrintAllTypes - Instructions who have operands of all the same type
3139     // omit the type from all but the first operand.  If the instruction has
3140     // different type operands (for example br), then they are all printed.
3141     bool PrintAllTypes = false;
3142     Type *TheType = Operand->getType();
3143
3144     // Select, Store and ShuffleVector always print all types.
3145     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3146         || isa<ReturnInst>(I)) {
3147       PrintAllTypes = true;
3148     } else {
3149       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3150         Operand = I.getOperand(i);
3151         // note that Operand shouldn't be null, but the test helps make dump()
3152         // more tolerant of malformed IR
3153         if (Operand && Operand->getType() != TheType) {
3154           PrintAllTypes = true;    // We have differing types!  Print them all!
3155           break;
3156         }
3157       }
3158     }
3159
3160     if (!PrintAllTypes) {
3161       Out << ' ';
3162       TypePrinter.print(TheType, Out);
3163     }
3164
3165     Out << ' ';
3166     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3167       if (i) Out << ", ";
3168       writeOperand(I.getOperand(i), PrintAllTypes);
3169     }
3170   }
3171
3172   // Print atomic ordering/alignment for memory operations
3173   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3174     if (LI->isAtomic())
3175       writeAtomic(LI->getOrdering(), LI->getSynchScope());
3176     if (LI->getAlignment())
3177       Out << ", align " << LI->getAlignment();
3178   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3179     if (SI->isAtomic())
3180       writeAtomic(SI->getOrdering(), SI->getSynchScope());
3181     if (SI->getAlignment())
3182       Out << ", align " << SI->getAlignment();
3183   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3184     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3185                        CXI->getSynchScope());
3186   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3187     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3188   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3189     writeAtomic(FI->getOrdering(), FI->getSynchScope());
3190   }
3191
3192   // Print Metadata info.
3193   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3194   I.getAllMetadata(InstMD);
3195   printMetadataAttachments(InstMD, ", ");
3196
3197   // Print a nice comment.
3198   printInfoComment(I);
3199 }
3200
3201 void AssemblyWriter::printMetadataAttachments(
3202     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3203     StringRef Separator) {
3204   if (MDs.empty())
3205     return;
3206
3207   if (MDNames.empty())
3208     MDs[0].second->getContext().getMDKindNames(MDNames);
3209
3210   for (const auto &I : MDs) {
3211     unsigned Kind = I.first;
3212     Out << Separator;
3213     if (Kind < MDNames.size()) {
3214       Out << "!";
3215       printMetadataIdentifier(MDNames[Kind], Out);
3216     } else
3217       Out << "!<unknown kind #" << Kind << ">";
3218     Out << ' ';
3219     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3220   }
3221 }
3222
3223 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3224   Out << '!' << Slot << " = ";
3225   printMDNodeBody(Node);
3226   Out << "\n";
3227 }
3228
3229 void AssemblyWriter::writeAllMDNodes() {
3230   SmallVector<const MDNode *, 16> Nodes;
3231   Nodes.resize(Machine.mdn_size());
3232   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3233        I != E; ++I)
3234     Nodes[I->second] = cast<MDNode>(I->first);
3235
3236   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3237     writeMDNode(i, Nodes[i]);
3238   }
3239 }
3240
3241 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3242   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3243 }
3244
3245 void AssemblyWriter::writeAllAttributeGroups() {
3246   std::vector<std::pair<AttributeSet, unsigned>> asVec;
3247   asVec.resize(Machine.as_size());
3248
3249   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3250        I != E; ++I)
3251     asVec[I->second] = *I;
3252
3253   for (const auto &I : asVec)
3254     Out << "attributes #" << I.second << " = { "
3255         << I.first.getAsString(true) << " }\n";
3256 }
3257
3258 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3259   bool IsInFunction = Machine.getFunction();
3260   if (IsInFunction)
3261     Out << "  ";
3262
3263   Out << "uselistorder";
3264   if (const BasicBlock *BB =
3265           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3266     Out << "_bb ";
3267     writeOperand(BB->getParent(), false);
3268     Out << ", ";
3269     writeOperand(BB, false);
3270   } else {
3271     Out << " ";
3272     writeOperand(Order.V, true);
3273   }
3274   Out << ", { ";
3275
3276   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3277   Out << Order.Shuffle[0];
3278   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3279     Out << ", " << Order.Shuffle[I];
3280   Out << " }\n";
3281 }
3282
3283 void AssemblyWriter::printUseLists(const Function *F) {
3284   auto hasMore =
3285       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3286   if (!hasMore())
3287     // Nothing to do.
3288     return;
3289
3290   Out << "\n; uselistorder directives\n";
3291   while (hasMore()) {
3292     printUseListOrder(UseListOrders.back());
3293     UseListOrders.pop_back();
3294   }
3295 }
3296
3297 //===----------------------------------------------------------------------===//
3298 //                       External Interface declarations
3299 //===----------------------------------------------------------------------===//
3300
3301 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3302                      bool ShouldPreserveUseListOrder,
3303                      bool IsForDebug) const {
3304   SlotTracker SlotTable(this->getParent());
3305   formatted_raw_ostream OS(ROS);
3306   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
3307                    IsForDebug,
3308                    ShouldPreserveUseListOrder);
3309   W.printFunction(this);
3310 }
3311
3312 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3313                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3314   SlotTracker SlotTable(this);
3315   formatted_raw_ostream OS(ROS);
3316   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3317                    ShouldPreserveUseListOrder);
3318   W.printModule(this);
3319 }
3320
3321 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3322   SlotTracker SlotTable(getParent());
3323   formatted_raw_ostream OS(ROS);
3324   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3325   W.printNamedMDNode(this);
3326 }
3327
3328 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3329                         bool IsForDebug) const {
3330   Optional<SlotTracker> LocalST;
3331   SlotTracker *SlotTable;
3332   if (auto *ST = MST.getMachine())
3333     SlotTable = ST;
3334   else {
3335     LocalST.emplace(getParent());
3336     SlotTable = &*LocalST;
3337   }
3338
3339   formatted_raw_ostream OS(ROS);
3340   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
3341   W.printNamedMDNode(this);
3342 }
3343
3344 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3345   PrintLLVMName(ROS, getName(), ComdatPrefix);
3346   ROS << " = comdat ";
3347
3348   switch (getSelectionKind()) {
3349   case Comdat::Any:
3350     ROS << "any";
3351     break;
3352   case Comdat::ExactMatch:
3353     ROS << "exactmatch";
3354     break;
3355   case Comdat::Largest:
3356     ROS << "largest";
3357     break;
3358   case Comdat::NoDuplicates:
3359     ROS << "noduplicates";
3360     break;
3361   case Comdat::SameSize:
3362     ROS << "samesize";
3363     break;
3364   }
3365
3366   ROS << '\n';
3367 }
3368
3369 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
3370   TypePrinting TP;
3371   TP.print(const_cast<Type*>(this), OS);
3372
3373   if (NoDetails)
3374     return;
3375
3376   // If the type is a named struct type, print the body as well.
3377   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3378     if (!STy->isLiteral()) {
3379       OS << " = type ";
3380       TP.printStructBody(STy, OS);
3381     }
3382 }
3383
3384 static bool isReferencingMDNode(const Instruction &I) {
3385   if (const auto *CI = dyn_cast<CallInst>(&I))
3386     if (Function *F = CI->getCalledFunction())
3387       if (F->isIntrinsic())
3388         for (auto &Op : I.operands())
3389           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3390             if (isa<MDNode>(V->getMetadata()))
3391               return true;
3392   return false;
3393 }
3394
3395 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3396   bool ShouldInitializeAllMetadata = false;
3397   if (auto *I = dyn_cast<Instruction>(this))
3398     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3399   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3400     ShouldInitializeAllMetadata = true;
3401
3402   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3403   print(ROS, MST, IsForDebug);
3404 }
3405
3406 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3407                   bool IsForDebug) const {
3408   formatted_raw_ostream OS(ROS);
3409   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3410   SlotTracker &SlotTable =
3411       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3412   auto incorporateFunction = [&](const Function *F) {
3413     if (F)
3414       MST.incorporateFunction(*F);
3415   };
3416
3417   if (const Instruction *I = dyn_cast<Instruction>(this)) {
3418     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3419     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3420     W.printInstruction(*I);
3421   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3422     incorporateFunction(BB->getParent());
3423     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3424     W.printBasicBlock(BB);
3425   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3426     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3427     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3428       W.printGlobal(V);
3429     else if (const Function *F = dyn_cast<Function>(GV))
3430       W.printFunction(F);
3431     else
3432       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
3433   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3434     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3435   } else if (const Constant *C = dyn_cast<Constant>(this)) {
3436     TypePrinting TypePrinter;
3437     TypePrinter.print(C->getType(), OS);
3438     OS << ' ';
3439     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3440   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3441     this->printAsOperand(OS, /* PrintType */ true, MST);
3442   } else {
3443     llvm_unreachable("Unknown value to print out!");
3444   }
3445 }
3446
3447 /// Print without a type, skipping the TypePrinting object.
3448 ///
3449 /// \return \c true iff printing was successful.
3450 static bool printWithoutType(const Value &V, raw_ostream &O,
3451                              SlotTracker *Machine, const Module *M) {
3452   if (V.hasName() || isa<GlobalValue>(V) ||
3453       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3454     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3455     return true;
3456   }
3457   return false;
3458 }
3459
3460 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3461                                ModuleSlotTracker &MST) {
3462   TypePrinting TypePrinter;
3463   if (const Module *M = MST.getModule())
3464     TypePrinter.incorporateTypes(*M);
3465   if (PrintType) {
3466     TypePrinter.print(V.getType(), O);
3467     O << ' ';
3468   }
3469
3470   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3471                          MST.getModule());
3472 }
3473
3474 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3475                            const Module *M) const {
3476   if (!M)
3477     M = getModuleFromVal(this);
3478
3479   if (!PrintType)
3480     if (printWithoutType(*this, O, nullptr, M))
3481       return;
3482
3483   SlotTracker Machine(
3484       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3485   ModuleSlotTracker MST(Machine, M);
3486   printAsOperandImpl(*this, O, PrintType, MST);
3487 }
3488
3489 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3490                            ModuleSlotTracker &MST) const {
3491   if (!PrintType)
3492     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3493       return;
3494
3495   printAsOperandImpl(*this, O, PrintType, MST);
3496 }
3497
3498 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3499                               ModuleSlotTracker &MST, const Module *M,
3500                               bool OnlyAsOperand) {
3501   formatted_raw_ostream OS(ROS);
3502
3503   TypePrinting TypePrinter;
3504   if (M)
3505     TypePrinter.incorporateTypes(*M);
3506
3507   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3508                          /* FromValue */ true);
3509
3510   auto *N = dyn_cast<MDNode>(&MD);
3511   if (OnlyAsOperand || !N)
3512     return;
3513
3514   OS << " = ";
3515   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3516 }
3517
3518 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3519   ModuleSlotTracker MST(M, isa<MDNode>(this));
3520   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3521 }
3522
3523 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3524                               const Module *M) const {
3525   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3526 }
3527
3528 void Metadata::print(raw_ostream &OS, const Module *M,
3529                      bool /*IsForDebug*/) const {
3530   ModuleSlotTracker MST(M, isa<MDNode>(this));
3531   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3532 }
3533
3534 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3535                      const Module *M, bool /*IsForDebug*/) const {
3536   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3537 }
3538
3539 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3540 // Value::dump - allow easy printing of Values from the debugger.
3541 LLVM_DUMP_METHOD
3542 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3543
3544 // Type::dump - allow easy printing of Types from the debugger.
3545 LLVM_DUMP_METHOD
3546 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3547
3548 // Module::dump() - Allow printing of Modules from the debugger.
3549 LLVM_DUMP_METHOD
3550 void Module::dump() const {
3551   print(dbgs(), nullptr,
3552         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3553 }
3554
3555 // \brief Allow printing of Comdats from the debugger.
3556 LLVM_DUMP_METHOD
3557 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3558
3559 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3560 LLVM_DUMP_METHOD
3561 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3562
3563 LLVM_DUMP_METHOD
3564 void Metadata::dump() const { dump(nullptr); }
3565
3566 LLVM_DUMP_METHOD
3567 void Metadata::dump(const Module *M) const {
3568   print(dbgs(), M, /*IsForDebug=*/true);
3569   dbgs() << '\n';
3570 }
3571 #endif