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