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