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