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