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