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