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