xref: /freebsd/contrib/llvm-project/llvm/lib/IR/AsmWriter.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This library implements `print` family of functions in classes like
10 // Module, Function, Value, etc. In-memory representation of those classes is
11 // converted to IR strings.
12 //
13 // Note that these routines must be extremely tolerant of various errors in the
14 // LLVM code, because it can be used for debugging transformations.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/iterator_range.h"
30 #include "llvm/BinaryFormat/Dwarf.h"
31 #include "llvm/Config/llvm-config.h"
32 #include "llvm/IR/Argument.h"
33 #include "llvm/IR/AssemblyAnnotationWriter.h"
34 #include "llvm/IR/Attributes.h"
35 #include "llvm/IR/BasicBlock.h"
36 #include "llvm/IR/CFG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Comdat.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DebugInfoMetadata.h"
42 #include "llvm/IR/DebugProgramInstruction.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalIFunc.h"
47 #include "llvm/IR/GlobalObject.h"
48 #include "llvm/IR/GlobalValue.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/IRPrintingPasses.h"
51 #include "llvm/IR/InlineAsm.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Metadata.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/ModuleSlotTracker.h"
60 #include "llvm/IR/ModuleSummaryIndex.h"
61 #include "llvm/IR/Operator.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/TypeFinder.h"
64 #include "llvm/IR/TypedPointerType.h"
65 #include "llvm/IR/Use.h"
66 #include "llvm/IR/User.h"
67 #include "llvm/IR/Value.h"
68 #include "llvm/Support/AtomicOrdering.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/Format.h"
74 #include "llvm/Support/FormattedStream.h"
75 #include "llvm/Support/SaveAndRestore.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <algorithm>
78 #include <cassert>
79 #include <cctype>
80 #include <cstddef>
81 #include <cstdint>
82 #include <iterator>
83 #include <memory>
84 #include <optional>
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 using OrderMap = MapVector<const Value *, unsigned>;
100 
101 using UseListOrderMap =
102     DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>;
103 
104 /// Look for a value that might be wrapped as metadata, e.g. a value in a
105 /// metadata operand. Returns the input value as-is if it is not wrapped.
skipMetadataWrapper(const Value * V)106 static const Value *skipMetadataWrapper(const Value *V) {
107   if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
108     if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
109       return VAM->getValue();
110   return V;
111 }
112 
orderValue(const Value * V,OrderMap & OM)113 static void orderValue(const Value *V, OrderMap &OM) {
114   if (OM.lookup(V))
115     return;
116 
117   if (const Constant *C = dyn_cast<Constant>(V))
118     if (C->getNumOperands() && !isa<GlobalValue>(C))
119       for (const Value *Op : C->operands())
120         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
121           orderValue(Op, OM);
122 
123   // Note: we cannot cache this lookup above, since inserting into the map
124   // changes the map's size, and thus affects the other IDs.
125   unsigned ID = OM.size() + 1;
126   OM[V] = ID;
127 }
128 
orderModule(const Module * M)129 static OrderMap orderModule(const Module *M) {
130   OrderMap OM;
131 
132   for (const GlobalVariable &G : M->globals()) {
133     if (G.hasInitializer())
134       if (!isa<GlobalValue>(G.getInitializer()))
135         orderValue(G.getInitializer(), OM);
136     orderValue(&G, OM);
137   }
138   for (const GlobalAlias &A : M->aliases()) {
139     if (!isa<GlobalValue>(A.getAliasee()))
140       orderValue(A.getAliasee(), OM);
141     orderValue(&A, OM);
142   }
143   for (const GlobalIFunc &I : M->ifuncs()) {
144     if (!isa<GlobalValue>(I.getResolver()))
145       orderValue(I.getResolver(), OM);
146     orderValue(&I, OM);
147   }
148   for (const Function &F : *M) {
149     for (const Use &U : F.operands())
150       if (!isa<GlobalValue>(U.get()))
151         orderValue(U.get(), OM);
152 
153     orderValue(&F, OM);
154 
155     if (F.isDeclaration())
156       continue;
157 
158     for (const Argument &A : F.args())
159       orderValue(&A, OM);
160     for (const BasicBlock &BB : F) {
161       orderValue(&BB, OM);
162       for (const Instruction &I : BB) {
163         for (const Value *Op : I.operands()) {
164           Op = skipMetadataWrapper(Op);
165           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
166               isa<InlineAsm>(*Op))
167             orderValue(Op, OM);
168         }
169         orderValue(&I, OM);
170       }
171     }
172   }
173   return OM;
174 }
175 
176 static std::vector<unsigned>
predictValueUseListOrder(const Value * V,unsigned ID,const OrderMap & OM)177 predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
178   // Predict use-list order for this one.
179   using Entry = std::pair<const Use *, unsigned>;
180   SmallVector<Entry, 64> List;
181   for (const Use &U : V->uses())
182     // Check if this user will be serialized.
183     if (OM.lookup(U.getUser()))
184       List.push_back(std::make_pair(&U, List.size()));
185 
186   if (List.size() < 2)
187     // We may have lost some users.
188     return {};
189 
190   // When referencing a value before its declaration, a temporary value is
191   // created, which will later be RAUWed with the actual value. This reverses
192   // the use list. This happens for all values apart from basic blocks.
193   bool GetsReversed = !isa<BasicBlock>(V);
194   if (auto *BA = dyn_cast<BlockAddress>(V))
195     ID = OM.lookup(BA->getBasicBlock());
196   llvm::sort(List, [&](const Entry &L, const Entry &R) {
197     const Use *LU = L.first;
198     const Use *RU = R.first;
199     if (LU == RU)
200       return false;
201 
202     auto LID = OM.lookup(LU->getUser());
203     auto RID = OM.lookup(RU->getUser());
204 
205     // If ID is 4, then expect: 7 6 5 1 2 3.
206     if (LID < RID) {
207       if (GetsReversed)
208         if (RID <= ID)
209           return true;
210       return false;
211     }
212     if (RID < LID) {
213       if (GetsReversed)
214         if (LID <= ID)
215           return false;
216       return true;
217     }
218 
219     // LID and RID are equal, so we have different operands of the same user.
220     // Assume operands are added in order for all instructions.
221     if (GetsReversed)
222       if (LID <= ID)
223         return LU->getOperandNo() < RU->getOperandNo();
224     return LU->getOperandNo() > RU->getOperandNo();
225   });
226 
227   if (llvm::is_sorted(List, llvm::less_second()))
228     // Order is already correct.
229     return {};
230 
231   // Store the shuffle.
232   std::vector<unsigned> Shuffle(List.size());
233   for (size_t I = 0, E = List.size(); I != E; ++I)
234     Shuffle[I] = List[I].second;
235   return Shuffle;
236 }
237 
predictUseListOrder(const Module * M)238 static UseListOrderMap predictUseListOrder(const Module *M) {
239   OrderMap OM = orderModule(M);
240   UseListOrderMap ULOM;
241   for (const auto &Pair : OM) {
242     const Value *V = Pair.first;
243     if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
244       continue;
245 
246     std::vector<unsigned> Shuffle =
247         predictValueUseListOrder(V, Pair.second, OM);
248     if (Shuffle.empty())
249       continue;
250 
251     const Function *F = nullptr;
252     if (auto *I = dyn_cast<Instruction>(V))
253       F = I->getFunction();
254     if (auto *A = dyn_cast<Argument>(V))
255       F = A->getParent();
256     if (auto *BB = dyn_cast<BasicBlock>(V))
257       F = BB->getParent();
258     ULOM[F][V] = std::move(Shuffle);
259   }
260   return ULOM;
261 }
262 
getModuleFromVal(const Value * V)263 static const Module *getModuleFromVal(const Value *V) {
264   if (const Argument *MA = dyn_cast<Argument>(V))
265     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
266 
267   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
268     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
269 
270   if (const Instruction *I = dyn_cast<Instruction>(V)) {
271     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
272     return M ? M->getParent() : nullptr;
273   }
274 
275   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
276     return GV->getParent();
277 
278   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
279     for (const User *U : MAV->users())
280       if (isa<Instruction>(U))
281         if (const Module *M = getModuleFromVal(U))
282           return M;
283     return nullptr;
284   }
285 
286   return nullptr;
287 }
288 
getModuleFromDPI(const DbgMarker * Marker)289 static const Module *getModuleFromDPI(const DbgMarker *Marker) {
290   const Function *M =
291       Marker->getParent() ? Marker->getParent()->getParent() : nullptr;
292   return M ? M->getParent() : nullptr;
293 }
294 
getModuleFromDPI(const DbgRecord * DR)295 static const Module *getModuleFromDPI(const DbgRecord *DR) {
296   return DR->getMarker() ? getModuleFromDPI(DR->getMarker()) : nullptr;
297 }
298 
PrintCallingConv(unsigned cc,raw_ostream & Out)299 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
300   switch (cc) {
301   default:                         Out << "cc" << cc; break;
302   case CallingConv::Fast:          Out << "fastcc"; break;
303   case CallingConv::Cold:          Out << "coldcc"; break;
304   case CallingConv::AnyReg:        Out << "anyregcc"; break;
305   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
306   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
307   case CallingConv::PreserveNone:  Out << "preserve_nonecc"; break;
308   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
309   case CallingConv::GHC:           Out << "ghccc"; break;
310   case CallingConv::Tail:          Out << "tailcc"; break;
311   case CallingConv::GRAAL:         Out << "graalcc"; break;
312   case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
313   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
314   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
315   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
316   case CallingConv::X86_RegCall:   Out << "x86_regcallcc"; break;
317   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
318   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
319   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
320   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
321   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
322   case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
323   case CallingConv::AArch64_SVE_VectorCall:
324     Out << "aarch64_sve_vector_pcs";
325     break;
326   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
327     Out << "aarch64_sme_preservemost_from_x0";
328     break;
329   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1:
330     Out << "aarch64_sme_preservemost_from_x1";
331     break;
332   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
333     Out << "aarch64_sme_preservemost_from_x2";
334     break;
335   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
336   case CallingConv::AVR_INTR:      Out << "avr_intrcc "; break;
337   case CallingConv::AVR_SIGNAL:    Out << "avr_signalcc "; break;
338   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
339   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
340   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
341   case CallingConv::Win64:         Out << "win64cc"; break;
342   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
343   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
344   case CallingConv::Swift:         Out << "swiftcc"; break;
345   case CallingConv::SwiftTail:     Out << "swifttailcc"; break;
346   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
347   case CallingConv::DUMMY_HHVM:
348     Out << "hhvmcc";
349     break;
350   case CallingConv::DUMMY_HHVM_C:
351     Out << "hhvm_ccc";
352     break;
353   case CallingConv::AMDGPU_VS:     Out << "amdgpu_vs"; break;
354   case CallingConv::AMDGPU_LS:     Out << "amdgpu_ls"; break;
355   case CallingConv::AMDGPU_HS:     Out << "amdgpu_hs"; break;
356   case CallingConv::AMDGPU_ES:     Out << "amdgpu_es"; break;
357   case CallingConv::AMDGPU_GS:     Out << "amdgpu_gs"; break;
358   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
359   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
360   case CallingConv::AMDGPU_CS_Chain:
361     Out << "amdgpu_cs_chain";
362     break;
363   case CallingConv::AMDGPU_CS_ChainPreserve:
364     Out << "amdgpu_cs_chain_preserve";
365     break;
366   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
367   case CallingConv::AMDGPU_Gfx:    Out << "amdgpu_gfx"; break;
368   case CallingConv::M68k_RTD:      Out << "m68k_rtdcc"; break;
369   case CallingConv::RISCV_VectorCall:
370     Out << "riscv_vector_cc";
371     break;
372   }
373 }
374 
375 enum PrefixType {
376   GlobalPrefix,
377   ComdatPrefix,
378   LabelPrefix,
379   LocalPrefix,
380   NoPrefix
381 };
382 
printLLVMNameWithoutPrefix(raw_ostream & OS,StringRef Name)383 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
384   assert(!Name.empty() && "Cannot get empty name!");
385 
386   // Scan the name to see if it needs quotes first.
387   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
388   if (!NeedsQuotes) {
389     for (unsigned char C : Name) {
390       // By making this unsigned, the value passed in to isalnum will always be
391       // in the range 0-255.  This is important when building with MSVC because
392       // its implementation will assert.  This situation can arise when dealing
393       // with UTF-8 multibyte characters.
394       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
395           C != '_') {
396         NeedsQuotes = true;
397         break;
398       }
399     }
400   }
401 
402   // If we didn't need any quotes, just write out the name in one blast.
403   if (!NeedsQuotes) {
404     OS << Name;
405     return;
406   }
407 
408   // Okay, we need quotes.  Output the quotes and escape any scary characters as
409   // needed.
410   OS << '"';
411   printEscapedString(Name, OS);
412   OS << '"';
413 }
414 
415 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
416 /// (if the string only contains simple characters) or is surrounded with ""'s
417 /// (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,StringRef Name,PrefixType Prefix)418 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
419   switch (Prefix) {
420   case NoPrefix:
421     break;
422   case GlobalPrefix:
423     OS << '@';
424     break;
425   case ComdatPrefix:
426     OS << '$';
427     break;
428   case LabelPrefix:
429     break;
430   case LocalPrefix:
431     OS << '%';
432     break;
433   }
434   printLLVMNameWithoutPrefix(OS, Name);
435 }
436 
437 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
438 /// (if the string only contains simple characters) or is surrounded with ""'s
439 /// (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,const Value * V)440 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
441   PrintLLVMName(OS, V->getName(),
442                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
443 }
444 
PrintShuffleMask(raw_ostream & Out,Type * Ty,ArrayRef<int> Mask)445 static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
446   Out << ", <";
447   if (isa<ScalableVectorType>(Ty))
448     Out << "vscale x ";
449   Out << Mask.size() << " x i32> ";
450   bool FirstElt = true;
451   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
452     Out << "zeroinitializer";
453   } else if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
454     Out << "poison";
455   } else {
456     Out << "<";
457     for (int Elt : Mask) {
458       if (FirstElt)
459         FirstElt = false;
460       else
461         Out << ", ";
462       Out << "i32 ";
463       if (Elt == PoisonMaskElem)
464         Out << "poison";
465       else
466         Out << Elt;
467     }
468     Out << ">";
469   }
470 }
471 
472 namespace {
473 
474 class TypePrinting {
475 public:
TypePrinting(const Module * M=nullptr)476   TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
477 
478   TypePrinting(const TypePrinting &) = delete;
479   TypePrinting &operator=(const TypePrinting &) = delete;
480 
481   /// The named types that are used by the current module.
482   TypeFinder &getNamedTypes();
483 
484   /// The numbered types, number to type mapping.
485   std::vector<StructType *> &getNumberedTypes();
486 
487   bool empty();
488 
489   void print(Type *Ty, raw_ostream &OS);
490 
491   void printStructBody(StructType *Ty, raw_ostream &OS);
492 
493 private:
494   void incorporateTypes();
495 
496   /// A module to process lazily when needed. Set to nullptr as soon as used.
497   const Module *DeferredM;
498 
499   TypeFinder NamedTypes;
500 
501   // The numbered types, along with their value.
502   DenseMap<StructType *, unsigned> Type2Number;
503 
504   std::vector<StructType *> NumberedTypes;
505 };
506 
507 } // end anonymous namespace
508 
getNamedTypes()509 TypeFinder &TypePrinting::getNamedTypes() {
510   incorporateTypes();
511   return NamedTypes;
512 }
513 
getNumberedTypes()514 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
515   incorporateTypes();
516 
517   // We know all the numbers that each type is used and we know that it is a
518   // dense assignment. Convert the map to an index table, if it's not done
519   // already (judging from the sizes):
520   if (NumberedTypes.size() == Type2Number.size())
521     return NumberedTypes;
522 
523   NumberedTypes.resize(Type2Number.size());
524   for (const auto &P : Type2Number) {
525     assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
526     assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
527     NumberedTypes[P.second] = P.first;
528   }
529   return NumberedTypes;
530 }
531 
empty()532 bool TypePrinting::empty() {
533   incorporateTypes();
534   return NamedTypes.empty() && Type2Number.empty();
535 }
536 
incorporateTypes()537 void TypePrinting::incorporateTypes() {
538   if (!DeferredM)
539     return;
540 
541   NamedTypes.run(*DeferredM, false);
542   DeferredM = nullptr;
543 
544   // The list of struct types we got back includes all the struct types, split
545   // the unnamed ones out to a numbering and remove the anonymous structs.
546   unsigned NextNumber = 0;
547 
548   std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
549   for (StructType *STy : NamedTypes) {
550     // Ignore anonymous types.
551     if (STy->isLiteral())
552       continue;
553 
554     if (STy->getName().empty())
555       Type2Number[STy] = NextNumber++;
556     else
557       *NextToUse++ = STy;
558   }
559 
560   NamedTypes.erase(NextToUse, NamedTypes.end());
561 }
562 
563 /// Write the specified type to the specified raw_ostream, making use of type
564 /// names or up references to shorten the type name where possible.
print(Type * Ty,raw_ostream & OS)565 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
566   switch (Ty->getTypeID()) {
567   case Type::VoidTyID:      OS << "void"; return;
568   case Type::HalfTyID:      OS << "half"; return;
569   case Type::BFloatTyID:    OS << "bfloat"; return;
570   case Type::FloatTyID:     OS << "float"; return;
571   case Type::DoubleTyID:    OS << "double"; return;
572   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
573   case Type::FP128TyID:     OS << "fp128"; return;
574   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
575   case Type::LabelTyID:     OS << "label"; return;
576   case Type::MetadataTyID:  OS << "metadata"; return;
577   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
578   case Type::X86_AMXTyID:   OS << "x86_amx"; return;
579   case Type::TokenTyID:     OS << "token"; return;
580   case Type::IntegerTyID:
581     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
582     return;
583 
584   case Type::FunctionTyID: {
585     FunctionType *FTy = cast<FunctionType>(Ty);
586     print(FTy->getReturnType(), OS);
587     OS << " (";
588     ListSeparator LS;
589     for (Type *Ty : FTy->params()) {
590       OS << LS;
591       print(Ty, OS);
592     }
593     if (FTy->isVarArg())
594       OS << LS << "...";
595     OS << ')';
596     return;
597   }
598   case Type::StructTyID: {
599     StructType *STy = cast<StructType>(Ty);
600 
601     if (STy->isLiteral())
602       return printStructBody(STy, OS);
603 
604     if (!STy->getName().empty())
605       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
606 
607     incorporateTypes();
608     const auto I = Type2Number.find(STy);
609     if (I != Type2Number.end())
610       OS << '%' << I->second;
611     else  // Not enumerated, print the hex address.
612       OS << "%\"type " << STy << '\"';
613     return;
614   }
615   case Type::PointerTyID: {
616     PointerType *PTy = cast<PointerType>(Ty);
617     OS << "ptr";
618     if (unsigned AddressSpace = PTy->getAddressSpace())
619       OS << " addrspace(" << AddressSpace << ')';
620     return;
621   }
622   case Type::ArrayTyID: {
623     ArrayType *ATy = cast<ArrayType>(Ty);
624     OS << '[' << ATy->getNumElements() << " x ";
625     print(ATy->getElementType(), OS);
626     OS << ']';
627     return;
628   }
629   case Type::FixedVectorTyID:
630   case Type::ScalableVectorTyID: {
631     VectorType *PTy = cast<VectorType>(Ty);
632     ElementCount EC = PTy->getElementCount();
633     OS << "<";
634     if (EC.isScalable())
635       OS << "vscale x ";
636     OS << EC.getKnownMinValue() << " x ";
637     print(PTy->getElementType(), OS);
638     OS << '>';
639     return;
640   }
641   case Type::TypedPointerTyID: {
642     TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
643     OS << "typedptr(" << *TPTy->getElementType() << ", "
644        << TPTy->getAddressSpace() << ")";
645     return;
646   }
647   case Type::TargetExtTyID:
648     TargetExtType *TETy = cast<TargetExtType>(Ty);
649     OS << "target(\"";
650     printEscapedString(Ty->getTargetExtName(), OS);
651     OS << "\"";
652     for (Type *Inner : TETy->type_params())
653       OS << ", " << *Inner;
654     for (unsigned IntParam : TETy->int_params())
655       OS << ", " << IntParam;
656     OS << ")";
657     return;
658   }
659   llvm_unreachable("Invalid TypeID");
660 }
661 
printStructBody(StructType * STy,raw_ostream & OS)662 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
663   if (STy->isOpaque()) {
664     OS << "opaque";
665     return;
666   }
667 
668   if (STy->isPacked())
669     OS << '<';
670 
671   if (STy->getNumElements() == 0) {
672     OS << "{}";
673   } else {
674     OS << "{ ";
675     ListSeparator LS;
676     for (Type *Ty : STy->elements()) {
677       OS << LS;
678       print(Ty, OS);
679     }
680 
681     OS << " }";
682   }
683   if (STy->isPacked())
684     OS << '>';
685 }
686 
687 AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
688 
689 namespace llvm {
690 
691 //===----------------------------------------------------------------------===//
692 // SlotTracker Class: Enumerate slot numbers for unnamed values
693 //===----------------------------------------------------------------------===//
694 /// This class provides computation of slot numbers for LLVM Assembly writing.
695 ///
696 class SlotTracker : public AbstractSlotTrackerStorage {
697 public:
698   /// ValueMap - A mapping of Values to slot numbers.
699   using ValueMap = DenseMap<const Value *, unsigned>;
700 
701 private:
702   /// TheModule - The module for which we are holding slot numbers.
703   const Module* TheModule;
704 
705   /// TheFunction - The function for which we are holding slot numbers.
706   const Function* TheFunction = nullptr;
707   bool FunctionProcessed = false;
708   bool ShouldInitializeAllMetadata;
709 
710   std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
711       ProcessModuleHookFn;
712   std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
713       ProcessFunctionHookFn;
714 
715   /// The summary index for which we are holding slot numbers.
716   const ModuleSummaryIndex *TheIndex = nullptr;
717 
718   /// mMap - The slot map for the module level data.
719   ValueMap mMap;
720   unsigned mNext = 0;
721 
722   /// fMap - The slot map for the function level data.
723   ValueMap fMap;
724   unsigned fNext = 0;
725 
726   /// mdnMap - Map for MDNodes.
727   DenseMap<const MDNode*, unsigned> mdnMap;
728   unsigned mdnNext = 0;
729 
730   /// asMap - The slot map for attribute sets.
731   DenseMap<AttributeSet, unsigned> asMap;
732   unsigned asNext = 0;
733 
734   /// ModulePathMap - The slot map for Module paths used in the summary index.
735   StringMap<unsigned> ModulePathMap;
736   unsigned ModulePathNext = 0;
737 
738   /// GUIDMap - The slot map for GUIDs used in the summary index.
739   DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
740   unsigned GUIDNext = 0;
741 
742   /// TypeIdMap - The slot map for type ids used in the summary index.
743   StringMap<unsigned> TypeIdMap;
744   unsigned TypeIdNext = 0;
745 
746   /// TypeIdCompatibleVtableMap - The slot map for type compatible vtable ids
747   /// used in the summary index.
748   StringMap<unsigned> TypeIdCompatibleVtableMap;
749   unsigned TypeIdCompatibleVtableNext = 0;
750 
751 public:
752   /// Construct from a module.
753   ///
754   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
755   /// functions, giving correct numbering for metadata referenced only from
756   /// within a function (even if no functions have been initialized).
757   explicit SlotTracker(const Module *M,
758                        bool ShouldInitializeAllMetadata = false);
759 
760   /// Construct from a function, starting out in incorp state.
761   ///
762   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
763   /// functions, giving correct numbering for metadata referenced only from
764   /// within a function (even if no functions have been initialized).
765   explicit SlotTracker(const Function *F,
766                        bool ShouldInitializeAllMetadata = false);
767 
768   /// Construct from a module summary index.
769   explicit SlotTracker(const ModuleSummaryIndex *Index);
770 
771   SlotTracker(const SlotTracker &) = delete;
772   SlotTracker &operator=(const SlotTracker &) = delete;
773 
774   ~SlotTracker() = default;
775 
776   void setProcessHook(
777       std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
778   void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
779                                          const Function *, bool)>);
780 
getNextMetadataSlot()781   unsigned getNextMetadataSlot() override { return mdnNext; }
782 
783   void createMetadataSlot(const MDNode *N) override;
784 
785   /// Return the slot number of the specified value in it's type
786   /// plane.  If something is not in the SlotTracker, return -1.
787   int getLocalSlot(const Value *V);
788   int getGlobalSlot(const GlobalValue *V);
789   int getMetadataSlot(const MDNode *N) override;
790   int getAttributeGroupSlot(AttributeSet AS);
791   int getModulePathSlot(StringRef Path);
792   int getGUIDSlot(GlobalValue::GUID GUID);
793   int getTypeIdSlot(StringRef Id);
794   int getTypeIdCompatibleVtableSlot(StringRef Id);
795 
796   /// If you'd like to deal with a function instead of just a module, use
797   /// this method to get its data into the SlotTracker.
incorporateFunction(const Function * F)798   void incorporateFunction(const Function *F) {
799     TheFunction = F;
800     FunctionProcessed = false;
801   }
802 
getFunction() const803   const Function *getFunction() const { return TheFunction; }
804 
805   /// After calling incorporateFunction, use this method to remove the
806   /// most recently incorporated function from the SlotTracker. This
807   /// will reset the state of the machine back to just the module contents.
808   void purgeFunction();
809 
810   /// MDNode map iterators.
811   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
812 
mdn_begin()813   mdn_iterator mdn_begin() { return mdnMap.begin(); }
mdn_end()814   mdn_iterator mdn_end() { return mdnMap.end(); }
mdn_size() const815   unsigned mdn_size() const { return mdnMap.size(); }
mdn_empty() const816   bool mdn_empty() const { return mdnMap.empty(); }
817 
818   /// AttributeSet map iterators.
819   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
820 
as_begin()821   as_iterator as_begin()   { return asMap.begin(); }
as_end()822   as_iterator as_end()     { return asMap.end(); }
as_size() const823   unsigned as_size() const { return asMap.size(); }
as_empty() const824   bool as_empty() const    { return asMap.empty(); }
825 
826   /// GUID map iterators.
827   using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
828 
829   /// These functions do the actual initialization.
830   inline void initializeIfNeeded();
831   int initializeIndexIfNeeded();
832 
833   // Implementation Details
834 private:
835   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
836   void CreateModuleSlot(const GlobalValue *V);
837 
838   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
839   void CreateMetadataSlot(const MDNode *N);
840 
841   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
842   void CreateFunctionSlot(const Value *V);
843 
844   /// Insert the specified AttributeSet into the slot table.
845   void CreateAttributeSetSlot(AttributeSet AS);
846 
847   inline void CreateModulePathSlot(StringRef Path);
848   void CreateGUIDSlot(GlobalValue::GUID GUID);
849   void CreateTypeIdSlot(StringRef Id);
850   void CreateTypeIdCompatibleVtableSlot(StringRef Id);
851 
852   /// Add all of the module level global variables (and their initializers)
853   /// and function declarations, but not the contents of those functions.
854   void processModule();
855   // Returns number of allocated slots
856   int processIndex();
857 
858   /// Add all of the functions arguments, basic blocks, and instructions.
859   void processFunction();
860 
861   /// Add the metadata directly attached to a GlobalObject.
862   void processGlobalObjectMetadata(const GlobalObject &GO);
863 
864   /// Add all of the metadata from a function.
865   void processFunctionMetadata(const Function &F);
866 
867   /// Add all of the metadata from an instruction.
868   void processInstructionMetadata(const Instruction &I);
869 
870   /// Add all of the metadata from a DbgRecord.
871   void processDbgRecordMetadata(const DbgRecord &DVR);
872 };
873 
874 } // end namespace llvm
875 
ModuleSlotTracker(SlotTracker & Machine,const Module * M,const Function * F)876 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
877                                      const Function *F)
878     : M(M), F(F), Machine(&Machine) {}
879 
ModuleSlotTracker(const Module * M,bool ShouldInitializeAllMetadata)880 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
881                                      bool ShouldInitializeAllMetadata)
882     : ShouldCreateStorage(M),
883       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
884 
885 ModuleSlotTracker::~ModuleSlotTracker() = default;
886 
getMachine()887 SlotTracker *ModuleSlotTracker::getMachine() {
888   if (!ShouldCreateStorage)
889     return Machine;
890 
891   ShouldCreateStorage = false;
892   MachineStorage =
893       std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
894   Machine = MachineStorage.get();
895   if (ProcessModuleHookFn)
896     Machine->setProcessHook(ProcessModuleHookFn);
897   if (ProcessFunctionHookFn)
898     Machine->setProcessHook(ProcessFunctionHookFn);
899   return Machine;
900 }
901 
incorporateFunction(const Function & F)902 void ModuleSlotTracker::incorporateFunction(const Function &F) {
903   // Using getMachine() may lazily create the slot tracker.
904   if (!getMachine())
905     return;
906 
907   // Nothing to do if this is the right function already.
908   if (this->F == &F)
909     return;
910   if (this->F)
911     Machine->purgeFunction();
912   Machine->incorporateFunction(&F);
913   this->F = &F;
914 }
915 
getLocalSlot(const Value * V)916 int ModuleSlotTracker::getLocalSlot(const Value *V) {
917   assert(F && "No function incorporated");
918   return Machine->getLocalSlot(V);
919 }
920 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Module *,bool)> Fn)921 void ModuleSlotTracker::setProcessHook(
922     std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
923         Fn) {
924   ProcessModuleHookFn = Fn;
925 }
926 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Function *,bool)> Fn)927 void ModuleSlotTracker::setProcessHook(
928     std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
929         Fn) {
930   ProcessFunctionHookFn = Fn;
931 }
932 
createSlotTracker(const Value * V)933 static SlotTracker *createSlotTracker(const Value *V) {
934   if (const Argument *FA = dyn_cast<Argument>(V))
935     return new SlotTracker(FA->getParent());
936 
937   if (const Instruction *I = dyn_cast<Instruction>(V))
938     if (I->getParent())
939       return new SlotTracker(I->getParent()->getParent());
940 
941   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
942     return new SlotTracker(BB->getParent());
943 
944   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
945     return new SlotTracker(GV->getParent());
946 
947   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
948     return new SlotTracker(GA->getParent());
949 
950   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
951     return new SlotTracker(GIF->getParent());
952 
953   if (const Function *Func = dyn_cast<Function>(V))
954     return new SlotTracker(Func);
955 
956   return nullptr;
957 }
958 
959 #if 0
960 #define ST_DEBUG(X) dbgs() << X
961 #else
962 #define ST_DEBUG(X)
963 #endif
964 
965 // Module level constructor. Causes the contents of the Module (sans functions)
966 // to be added to the slot table.
SlotTracker(const Module * M,bool ShouldInitializeAllMetadata)967 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
968     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
969 
970 // Function level constructor. Causes the contents of the Module and the one
971 // function provided to be added to the slot table.
SlotTracker(const Function * F,bool ShouldInitializeAllMetadata)972 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
973     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
974       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
975 
SlotTracker(const ModuleSummaryIndex * Index)976 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
977     : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
978 
initializeIfNeeded()979 inline void SlotTracker::initializeIfNeeded() {
980   if (TheModule) {
981     processModule();
982     TheModule = nullptr; ///< Prevent re-processing next time we're called.
983   }
984 
985   if (TheFunction && !FunctionProcessed)
986     processFunction();
987 }
988 
initializeIndexIfNeeded()989 int SlotTracker::initializeIndexIfNeeded() {
990   if (!TheIndex)
991     return 0;
992   int NumSlots = processIndex();
993   TheIndex = nullptr; ///< Prevent re-processing next time we're called.
994   return NumSlots;
995 }
996 
997 // Iterate through all the global variables, functions, and global
998 // variable initializers and create slots for them.
processModule()999 void SlotTracker::processModule() {
1000   ST_DEBUG("begin processModule!\n");
1001 
1002   // Add all of the unnamed global variables to the value table.
1003   for (const GlobalVariable &Var : TheModule->globals()) {
1004     if (!Var.hasName())
1005       CreateModuleSlot(&Var);
1006     processGlobalObjectMetadata(Var);
1007     auto Attrs = Var.getAttributes();
1008     if (Attrs.hasAttributes())
1009       CreateAttributeSetSlot(Attrs);
1010   }
1011 
1012   for (const GlobalAlias &A : TheModule->aliases()) {
1013     if (!A.hasName())
1014       CreateModuleSlot(&A);
1015   }
1016 
1017   for (const GlobalIFunc &I : TheModule->ifuncs()) {
1018     if (!I.hasName())
1019       CreateModuleSlot(&I);
1020   }
1021 
1022   // Add metadata used by named metadata.
1023   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
1024     for (const MDNode *N : NMD.operands())
1025       CreateMetadataSlot(N);
1026   }
1027 
1028   for (const Function &F : *TheModule) {
1029     if (!F.hasName())
1030       // Add all the unnamed functions to the table.
1031       CreateModuleSlot(&F);
1032 
1033     if (ShouldInitializeAllMetadata)
1034       processFunctionMetadata(F);
1035 
1036     // Add all the function attributes to the table.
1037     // FIXME: Add attributes of other objects?
1038     AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
1039     if (FnAttrs.hasAttributes())
1040       CreateAttributeSetSlot(FnAttrs);
1041   }
1042 
1043   if (ProcessModuleHookFn)
1044     ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
1045 
1046   ST_DEBUG("end processModule!\n");
1047 }
1048 
1049 // Process the arguments, basic blocks, and instructions  of a function.
processFunction()1050 void SlotTracker::processFunction() {
1051   ST_DEBUG("begin processFunction!\n");
1052   fNext = 0;
1053 
1054   // Process function metadata if it wasn't hit at the module-level.
1055   if (!ShouldInitializeAllMetadata)
1056     processFunctionMetadata(*TheFunction);
1057 
1058   // Add all the function arguments with no names.
1059   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1060       AE = TheFunction->arg_end(); AI != AE; ++AI)
1061     if (!AI->hasName())
1062       CreateFunctionSlot(&*AI);
1063 
1064   ST_DEBUG("Inserting Instructions:\n");
1065 
1066   // Add all of the basic blocks and instructions with no names.
1067   for (auto &BB : *TheFunction) {
1068     if (!BB.hasName())
1069       CreateFunctionSlot(&BB);
1070 
1071     for (auto &I : BB) {
1072       if (!I.getType()->isVoidTy() && !I.hasName())
1073         CreateFunctionSlot(&I);
1074 
1075       // We allow direct calls to any llvm.foo function here, because the
1076       // target may not be linked into the optimizer.
1077       if (const auto *Call = dyn_cast<CallBase>(&I)) {
1078         // Add all the call attributes to the table.
1079         AttributeSet Attrs = Call->getAttributes().getFnAttrs();
1080         if (Attrs.hasAttributes())
1081           CreateAttributeSetSlot(Attrs);
1082       }
1083     }
1084   }
1085 
1086   if (ProcessFunctionHookFn)
1087     ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
1088 
1089   FunctionProcessed = true;
1090 
1091   ST_DEBUG("end processFunction!\n");
1092 }
1093 
1094 // Iterate through all the GUID in the index and create slots for them.
processIndex()1095 int SlotTracker::processIndex() {
1096   ST_DEBUG("begin processIndex!\n");
1097   assert(TheIndex);
1098 
1099   // The first block of slots are just the module ids, which start at 0 and are
1100   // assigned consecutively. Since the StringMap iteration order isn't
1101   // guaranteed, order by path string before assigning slots.
1102   std::vector<StringRef> ModulePaths;
1103   for (auto &[ModPath, _] : TheIndex->modulePaths())
1104     ModulePaths.push_back(ModPath);
1105   llvm::sort(ModulePaths.begin(), ModulePaths.end());
1106   for (auto &ModPath : ModulePaths)
1107     CreateModulePathSlot(ModPath);
1108 
1109   // Start numbering the GUIDs after the module ids.
1110   GUIDNext = ModulePathNext;
1111 
1112   for (auto &GlobalList : *TheIndex)
1113     CreateGUIDSlot(GlobalList.first);
1114 
1115   // Start numbering the TypeIdCompatibleVtables after the GUIDs.
1116   TypeIdCompatibleVtableNext = GUIDNext;
1117   for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1118     CreateTypeIdCompatibleVtableSlot(TId.first);
1119 
1120   // Start numbering the TypeIds after the TypeIdCompatibleVtables.
1121   TypeIdNext = TypeIdCompatibleVtableNext;
1122   for (const auto &TID : TheIndex->typeIds())
1123     CreateTypeIdSlot(TID.second.first);
1124 
1125   ST_DEBUG("end processIndex!\n");
1126   return TypeIdNext;
1127 }
1128 
processGlobalObjectMetadata(const GlobalObject & GO)1129 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1130   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1131   GO.getAllMetadata(MDs);
1132   for (auto &MD : MDs)
1133     CreateMetadataSlot(MD.second);
1134 }
1135 
processFunctionMetadata(const Function & F)1136 void SlotTracker::processFunctionMetadata(const Function &F) {
1137   processGlobalObjectMetadata(F);
1138   for (auto &BB : F) {
1139     for (auto &I : BB) {
1140       for (const DbgRecord &DR : I.getDbgRecordRange())
1141         processDbgRecordMetadata(DR);
1142       processInstructionMetadata(I);
1143     }
1144   }
1145 }
1146 
processDbgRecordMetadata(const DbgRecord & DR)1147 void SlotTracker::processDbgRecordMetadata(const DbgRecord &DR) {
1148   if (const DbgVariableRecord *DVR = dyn_cast<const DbgVariableRecord>(&DR)) {
1149     // Process metadata used by DbgRecords; we only specifically care about the
1150     // DILocalVariable, DILocation, and DIAssignID fields, as the Value and
1151     // Expression fields should only be printed inline and so do not use a slot.
1152     // Note: The above doesn't apply for empty-metadata operands.
1153     if (auto *Empty = dyn_cast<MDNode>(DVR->getRawLocation()))
1154       CreateMetadataSlot(Empty);
1155     CreateMetadataSlot(DVR->getRawVariable());
1156     if (DVR->isDbgAssign()) {
1157       CreateMetadataSlot(cast<MDNode>(DVR->getRawAssignID()));
1158       if (auto *Empty = dyn_cast<MDNode>(DVR->getRawAddress()))
1159         CreateMetadataSlot(Empty);
1160     }
1161   } else if (const DbgLabelRecord *DLR = dyn_cast<const DbgLabelRecord>(&DR)) {
1162     CreateMetadataSlot(DLR->getRawLabel());
1163   } else {
1164     llvm_unreachable("unsupported DbgRecord kind");
1165   }
1166   CreateMetadataSlot(DR.getDebugLoc().getAsMDNode());
1167 }
1168 
processInstructionMetadata(const Instruction & I)1169 void SlotTracker::processInstructionMetadata(const Instruction &I) {
1170   // Process metadata used directly by intrinsics.
1171   if (const CallInst *CI = dyn_cast<CallInst>(&I))
1172     if (Function *F = CI->getCalledFunction())
1173       if (F->isIntrinsic())
1174         for (auto &Op : I.operands())
1175           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1176             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1177               CreateMetadataSlot(N);
1178 
1179   // Process metadata attached to this instruction.
1180   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1181   I.getAllMetadata(MDs);
1182   for (auto &MD : MDs)
1183     CreateMetadataSlot(MD.second);
1184 }
1185 
1186 /// Clean up after incorporating a function. This is the only way to get out of
1187 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1188 /// incorporation state is indicated by TheFunction != 0.
purgeFunction()1189 void SlotTracker::purgeFunction() {
1190   ST_DEBUG("begin purgeFunction!\n");
1191   fMap.clear(); // Simply discard the function level map
1192   TheFunction = nullptr;
1193   FunctionProcessed = false;
1194   ST_DEBUG("end purgeFunction!\n");
1195 }
1196 
1197 /// getGlobalSlot - Get the slot number of a global value.
getGlobalSlot(const GlobalValue * V)1198 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1199   // Check for uninitialized state and do lazy initialization.
1200   initializeIfNeeded();
1201 
1202   // Find the value in the module map
1203   ValueMap::iterator MI = mMap.find(V);
1204   return MI == mMap.end() ? -1 : (int)MI->second;
1205 }
1206 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Module *,bool)> Fn)1207 void SlotTracker::setProcessHook(
1208     std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
1209         Fn) {
1210   ProcessModuleHookFn = Fn;
1211 }
1212 
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Function *,bool)> Fn)1213 void SlotTracker::setProcessHook(
1214     std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
1215         Fn) {
1216   ProcessFunctionHookFn = Fn;
1217 }
1218 
1219 /// getMetadataSlot - Get the slot number of a MDNode.
createMetadataSlot(const MDNode * N)1220 void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
1221 
1222 /// getMetadataSlot - Get the slot number of a MDNode.
getMetadataSlot(const MDNode * N)1223 int SlotTracker::getMetadataSlot(const MDNode *N) {
1224   // Check for uninitialized state and do lazy initialization.
1225   initializeIfNeeded();
1226 
1227   // Find the MDNode in the module map
1228   mdn_iterator MI = mdnMap.find(N);
1229   return MI == mdnMap.end() ? -1 : (int)MI->second;
1230 }
1231 
1232 /// getLocalSlot - Get the slot number for a value that is local to a function.
getLocalSlot(const Value * V)1233 int SlotTracker::getLocalSlot(const Value *V) {
1234   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1235 
1236   // Check for uninitialized state and do lazy initialization.
1237   initializeIfNeeded();
1238 
1239   ValueMap::iterator FI = fMap.find(V);
1240   return FI == fMap.end() ? -1 : (int)FI->second;
1241 }
1242 
getAttributeGroupSlot(AttributeSet AS)1243 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1244   // Check for uninitialized state and do lazy initialization.
1245   initializeIfNeeded();
1246 
1247   // Find the AttributeSet in the module map.
1248   as_iterator AI = asMap.find(AS);
1249   return AI == asMap.end() ? -1 : (int)AI->second;
1250 }
1251 
getModulePathSlot(StringRef Path)1252 int SlotTracker::getModulePathSlot(StringRef Path) {
1253   // Check for uninitialized state and do lazy initialization.
1254   initializeIndexIfNeeded();
1255 
1256   // Find the Module path in the map
1257   auto I = ModulePathMap.find(Path);
1258   return I == ModulePathMap.end() ? -1 : (int)I->second;
1259 }
1260 
getGUIDSlot(GlobalValue::GUID GUID)1261 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1262   // Check for uninitialized state and do lazy initialization.
1263   initializeIndexIfNeeded();
1264 
1265   // Find the GUID in the map
1266   guid_iterator I = GUIDMap.find(GUID);
1267   return I == GUIDMap.end() ? -1 : (int)I->second;
1268 }
1269 
getTypeIdSlot(StringRef Id)1270 int SlotTracker::getTypeIdSlot(StringRef Id) {
1271   // Check for uninitialized state and do lazy initialization.
1272   initializeIndexIfNeeded();
1273 
1274   // Find the TypeId string in the map
1275   auto I = TypeIdMap.find(Id);
1276   return I == TypeIdMap.end() ? -1 : (int)I->second;
1277 }
1278 
getTypeIdCompatibleVtableSlot(StringRef Id)1279 int SlotTracker::getTypeIdCompatibleVtableSlot(StringRef Id) {
1280   // Check for uninitialized state and do lazy initialization.
1281   initializeIndexIfNeeded();
1282 
1283   // Find the TypeIdCompatibleVtable string in the map
1284   auto I = TypeIdCompatibleVtableMap.find(Id);
1285   return I == TypeIdCompatibleVtableMap.end() ? -1 : (int)I->second;
1286 }
1287 
1288 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
CreateModuleSlot(const GlobalValue * V)1289 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1290   assert(V && "Can't insert a null Value into SlotTracker!");
1291   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1292   assert(!V->hasName() && "Doesn't need a slot!");
1293 
1294   unsigned DestSlot = mNext++;
1295   mMap[V] = DestSlot;
1296 
1297   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1298            DestSlot << " [");
1299   // G = Global, F = Function, A = Alias, I = IFunc, o = other
1300   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1301             (isa<Function>(V) ? 'F' :
1302              (isa<GlobalAlias>(V) ? 'A' :
1303               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1304 }
1305 
1306 /// CreateSlot - Create a new slot for the specified value if it has no name.
CreateFunctionSlot(const Value * V)1307 void SlotTracker::CreateFunctionSlot(const Value *V) {
1308   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1309 
1310   unsigned DestSlot = fNext++;
1311   fMap[V] = DestSlot;
1312 
1313   // G = Global, F = Function, o = other
1314   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1315            DestSlot << " [o]\n");
1316 }
1317 
1318 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
CreateMetadataSlot(const MDNode * N)1319 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1320   assert(N && "Can't insert a null Value into SlotTracker!");
1321 
1322   // Don't make slots for DIExpressions. We just print them inline everywhere.
1323   if (isa<DIExpression>(N))
1324     return;
1325 
1326   unsigned DestSlot = mdnNext;
1327   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1328     return;
1329   ++mdnNext;
1330 
1331   // Recursively add any MDNodes referenced by operands.
1332   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1333     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1334       CreateMetadataSlot(Op);
1335 }
1336 
CreateAttributeSetSlot(AttributeSet AS)1337 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1338   assert(AS.hasAttributes() && "Doesn't need a slot!");
1339 
1340   as_iterator I = asMap.find(AS);
1341   if (I != asMap.end())
1342     return;
1343 
1344   unsigned DestSlot = asNext++;
1345   asMap[AS] = DestSlot;
1346 }
1347 
1348 /// Create a new slot for the specified Module
CreateModulePathSlot(StringRef Path)1349 void SlotTracker::CreateModulePathSlot(StringRef Path) {
1350   ModulePathMap[Path] = ModulePathNext++;
1351 }
1352 
1353 /// Create a new slot for the specified GUID
CreateGUIDSlot(GlobalValue::GUID GUID)1354 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1355   GUIDMap[GUID] = GUIDNext++;
1356 }
1357 
1358 /// Create a new slot for the specified Id
CreateTypeIdSlot(StringRef Id)1359 void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1360   TypeIdMap[Id] = TypeIdNext++;
1361 }
1362 
1363 /// Create a new slot for the specified Id
CreateTypeIdCompatibleVtableSlot(StringRef Id)1364 void SlotTracker::CreateTypeIdCompatibleVtableSlot(StringRef Id) {
1365   TypeIdCompatibleVtableMap[Id] = TypeIdCompatibleVtableNext++;
1366 }
1367 
1368 namespace {
1369 /// Common instances used by most of the printer functions.
1370 struct AsmWriterContext {
1371   TypePrinting *TypePrinter = nullptr;
1372   SlotTracker *Machine = nullptr;
1373   const Module *Context = nullptr;
1374 
AsmWriterContext__anon33b632580511::AsmWriterContext1375   AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
1376       : TypePrinter(TP), Machine(ST), Context(M) {}
1377 
getEmpty__anon33b632580511::AsmWriterContext1378   static AsmWriterContext &getEmpty() {
1379     static AsmWriterContext EmptyCtx(nullptr, nullptr);
1380     return EmptyCtx;
1381   }
1382 
1383   /// A callback that will be triggered when the underlying printer
1384   /// prints a Metadata as operand.
onWriteMetadataAsOperand__anon33b632580511::AsmWriterContext1385   virtual void onWriteMetadataAsOperand(const Metadata *) {}
1386 
1387   virtual ~AsmWriterContext() = default;
1388 };
1389 } // end anonymous namespace
1390 
1391 //===----------------------------------------------------------------------===//
1392 // AsmWriter Implementation
1393 //===----------------------------------------------------------------------===//
1394 
1395 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1396                                    AsmWriterContext &WriterCtx);
1397 
1398 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1399                                    AsmWriterContext &WriterCtx,
1400                                    bool FromValue = false);
1401 
WriteOptimizationInfo(raw_ostream & Out,const User * U)1402 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1403   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
1404     Out << FPO->getFastMathFlags();
1405 
1406   if (const OverflowingBinaryOperator *OBO =
1407         dyn_cast<OverflowingBinaryOperator>(U)) {
1408     if (OBO->hasNoUnsignedWrap())
1409       Out << " nuw";
1410     if (OBO->hasNoSignedWrap())
1411       Out << " nsw";
1412   } else if (const PossiblyExactOperator *Div =
1413                dyn_cast<PossiblyExactOperator>(U)) {
1414     if (Div->isExact())
1415       Out << " exact";
1416   } else if (const PossiblyDisjointInst *PDI =
1417                  dyn_cast<PossiblyDisjointInst>(U)) {
1418     if (PDI->isDisjoint())
1419       Out << " disjoint";
1420   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1421     if (GEP->isInBounds())
1422       Out << " inbounds";
1423     else if (GEP->hasNoUnsignedSignedWrap())
1424       Out << " nusw";
1425     if (GEP->hasNoUnsignedWrap())
1426       Out << " nuw";
1427     if (auto InRange = GEP->getInRange()) {
1428       Out << " inrange(" << InRange->getLower() << ", " << InRange->getUpper()
1429           << ")";
1430     }
1431   } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(U)) {
1432     if (NNI->hasNonNeg())
1433       Out << " nneg";
1434   } else if (const auto *TI = dyn_cast<TruncInst>(U)) {
1435     if (TI->hasNoUnsignedWrap())
1436       Out << " nuw";
1437     if (TI->hasNoSignedWrap())
1438       Out << " nsw";
1439   }
1440 }
1441 
WriteAPFloatInternal(raw_ostream & Out,const APFloat & APF)1442 static void WriteAPFloatInternal(raw_ostream &Out, const APFloat &APF) {
1443   if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1444       &APF.getSemantics() == &APFloat::IEEEdouble()) {
1445     // We would like to output the FP constant value in exponential notation,
1446     // but we cannot do this if doing so will lose precision.  Check here to
1447     // make sure that we only output it in exponential format if we can parse
1448     // the value back and get the same value.
1449     //
1450     bool ignored;
1451     bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1452     bool isInf = APF.isInfinity();
1453     bool isNaN = APF.isNaN();
1454 
1455     if (!isInf && !isNaN) {
1456       double Val = APF.convertToDouble();
1457       SmallString<128> StrVal;
1458       APF.toString(StrVal, 6, 0, false);
1459       // Check to make sure that the stringized number is not some string like
1460       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
1461       // that the string matches the "[-+]?[0-9]" regex.
1462       //
1463       assert((isDigit(StrVal[0]) ||
1464               ((StrVal[0] == '-' || StrVal[0] == '+') && isDigit(StrVal[1]))) &&
1465              "[-+]?[0-9] regex does not match!");
1466       // Reparse stringized version!
1467       if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1468         Out << StrVal;
1469         return;
1470       }
1471     }
1472 
1473     // Otherwise we could not reparse it to exactly the same value, so we must
1474     // output the string in hexadecimal format!  Note that loading and storing
1475     // floating point types changes the bits of NaNs on some hosts, notably
1476     // x86, so we must not use these types.
1477     static_assert(sizeof(double) == sizeof(uint64_t),
1478                   "assuming that double is 64 bits!");
1479     APFloat apf = APF;
1480 
1481     // Floats are represented in ASCII IR as double, convert.
1482     // FIXME: We should allow 32-bit hex float and remove this.
1483     if (!isDouble) {
1484       // A signaling NaN is quieted on conversion, so we need to recreate the
1485       // expected value after convert (quiet bit of the payload is clear).
1486       bool IsSNAN = apf.isSignaling();
1487       apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1488                   &ignored);
1489       if (IsSNAN) {
1490         APInt Payload = apf.bitcastToAPInt();
1491         apf =
1492             APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(), &Payload);
1493       }
1494     }
1495 
1496     Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1497     return;
1498   }
1499 
1500   // Either half, bfloat or some form of long double.
1501   // These appear as a magic letter identifying the type, then a
1502   // fixed number of hex digits.
1503   Out << "0x";
1504   APInt API = APF.bitcastToAPInt();
1505   if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1506     Out << 'K';
1507     Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1508                                 /*Upper=*/true);
1509     Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1510                                 /*Upper=*/true);
1511   } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1512     Out << 'L';
1513     Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1514                                 /*Upper=*/true);
1515     Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1516                                 /*Upper=*/true);
1517   } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1518     Out << 'M';
1519     Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1520                                 /*Upper=*/true);
1521     Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1522                                 /*Upper=*/true);
1523   } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1524     Out << 'H';
1525     Out << format_hex_no_prefix(API.getZExtValue(), 4,
1526                                 /*Upper=*/true);
1527   } else if (&APF.getSemantics() == &APFloat::BFloat()) {
1528     Out << 'R';
1529     Out << format_hex_no_prefix(API.getZExtValue(), 4,
1530                                 /*Upper=*/true);
1531   } else
1532     llvm_unreachable("Unsupported floating point type");
1533 }
1534 
WriteConstantInternal(raw_ostream & Out,const Constant * CV,AsmWriterContext & WriterCtx)1535 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1536                                   AsmWriterContext &WriterCtx) {
1537   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1538     Type *Ty = CI->getType();
1539 
1540     if (Ty->isVectorTy()) {
1541       Out << "splat (";
1542       WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);
1543       Out << " ";
1544     }
1545 
1546     if (Ty->getScalarType()->isIntegerTy(1))
1547       Out << (CI->getZExtValue() ? "true" : "false");
1548     else
1549       Out << CI->getValue();
1550 
1551     if (Ty->isVectorTy())
1552       Out << ")";
1553 
1554     return;
1555   }
1556 
1557   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1558     Type *Ty = CFP->getType();
1559 
1560     if (Ty->isVectorTy()) {
1561       Out << "splat (";
1562       WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);
1563       Out << " ";
1564     }
1565 
1566     WriteAPFloatInternal(Out, CFP->getValueAPF());
1567 
1568     if (Ty->isVectorTy())
1569       Out << ")";
1570 
1571     return;
1572   }
1573 
1574   if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
1575     Out << "zeroinitializer";
1576     return;
1577   }
1578 
1579   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1580     Out << "blockaddress(";
1581     WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
1582     Out << ", ";
1583     WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
1584     Out << ")";
1585     return;
1586   }
1587 
1588   if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1589     Out << "dso_local_equivalent ";
1590     WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
1591     return;
1592   }
1593 
1594   if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
1595     Out << "no_cfi ";
1596     WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
1597     return;
1598   }
1599 
1600   if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV)) {
1601     Out << "ptrauth (";
1602 
1603     // ptrauth (ptr CST, i32 KEY[, i64 DISC[, ptr ADDRDISC]?]?)
1604     unsigned NumOpsToWrite = 2;
1605     if (!CPA->getOperand(2)->isNullValue())
1606       NumOpsToWrite = 3;
1607     if (!CPA->getOperand(3)->isNullValue())
1608       NumOpsToWrite = 4;
1609 
1610     ListSeparator LS;
1611     for (unsigned i = 0, e = NumOpsToWrite; i != e; ++i) {
1612       Out << LS;
1613       WriterCtx.TypePrinter->print(CPA->getOperand(i)->getType(), Out);
1614       Out << ' ';
1615       WriteAsOperandInternal(Out, CPA->getOperand(i), WriterCtx);
1616     }
1617     Out << ')';
1618     return;
1619   }
1620 
1621   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1622     Type *ETy = CA->getType()->getElementType();
1623     Out << '[';
1624     WriterCtx.TypePrinter->print(ETy, Out);
1625     Out << ' ';
1626     WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
1627     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1628       Out << ", ";
1629       WriterCtx.TypePrinter->print(ETy, Out);
1630       Out << ' ';
1631       WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
1632     }
1633     Out << ']';
1634     return;
1635   }
1636 
1637   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1638     // As a special case, print the array as a string if it is an array of
1639     // i8 with ConstantInt values.
1640     if (CA->isString()) {
1641       Out << "c\"";
1642       printEscapedString(CA->getAsString(), Out);
1643       Out << '"';
1644       return;
1645     }
1646 
1647     Type *ETy = CA->getType()->getElementType();
1648     Out << '[';
1649     WriterCtx.TypePrinter->print(ETy, Out);
1650     Out << ' ';
1651     WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
1652     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1653       Out << ", ";
1654       WriterCtx.TypePrinter->print(ETy, Out);
1655       Out << ' ';
1656       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
1657     }
1658     Out << ']';
1659     return;
1660   }
1661 
1662   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1663     if (CS->getType()->isPacked())
1664       Out << '<';
1665     Out << '{';
1666     unsigned N = CS->getNumOperands();
1667     if (N) {
1668       Out << ' ';
1669       WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
1670       Out << ' ';
1671 
1672       WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
1673 
1674       for (unsigned i = 1; i < N; i++) {
1675         Out << ", ";
1676         WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
1677         Out << ' ';
1678 
1679         WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
1680       }
1681       Out << ' ';
1682     }
1683 
1684     Out << '}';
1685     if (CS->getType()->isPacked())
1686       Out << '>';
1687     return;
1688   }
1689 
1690   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1691     auto *CVVTy = cast<FixedVectorType>(CV->getType());
1692     Type *ETy = CVVTy->getElementType();
1693     Out << '<';
1694     WriterCtx.TypePrinter->print(ETy, Out);
1695     Out << ' ';
1696     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
1697     for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1698       Out << ", ";
1699       WriterCtx.TypePrinter->print(ETy, Out);
1700       Out << ' ';
1701       WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
1702     }
1703     Out << '>';
1704     return;
1705   }
1706 
1707   if (isa<ConstantPointerNull>(CV)) {
1708     Out << "null";
1709     return;
1710   }
1711 
1712   if (isa<ConstantTokenNone>(CV)) {
1713     Out << "none";
1714     return;
1715   }
1716 
1717   if (isa<PoisonValue>(CV)) {
1718     Out << "poison";
1719     return;
1720   }
1721 
1722   if (isa<UndefValue>(CV)) {
1723     Out << "undef";
1724     return;
1725   }
1726 
1727   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1728     Out << CE->getOpcodeName();
1729     WriteOptimizationInfo(Out, CE);
1730     Out << " (";
1731 
1732     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1733       WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
1734       Out << ", ";
1735     }
1736 
1737     for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end();
1738          ++OI) {
1739       WriterCtx.TypePrinter->print((*OI)->getType(), Out);
1740       Out << ' ';
1741       WriteAsOperandInternal(Out, *OI, WriterCtx);
1742       if (OI+1 != CE->op_end())
1743         Out << ", ";
1744     }
1745 
1746     if (CE->isCast()) {
1747       Out << " to ";
1748       WriterCtx.TypePrinter->print(CE->getType(), Out);
1749     }
1750 
1751     if (CE->getOpcode() == Instruction::ShuffleVector)
1752       PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1753 
1754     Out << ')';
1755     return;
1756   }
1757 
1758   Out << "<placeholder or erroneous Constant>";
1759 }
1760 
writeMDTuple(raw_ostream & Out,const MDTuple * Node,AsmWriterContext & WriterCtx)1761 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1762                          AsmWriterContext &WriterCtx) {
1763   Out << "!{";
1764   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1765     const Metadata *MD = Node->getOperand(mi);
1766     if (!MD)
1767       Out << "null";
1768     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1769       Value *V = MDV->getValue();
1770       WriterCtx.TypePrinter->print(V->getType(), Out);
1771       Out << ' ';
1772       WriteAsOperandInternal(Out, V, WriterCtx);
1773     } else {
1774       WriteAsOperandInternal(Out, MD, WriterCtx);
1775       WriterCtx.onWriteMetadataAsOperand(MD);
1776     }
1777     if (mi + 1 != me)
1778       Out << ", ";
1779   }
1780 
1781   Out << "}";
1782 }
1783 
1784 namespace {
1785 
1786 struct FieldSeparator {
1787   bool Skip = true;
1788   const char *Sep;
1789 
FieldSeparator__anon33b632580611::FieldSeparator1790   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1791 };
1792 
operator <<(raw_ostream & OS,FieldSeparator & FS)1793 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1794   if (FS.Skip) {
1795     FS.Skip = false;
1796     return OS;
1797   }
1798   return OS << FS.Sep;
1799 }
1800 
1801 struct MDFieldPrinter {
1802   raw_ostream &Out;
1803   FieldSeparator FS;
1804   AsmWriterContext &WriterCtx;
1805 
MDFieldPrinter__anon33b632580611::MDFieldPrinter1806   explicit MDFieldPrinter(raw_ostream &Out)
1807       : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
MDFieldPrinter__anon33b632580611::MDFieldPrinter1808   MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1809       : Out(Out), WriterCtx(Ctx) {}
1810 
1811   void printTag(const DINode *N);
1812   void printMacinfoType(const DIMacroNode *N);
1813   void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1814   void printString(StringRef Name, StringRef Value,
1815                    bool ShouldSkipEmpty = true);
1816   void printMetadata(StringRef Name, const Metadata *MD,
1817                      bool ShouldSkipNull = true);
1818   template <class IntTy>
1819   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1820   void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1821                   bool ShouldSkipZero);
1822   void printBool(StringRef Name, bool Value,
1823                  std::optional<bool> Default = std::nullopt);
1824   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1825   void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1826   template <class IntTy, class Stringifier>
1827   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1828                       bool ShouldSkipZero = true);
1829   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1830   void printNameTableKind(StringRef Name,
1831                           DICompileUnit::DebugNameTableKind NTK);
1832 };
1833 
1834 } // end anonymous namespace
1835 
printTag(const DINode * N)1836 void MDFieldPrinter::printTag(const DINode *N) {
1837   Out << FS << "tag: ";
1838   auto Tag = dwarf::TagString(N->getTag());
1839   if (!Tag.empty())
1840     Out << Tag;
1841   else
1842     Out << N->getTag();
1843 }
1844 
printMacinfoType(const DIMacroNode * N)1845 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1846   Out << FS << "type: ";
1847   auto Type = dwarf::MacinfoString(N->getMacinfoType());
1848   if (!Type.empty())
1849     Out << Type;
1850   else
1851     Out << N->getMacinfoType();
1852 }
1853 
printChecksum(const DIFile::ChecksumInfo<StringRef> & Checksum)1854 void MDFieldPrinter::printChecksum(
1855     const DIFile::ChecksumInfo<StringRef> &Checksum) {
1856   Out << FS << "checksumkind: " << Checksum.getKindAsString();
1857   printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1858 }
1859 
printString(StringRef Name,StringRef Value,bool ShouldSkipEmpty)1860 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1861                                  bool ShouldSkipEmpty) {
1862   if (ShouldSkipEmpty && Value.empty())
1863     return;
1864 
1865   Out << FS << Name << ": \"";
1866   printEscapedString(Value, Out);
1867   Out << "\"";
1868 }
1869 
writeMetadataAsOperand(raw_ostream & Out,const Metadata * MD,AsmWriterContext & WriterCtx)1870 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1871                                    AsmWriterContext &WriterCtx) {
1872   if (!MD) {
1873     Out << "null";
1874     return;
1875   }
1876   WriteAsOperandInternal(Out, MD, WriterCtx);
1877   WriterCtx.onWriteMetadataAsOperand(MD);
1878 }
1879 
printMetadata(StringRef Name,const Metadata * MD,bool ShouldSkipNull)1880 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1881                                    bool ShouldSkipNull) {
1882   if (ShouldSkipNull && !MD)
1883     return;
1884 
1885   Out << FS << Name << ": ";
1886   writeMetadataAsOperand(Out, MD, WriterCtx);
1887 }
1888 
1889 template <class IntTy>
printInt(StringRef Name,IntTy Int,bool ShouldSkipZero)1890 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1891   if (ShouldSkipZero && !Int)
1892     return;
1893 
1894   Out << FS << Name << ": " << Int;
1895 }
1896 
printAPInt(StringRef Name,const APInt & Int,bool IsUnsigned,bool ShouldSkipZero)1897 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1898                                 bool IsUnsigned, bool ShouldSkipZero) {
1899   if (ShouldSkipZero && Int.isZero())
1900     return;
1901 
1902   Out << FS << Name << ": ";
1903   Int.print(Out, !IsUnsigned);
1904 }
1905 
printBool(StringRef Name,bool Value,std::optional<bool> Default)1906 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1907                                std::optional<bool> Default) {
1908   if (Default && Value == *Default)
1909     return;
1910   Out << FS << Name << ": " << (Value ? "true" : "false");
1911 }
1912 
printDIFlags(StringRef Name,DINode::DIFlags Flags)1913 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1914   if (!Flags)
1915     return;
1916 
1917   Out << FS << Name << ": ";
1918 
1919   SmallVector<DINode::DIFlags, 8> SplitFlags;
1920   auto Extra = DINode::splitFlags(Flags, SplitFlags);
1921 
1922   FieldSeparator FlagsFS(" | ");
1923   for (auto F : SplitFlags) {
1924     auto StringF = DINode::getFlagString(F);
1925     assert(!StringF.empty() && "Expected valid flag");
1926     Out << FlagsFS << StringF;
1927   }
1928   if (Extra || SplitFlags.empty())
1929     Out << FlagsFS << Extra;
1930 }
1931 
printDISPFlags(StringRef Name,DISubprogram::DISPFlags Flags)1932 void MDFieldPrinter::printDISPFlags(StringRef Name,
1933                                     DISubprogram::DISPFlags Flags) {
1934   // Always print this field, because no flags in the IR at all will be
1935   // interpreted as old-style isDefinition: true.
1936   Out << FS << Name << ": ";
1937 
1938   if (!Flags) {
1939     Out << 0;
1940     return;
1941   }
1942 
1943   SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1944   auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1945 
1946   FieldSeparator FlagsFS(" | ");
1947   for (auto F : SplitFlags) {
1948     auto StringF = DISubprogram::getFlagString(F);
1949     assert(!StringF.empty() && "Expected valid flag");
1950     Out << FlagsFS << StringF;
1951   }
1952   if (Extra || SplitFlags.empty())
1953     Out << FlagsFS << Extra;
1954 }
1955 
printEmissionKind(StringRef Name,DICompileUnit::DebugEmissionKind EK)1956 void MDFieldPrinter::printEmissionKind(StringRef Name,
1957                                        DICompileUnit::DebugEmissionKind EK) {
1958   Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1959 }
1960 
printNameTableKind(StringRef Name,DICompileUnit::DebugNameTableKind NTK)1961 void MDFieldPrinter::printNameTableKind(StringRef Name,
1962                                         DICompileUnit::DebugNameTableKind NTK) {
1963   if (NTK == DICompileUnit::DebugNameTableKind::Default)
1964     return;
1965   Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1966 }
1967 
1968 template <class IntTy, class Stringifier>
printDwarfEnum(StringRef Name,IntTy Value,Stringifier toString,bool ShouldSkipZero)1969 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1970                                     Stringifier toString, bool ShouldSkipZero) {
1971   if (!Value)
1972     return;
1973 
1974   Out << FS << Name << ": ";
1975   auto S = toString(Value);
1976   if (!S.empty())
1977     Out << S;
1978   else
1979     Out << Value;
1980 }
1981 
writeGenericDINode(raw_ostream & Out,const GenericDINode * N,AsmWriterContext & WriterCtx)1982 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1983                                AsmWriterContext &WriterCtx) {
1984   Out << "!GenericDINode(";
1985   MDFieldPrinter Printer(Out, WriterCtx);
1986   Printer.printTag(N);
1987   Printer.printString("header", N->getHeader());
1988   if (N->getNumDwarfOperands()) {
1989     Out << Printer.FS << "operands: {";
1990     FieldSeparator IFS;
1991     for (auto &I : N->dwarf_operands()) {
1992       Out << IFS;
1993       writeMetadataAsOperand(Out, I, WriterCtx);
1994     }
1995     Out << "}";
1996   }
1997   Out << ")";
1998 }
1999 
writeDILocation(raw_ostream & Out,const DILocation * DL,AsmWriterContext & WriterCtx)2000 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
2001                             AsmWriterContext &WriterCtx) {
2002   Out << "!DILocation(";
2003   MDFieldPrinter Printer(Out, WriterCtx);
2004   // Always output the line, since 0 is a relevant and important value for it.
2005   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
2006   Printer.printInt("column", DL->getColumn());
2007   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
2008   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
2009   Printer.printBool("isImplicitCode", DL->isImplicitCode(),
2010                     /* Default */ false);
2011   Out << ")";
2012 }
2013 
writeDIAssignID(raw_ostream & Out,const DIAssignID * DL,AsmWriterContext & WriterCtx)2014 static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
2015                             AsmWriterContext &WriterCtx) {
2016   Out << "!DIAssignID()";
2017   MDFieldPrinter Printer(Out, WriterCtx);
2018 }
2019 
writeDISubrange(raw_ostream & Out,const DISubrange * N,AsmWriterContext & WriterCtx)2020 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
2021                             AsmWriterContext &WriterCtx) {
2022   Out << "!DISubrange(";
2023   MDFieldPrinter Printer(Out, WriterCtx);
2024 
2025   auto *Count = N->getRawCountNode();
2026   if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
2027     auto *CV = cast<ConstantInt>(CE->getValue());
2028     Printer.printInt("count", CV->getSExtValue(),
2029                      /* ShouldSkipZero */ false);
2030   } else
2031     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
2032 
2033   // A lowerBound of constant 0 should not be skipped, since it is different
2034   // from an unspecified lower bound (= nullptr).
2035   auto *LBound = N->getRawLowerBound();
2036   if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
2037     auto *LV = cast<ConstantInt>(LE->getValue());
2038     Printer.printInt("lowerBound", LV->getSExtValue(),
2039                      /* ShouldSkipZero */ false);
2040   } else
2041     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
2042 
2043   auto *UBound = N->getRawUpperBound();
2044   if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
2045     auto *UV = cast<ConstantInt>(UE->getValue());
2046     Printer.printInt("upperBound", UV->getSExtValue(),
2047                      /* ShouldSkipZero */ false);
2048   } else
2049     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
2050 
2051   auto *Stride = N->getRawStride();
2052   if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
2053     auto *SV = cast<ConstantInt>(SE->getValue());
2054     Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
2055   } else
2056     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
2057 
2058   Out << ")";
2059 }
2060 
writeDIGenericSubrange(raw_ostream & Out,const DIGenericSubrange * N,AsmWriterContext & WriterCtx)2061 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
2062                                    AsmWriterContext &WriterCtx) {
2063   Out << "!DIGenericSubrange(";
2064   MDFieldPrinter Printer(Out, WriterCtx);
2065 
2066   auto IsConstant = [&](Metadata *Bound) -> bool {
2067     if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
2068       return BE->isConstant() &&
2069              DIExpression::SignedOrUnsignedConstant::SignedConstant ==
2070                  *BE->isConstant();
2071     }
2072     return false;
2073   };
2074 
2075   auto GetConstant = [&](Metadata *Bound) -> int64_t {
2076     assert(IsConstant(Bound) && "Expected constant");
2077     auto *BE = dyn_cast_or_null<DIExpression>(Bound);
2078     return static_cast<int64_t>(BE->getElement(1));
2079   };
2080 
2081   auto *Count = N->getRawCountNode();
2082   if (IsConstant(Count))
2083     Printer.printInt("count", GetConstant(Count),
2084                      /* ShouldSkipZero */ false);
2085   else
2086     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
2087 
2088   auto *LBound = N->getRawLowerBound();
2089   if (IsConstant(LBound))
2090     Printer.printInt("lowerBound", GetConstant(LBound),
2091                      /* ShouldSkipZero */ false);
2092   else
2093     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
2094 
2095   auto *UBound = N->getRawUpperBound();
2096   if (IsConstant(UBound))
2097     Printer.printInt("upperBound", GetConstant(UBound),
2098                      /* ShouldSkipZero */ false);
2099   else
2100     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
2101 
2102   auto *Stride = N->getRawStride();
2103   if (IsConstant(Stride))
2104     Printer.printInt("stride", GetConstant(Stride),
2105                      /* ShouldSkipZero */ false);
2106   else
2107     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
2108 
2109   Out << ")";
2110 }
2111 
writeDIEnumerator(raw_ostream & Out,const DIEnumerator * N,AsmWriterContext &)2112 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
2113                               AsmWriterContext &) {
2114   Out << "!DIEnumerator(";
2115   MDFieldPrinter Printer(Out);
2116   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
2117   Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
2118                      /*ShouldSkipZero=*/false);
2119   if (N->isUnsigned())
2120     Printer.printBool("isUnsigned", true);
2121   Out << ")";
2122 }
2123 
writeDIBasicType(raw_ostream & Out,const DIBasicType * N,AsmWriterContext &)2124 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
2125                              AsmWriterContext &) {
2126   Out << "!DIBasicType(";
2127   MDFieldPrinter Printer(Out);
2128   if (N->getTag() != dwarf::DW_TAG_base_type)
2129     Printer.printTag(N);
2130   Printer.printString("name", N->getName());
2131   Printer.printInt("size", N->getSizeInBits());
2132   Printer.printInt("align", N->getAlignInBits());
2133   Printer.printDwarfEnum("encoding", N->getEncoding(),
2134                          dwarf::AttributeEncodingString);
2135   Printer.printDIFlags("flags", N->getFlags());
2136   Out << ")";
2137 }
2138 
writeDIStringType(raw_ostream & Out,const DIStringType * N,AsmWriterContext & WriterCtx)2139 static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2140                               AsmWriterContext &WriterCtx) {
2141   Out << "!DIStringType(";
2142   MDFieldPrinter Printer(Out, WriterCtx);
2143   if (N->getTag() != dwarf::DW_TAG_string_type)
2144     Printer.printTag(N);
2145   Printer.printString("name", N->getName());
2146   Printer.printMetadata("stringLength", N->getRawStringLength());
2147   Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2148   Printer.printMetadata("stringLocationExpression",
2149                         N->getRawStringLocationExp());
2150   Printer.printInt("size", N->getSizeInBits());
2151   Printer.printInt("align", N->getAlignInBits());
2152   Printer.printDwarfEnum("encoding", N->getEncoding(),
2153                          dwarf::AttributeEncodingString);
2154   Out << ")";
2155 }
2156 
writeDIDerivedType(raw_ostream & Out,const DIDerivedType * N,AsmWriterContext & WriterCtx)2157 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2158                                AsmWriterContext &WriterCtx) {
2159   Out << "!DIDerivedType(";
2160   MDFieldPrinter Printer(Out, WriterCtx);
2161   Printer.printTag(N);
2162   Printer.printString("name", N->getName());
2163   Printer.printMetadata("scope", N->getRawScope());
2164   Printer.printMetadata("file", N->getRawFile());
2165   Printer.printInt("line", N->getLine());
2166   Printer.printMetadata("baseType", N->getRawBaseType(),
2167                         /* ShouldSkipNull */ false);
2168   Printer.printInt("size", N->getSizeInBits());
2169   Printer.printInt("align", N->getAlignInBits());
2170   Printer.printInt("offset", N->getOffsetInBits());
2171   Printer.printDIFlags("flags", N->getFlags());
2172   Printer.printMetadata("extraData", N->getRawExtraData());
2173   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2174     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2175                      /* ShouldSkipZero */ false);
2176   Printer.printMetadata("annotations", N->getRawAnnotations());
2177   if (auto PtrAuthData = N->getPtrAuthData()) {
2178     Printer.printInt("ptrAuthKey", PtrAuthData->key());
2179     Printer.printBool("ptrAuthIsAddressDiscriminated",
2180                       PtrAuthData->isAddressDiscriminated());
2181     Printer.printInt("ptrAuthExtraDiscriminator",
2182                      PtrAuthData->extraDiscriminator());
2183     Printer.printBool("ptrAuthIsaPointer", PtrAuthData->isaPointer());
2184     Printer.printBool("ptrAuthAuthenticatesNullValues",
2185                       PtrAuthData->authenticatesNullValues());
2186   }
2187   Out << ")";
2188 }
2189 
writeDICompositeType(raw_ostream & Out,const DICompositeType * N,AsmWriterContext & WriterCtx)2190 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2191                                  AsmWriterContext &WriterCtx) {
2192   Out << "!DICompositeType(";
2193   MDFieldPrinter Printer(Out, WriterCtx);
2194   Printer.printTag(N);
2195   Printer.printString("name", N->getName());
2196   Printer.printMetadata("scope", N->getRawScope());
2197   Printer.printMetadata("file", N->getRawFile());
2198   Printer.printInt("line", N->getLine());
2199   Printer.printMetadata("baseType", N->getRawBaseType());
2200   Printer.printInt("size", N->getSizeInBits());
2201   Printer.printInt("align", N->getAlignInBits());
2202   Printer.printInt("offset", N->getOffsetInBits());
2203   Printer.printDIFlags("flags", N->getFlags());
2204   Printer.printMetadata("elements", N->getRawElements());
2205   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2206                          dwarf::LanguageString);
2207   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2208   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2209   Printer.printString("identifier", N->getIdentifier());
2210   Printer.printMetadata("discriminator", N->getRawDiscriminator());
2211   Printer.printMetadata("dataLocation", N->getRawDataLocation());
2212   Printer.printMetadata("associated", N->getRawAssociated());
2213   Printer.printMetadata("allocated", N->getRawAllocated());
2214   if (auto *RankConst = N->getRankConst())
2215     Printer.printInt("rank", RankConst->getSExtValue(),
2216                      /* ShouldSkipZero */ false);
2217   else
2218     Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2219   Printer.printMetadata("annotations", N->getRawAnnotations());
2220   Out << ")";
2221 }
2222 
writeDISubroutineType(raw_ostream & Out,const DISubroutineType * N,AsmWriterContext & WriterCtx)2223 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2224                                   AsmWriterContext &WriterCtx) {
2225   Out << "!DISubroutineType(";
2226   MDFieldPrinter Printer(Out, WriterCtx);
2227   Printer.printDIFlags("flags", N->getFlags());
2228   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2229   Printer.printMetadata("types", N->getRawTypeArray(),
2230                         /* ShouldSkipNull */ false);
2231   Out << ")";
2232 }
2233 
writeDIFile(raw_ostream & Out,const DIFile * N,AsmWriterContext &)2234 static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
2235   Out << "!DIFile(";
2236   MDFieldPrinter Printer(Out);
2237   Printer.printString("filename", N->getFilename(),
2238                       /* ShouldSkipEmpty */ false);
2239   Printer.printString("directory", N->getDirectory(),
2240                       /* ShouldSkipEmpty */ false);
2241   // Print all values for checksum together, or not at all.
2242   if (N->getChecksum())
2243     Printer.printChecksum(*N->getChecksum());
2244   Printer.printString("source", N->getSource().value_or(StringRef()),
2245                       /* ShouldSkipEmpty */ true);
2246   Out << ")";
2247 }
2248 
writeDICompileUnit(raw_ostream & Out,const DICompileUnit * N,AsmWriterContext & WriterCtx)2249 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2250                                AsmWriterContext &WriterCtx) {
2251   Out << "!DICompileUnit(";
2252   MDFieldPrinter Printer(Out, WriterCtx);
2253   Printer.printDwarfEnum("language", N->getSourceLanguage(),
2254                          dwarf::LanguageString, /* ShouldSkipZero */ false);
2255   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2256   Printer.printString("producer", N->getProducer());
2257   Printer.printBool("isOptimized", N->isOptimized());
2258   Printer.printString("flags", N->getFlags());
2259   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2260                    /* ShouldSkipZero */ false);
2261   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2262   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2263   Printer.printMetadata("enums", N->getRawEnumTypes());
2264   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2265   Printer.printMetadata("globals", N->getRawGlobalVariables());
2266   Printer.printMetadata("imports", N->getRawImportedEntities());
2267   Printer.printMetadata("macros", N->getRawMacros());
2268   Printer.printInt("dwoId", N->getDWOId());
2269   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2270   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2271                     false);
2272   Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2273   Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2274   Printer.printString("sysroot", N->getSysRoot());
2275   Printer.printString("sdk", N->getSDK());
2276   Out << ")";
2277 }
2278 
writeDISubprogram(raw_ostream & Out,const DISubprogram * N,AsmWriterContext & WriterCtx)2279 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2280                               AsmWriterContext &WriterCtx) {
2281   Out << "!DISubprogram(";
2282   MDFieldPrinter Printer(Out, WriterCtx);
2283   Printer.printString("name", N->getName());
2284   Printer.printString("linkageName", N->getLinkageName());
2285   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2286   Printer.printMetadata("file", N->getRawFile());
2287   Printer.printInt("line", N->getLine());
2288   Printer.printMetadata("type", N->getRawType());
2289   Printer.printInt("scopeLine", N->getScopeLine());
2290   Printer.printMetadata("containingType", N->getRawContainingType());
2291   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2292       N->getVirtualIndex() != 0)
2293     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2294   Printer.printInt("thisAdjustment", N->getThisAdjustment());
2295   Printer.printDIFlags("flags", N->getFlags());
2296   Printer.printDISPFlags("spFlags", N->getSPFlags());
2297   Printer.printMetadata("unit", N->getRawUnit());
2298   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2299   Printer.printMetadata("declaration", N->getRawDeclaration());
2300   Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2301   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2302   Printer.printMetadata("annotations", N->getRawAnnotations());
2303   Printer.printString("targetFuncName", N->getTargetFuncName());
2304   Out << ")";
2305 }
2306 
writeDILexicalBlock(raw_ostream & Out,const DILexicalBlock * N,AsmWriterContext & WriterCtx)2307 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2308                                 AsmWriterContext &WriterCtx) {
2309   Out << "!DILexicalBlock(";
2310   MDFieldPrinter Printer(Out, WriterCtx);
2311   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2312   Printer.printMetadata("file", N->getRawFile());
2313   Printer.printInt("line", N->getLine());
2314   Printer.printInt("column", N->getColumn());
2315   Out << ")";
2316 }
2317 
writeDILexicalBlockFile(raw_ostream & Out,const DILexicalBlockFile * N,AsmWriterContext & WriterCtx)2318 static void writeDILexicalBlockFile(raw_ostream &Out,
2319                                     const DILexicalBlockFile *N,
2320                                     AsmWriterContext &WriterCtx) {
2321   Out << "!DILexicalBlockFile(";
2322   MDFieldPrinter Printer(Out, WriterCtx);
2323   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2324   Printer.printMetadata("file", N->getRawFile());
2325   Printer.printInt("discriminator", N->getDiscriminator(),
2326                    /* ShouldSkipZero */ false);
2327   Out << ")";
2328 }
2329 
writeDINamespace(raw_ostream & Out,const DINamespace * N,AsmWriterContext & WriterCtx)2330 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2331                              AsmWriterContext &WriterCtx) {
2332   Out << "!DINamespace(";
2333   MDFieldPrinter Printer(Out, WriterCtx);
2334   Printer.printString("name", N->getName());
2335   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2336   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2337   Out << ")";
2338 }
2339 
writeDICommonBlock(raw_ostream & Out,const DICommonBlock * N,AsmWriterContext & WriterCtx)2340 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2341                                AsmWriterContext &WriterCtx) {
2342   Out << "!DICommonBlock(";
2343   MDFieldPrinter Printer(Out, WriterCtx);
2344   Printer.printMetadata("scope", N->getRawScope(), false);
2345   Printer.printMetadata("declaration", N->getRawDecl(), false);
2346   Printer.printString("name", N->getName());
2347   Printer.printMetadata("file", N->getRawFile());
2348   Printer.printInt("line", N->getLineNo());
2349   Out << ")";
2350 }
2351 
writeDIMacro(raw_ostream & Out,const DIMacro * N,AsmWriterContext & WriterCtx)2352 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2353                          AsmWriterContext &WriterCtx) {
2354   Out << "!DIMacro(";
2355   MDFieldPrinter Printer(Out, WriterCtx);
2356   Printer.printMacinfoType(N);
2357   Printer.printInt("line", N->getLine());
2358   Printer.printString("name", N->getName());
2359   Printer.printString("value", N->getValue());
2360   Out << ")";
2361 }
2362 
writeDIMacroFile(raw_ostream & Out,const DIMacroFile * N,AsmWriterContext & WriterCtx)2363 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2364                              AsmWriterContext &WriterCtx) {
2365   Out << "!DIMacroFile(";
2366   MDFieldPrinter Printer(Out, WriterCtx);
2367   Printer.printInt("line", N->getLine());
2368   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2369   Printer.printMetadata("nodes", N->getRawElements());
2370   Out << ")";
2371 }
2372 
writeDIModule(raw_ostream & Out,const DIModule * N,AsmWriterContext & WriterCtx)2373 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2374                           AsmWriterContext &WriterCtx) {
2375   Out << "!DIModule(";
2376   MDFieldPrinter Printer(Out, WriterCtx);
2377   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2378   Printer.printString("name", N->getName());
2379   Printer.printString("configMacros", N->getConfigurationMacros());
2380   Printer.printString("includePath", N->getIncludePath());
2381   Printer.printString("apinotes", N->getAPINotesFile());
2382   Printer.printMetadata("file", N->getRawFile());
2383   Printer.printInt("line", N->getLineNo());
2384   Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
2385   Out << ")";
2386 }
2387 
writeDITemplateTypeParameter(raw_ostream & Out,const DITemplateTypeParameter * N,AsmWriterContext & WriterCtx)2388 static void writeDITemplateTypeParameter(raw_ostream &Out,
2389                                          const DITemplateTypeParameter *N,
2390                                          AsmWriterContext &WriterCtx) {
2391   Out << "!DITemplateTypeParameter(";
2392   MDFieldPrinter Printer(Out, WriterCtx);
2393   Printer.printString("name", N->getName());
2394   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2395   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2396   Out << ")";
2397 }
2398 
writeDITemplateValueParameter(raw_ostream & Out,const DITemplateValueParameter * N,AsmWriterContext & WriterCtx)2399 static void writeDITemplateValueParameter(raw_ostream &Out,
2400                                           const DITemplateValueParameter *N,
2401                                           AsmWriterContext &WriterCtx) {
2402   Out << "!DITemplateValueParameter(";
2403   MDFieldPrinter Printer(Out, WriterCtx);
2404   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2405     Printer.printTag(N);
2406   Printer.printString("name", N->getName());
2407   Printer.printMetadata("type", N->getRawType());
2408   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2409   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2410   Out << ")";
2411 }
2412 
writeDIGlobalVariable(raw_ostream & Out,const DIGlobalVariable * N,AsmWriterContext & WriterCtx)2413 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2414                                   AsmWriterContext &WriterCtx) {
2415   Out << "!DIGlobalVariable(";
2416   MDFieldPrinter Printer(Out, WriterCtx);
2417   Printer.printString("name", N->getName());
2418   Printer.printString("linkageName", N->getLinkageName());
2419   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2420   Printer.printMetadata("file", N->getRawFile());
2421   Printer.printInt("line", N->getLine());
2422   Printer.printMetadata("type", N->getRawType());
2423   Printer.printBool("isLocal", N->isLocalToUnit());
2424   Printer.printBool("isDefinition", N->isDefinition());
2425   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2426   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2427   Printer.printInt("align", N->getAlignInBits());
2428   Printer.printMetadata("annotations", N->getRawAnnotations());
2429   Out << ")";
2430 }
2431 
writeDILocalVariable(raw_ostream & Out,const DILocalVariable * N,AsmWriterContext & WriterCtx)2432 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2433                                  AsmWriterContext &WriterCtx) {
2434   Out << "!DILocalVariable(";
2435   MDFieldPrinter Printer(Out, WriterCtx);
2436   Printer.printString("name", N->getName());
2437   Printer.printInt("arg", N->getArg());
2438   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2439   Printer.printMetadata("file", N->getRawFile());
2440   Printer.printInt("line", N->getLine());
2441   Printer.printMetadata("type", N->getRawType());
2442   Printer.printDIFlags("flags", N->getFlags());
2443   Printer.printInt("align", N->getAlignInBits());
2444   Printer.printMetadata("annotations", N->getRawAnnotations());
2445   Out << ")";
2446 }
2447 
writeDILabel(raw_ostream & Out,const DILabel * N,AsmWriterContext & WriterCtx)2448 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2449                          AsmWriterContext &WriterCtx) {
2450   Out << "!DILabel(";
2451   MDFieldPrinter Printer(Out, WriterCtx);
2452   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2453   Printer.printString("name", N->getName());
2454   Printer.printMetadata("file", N->getRawFile());
2455   Printer.printInt("line", N->getLine());
2456   Out << ")";
2457 }
2458 
writeDIExpression(raw_ostream & Out,const DIExpression * N,AsmWriterContext & WriterCtx)2459 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2460                               AsmWriterContext &WriterCtx) {
2461   Out << "!DIExpression(";
2462   FieldSeparator FS;
2463   if (N->isValid()) {
2464     for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2465       auto OpStr = dwarf::OperationEncodingString(Op.getOp());
2466       assert(!OpStr.empty() && "Expected valid opcode");
2467 
2468       Out << FS << OpStr;
2469       if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2470         Out << FS << Op.getArg(0);
2471         Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
2472       } else {
2473         for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2474           Out << FS << Op.getArg(A);
2475       }
2476     }
2477   } else {
2478     for (const auto &I : N->getElements())
2479       Out << FS << I;
2480   }
2481   Out << ")";
2482 }
2483 
writeDIArgList(raw_ostream & Out,const DIArgList * N,AsmWriterContext & WriterCtx,bool FromValue=false)2484 static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2485                            AsmWriterContext &WriterCtx,
2486                            bool FromValue = false) {
2487   assert(FromValue &&
2488          "Unexpected DIArgList metadata outside of value argument");
2489   Out << "!DIArgList(";
2490   FieldSeparator FS;
2491   MDFieldPrinter Printer(Out, WriterCtx);
2492   for (Metadata *Arg : N->getArgs()) {
2493     Out << FS;
2494     WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2495   }
2496   Out << ")";
2497 }
2498 
writeDIGlobalVariableExpression(raw_ostream & Out,const DIGlobalVariableExpression * N,AsmWriterContext & WriterCtx)2499 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2500                                             const DIGlobalVariableExpression *N,
2501                                             AsmWriterContext &WriterCtx) {
2502   Out << "!DIGlobalVariableExpression(";
2503   MDFieldPrinter Printer(Out, WriterCtx);
2504   Printer.printMetadata("var", N->getVariable());
2505   Printer.printMetadata("expr", N->getExpression());
2506   Out << ")";
2507 }
2508 
writeDIObjCProperty(raw_ostream & Out,const DIObjCProperty * N,AsmWriterContext & WriterCtx)2509 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2510                                 AsmWriterContext &WriterCtx) {
2511   Out << "!DIObjCProperty(";
2512   MDFieldPrinter Printer(Out, WriterCtx);
2513   Printer.printString("name", N->getName());
2514   Printer.printMetadata("file", N->getRawFile());
2515   Printer.printInt("line", N->getLine());
2516   Printer.printString("setter", N->getSetterName());
2517   Printer.printString("getter", N->getGetterName());
2518   Printer.printInt("attributes", N->getAttributes());
2519   Printer.printMetadata("type", N->getRawType());
2520   Out << ")";
2521 }
2522 
writeDIImportedEntity(raw_ostream & Out,const DIImportedEntity * N,AsmWriterContext & WriterCtx)2523 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2524                                   AsmWriterContext &WriterCtx) {
2525   Out << "!DIImportedEntity(";
2526   MDFieldPrinter Printer(Out, WriterCtx);
2527   Printer.printTag(N);
2528   Printer.printString("name", N->getName());
2529   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2530   Printer.printMetadata("entity", N->getRawEntity());
2531   Printer.printMetadata("file", N->getRawFile());
2532   Printer.printInt("line", N->getLine());
2533   Printer.printMetadata("elements", N->getRawElements());
2534   Out << ")";
2535 }
2536 
WriteMDNodeBodyInternal(raw_ostream & Out,const MDNode * Node,AsmWriterContext & Ctx)2537 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2538                                     AsmWriterContext &Ctx) {
2539   if (Node->isDistinct())
2540     Out << "distinct ";
2541   else if (Node->isTemporary())
2542     Out << "<temporary!> "; // Handle broken code.
2543 
2544   switch (Node->getMetadataID()) {
2545   default:
2546     llvm_unreachable("Expected uniquable MDNode");
2547 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
2548   case Metadata::CLASS##Kind:                                                  \
2549     write##CLASS(Out, cast<CLASS>(Node), Ctx);                                 \
2550     break;
2551 #include "llvm/IR/Metadata.def"
2552   }
2553 }
2554 
2555 // Full implementation of printing a Value as an operand with support for
2556 // TypePrinting, etc.
WriteAsOperandInternal(raw_ostream & Out,const Value * V,AsmWriterContext & WriterCtx)2557 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2558                                    AsmWriterContext &WriterCtx) {
2559   if (V->hasName()) {
2560     PrintLLVMName(Out, V);
2561     return;
2562   }
2563 
2564   const Constant *CV = dyn_cast<Constant>(V);
2565   if (CV && !isa<GlobalValue>(CV)) {
2566     assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2567     WriteConstantInternal(Out, CV, WriterCtx);
2568     return;
2569   }
2570 
2571   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2572     Out << "asm ";
2573     if (IA->hasSideEffects())
2574       Out << "sideeffect ";
2575     if (IA->isAlignStack())
2576       Out << "alignstack ";
2577     // We don't emit the AD_ATT dialect as it's the assumed default.
2578     if (IA->getDialect() == InlineAsm::AD_Intel)
2579       Out << "inteldialect ";
2580     if (IA->canThrow())
2581       Out << "unwind ";
2582     Out << '"';
2583     printEscapedString(IA->getAsmString(), Out);
2584     Out << "\", \"";
2585     printEscapedString(IA->getConstraintString(), Out);
2586     Out << '"';
2587     return;
2588   }
2589 
2590   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2591     WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
2592                            /* FromValue */ true);
2593     return;
2594   }
2595 
2596   char Prefix = '%';
2597   int Slot;
2598   auto *Machine = WriterCtx.Machine;
2599   // If we have a SlotTracker, use it.
2600   if (Machine) {
2601     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2602       Slot = Machine->getGlobalSlot(GV);
2603       Prefix = '@';
2604     } else {
2605       Slot = Machine->getLocalSlot(V);
2606 
2607       // If the local value didn't succeed, then we may be referring to a value
2608       // from a different function.  Translate it, as this can happen when using
2609       // address of blocks.
2610       if (Slot == -1)
2611         if ((Machine = createSlotTracker(V))) {
2612           Slot = Machine->getLocalSlot(V);
2613           delete Machine;
2614         }
2615     }
2616   } else if ((Machine = createSlotTracker(V))) {
2617     // Otherwise, create one to get the # and then destroy it.
2618     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2619       Slot = Machine->getGlobalSlot(GV);
2620       Prefix = '@';
2621     } else {
2622       Slot = Machine->getLocalSlot(V);
2623     }
2624     delete Machine;
2625     Machine = nullptr;
2626   } else {
2627     Slot = -1;
2628   }
2629 
2630   if (Slot != -1)
2631     Out << Prefix << Slot;
2632   else
2633     Out << "<badref>";
2634 }
2635 
WriteAsOperandInternal(raw_ostream & Out,const Metadata * MD,AsmWriterContext & WriterCtx,bool FromValue)2636 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2637                                    AsmWriterContext &WriterCtx,
2638                                    bool FromValue) {
2639   // Write DIExpressions and DIArgLists inline when used as a value. Improves
2640   // readability of debug info intrinsics.
2641   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2642     writeDIExpression(Out, Expr, WriterCtx);
2643     return;
2644   }
2645   if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2646     writeDIArgList(Out, ArgList, WriterCtx, FromValue);
2647     return;
2648   }
2649 
2650   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2651     std::unique_ptr<SlotTracker> MachineStorage;
2652     SaveAndRestore SARMachine(WriterCtx.Machine);
2653     if (!WriterCtx.Machine) {
2654       MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2655       WriterCtx.Machine = MachineStorage.get();
2656     }
2657     int Slot = WriterCtx.Machine->getMetadataSlot(N);
2658     if (Slot == -1) {
2659       if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2660         writeDILocation(Out, Loc, WriterCtx);
2661         return;
2662       }
2663       // Give the pointer value instead of "badref", since this comes up all
2664       // the time when debugging.
2665       Out << "<" << N << ">";
2666     } else
2667       Out << '!' << Slot;
2668     return;
2669   }
2670 
2671   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2672     Out << "!\"";
2673     printEscapedString(MDS->getString(), Out);
2674     Out << '"';
2675     return;
2676   }
2677 
2678   auto *V = cast<ValueAsMetadata>(MD);
2679   assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
2680   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2681          "Unexpected function-local metadata outside of value argument");
2682 
2683   WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
2684   Out << ' ';
2685   WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
2686 }
2687 
2688 namespace {
2689 
2690 class AssemblyWriter {
2691   formatted_raw_ostream &Out;
2692   const Module *TheModule = nullptr;
2693   const ModuleSummaryIndex *TheIndex = nullptr;
2694   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2695   SlotTracker &Machine;
2696   TypePrinting TypePrinter;
2697   AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2698   SetVector<const Comdat *> Comdats;
2699   bool IsForDebug;
2700   bool ShouldPreserveUseListOrder;
2701   UseListOrderMap UseListOrders;
2702   SmallVector<StringRef, 8> MDNames;
2703   /// Synchronization scope names registered with LLVMContext.
2704   SmallVector<StringRef, 8> SSNs;
2705   DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2706 
2707 public:
2708   /// Construct an AssemblyWriter with an external SlotTracker
2709   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2710                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2711                  bool ShouldPreserveUseListOrder = false);
2712 
2713   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2714                  const ModuleSummaryIndex *Index, bool IsForDebug);
2715 
getContext()2716   AsmWriterContext getContext() {
2717     return AsmWriterContext(&TypePrinter, &Machine, TheModule);
2718   }
2719 
2720   void printMDNodeBody(const MDNode *MD);
2721   void printNamedMDNode(const NamedMDNode *NMD);
2722 
2723   void printModule(const Module *M);
2724 
2725   void writeOperand(const Value *Op, bool PrintType);
2726   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2727   void writeOperandBundles(const CallBase *Call);
2728   void writeSyncScope(const LLVMContext &Context,
2729                       SyncScope::ID SSID);
2730   void writeAtomic(const LLVMContext &Context,
2731                    AtomicOrdering Ordering,
2732                    SyncScope::ID SSID);
2733   void writeAtomicCmpXchg(const LLVMContext &Context,
2734                           AtomicOrdering SuccessOrdering,
2735                           AtomicOrdering FailureOrdering,
2736                           SyncScope::ID SSID);
2737 
2738   void writeAllMDNodes();
2739   void writeMDNode(unsigned Slot, const MDNode *Node);
2740   void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2741   void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
2742   void writeAllAttributeGroups();
2743 
2744   void printTypeIdentities();
2745   void printGlobal(const GlobalVariable *GV);
2746   void printAlias(const GlobalAlias *GA);
2747   void printIFunc(const GlobalIFunc *GI);
2748   void printComdat(const Comdat *C);
2749   void printFunction(const Function *F);
2750   void printArgument(const Argument *FA, AttributeSet Attrs);
2751   void printBasicBlock(const BasicBlock *BB);
2752   void printInstructionLine(const Instruction &I);
2753   void printInstruction(const Instruction &I);
2754   void printDbgMarker(const DbgMarker &DPI);
2755   void printDbgVariableRecord(const DbgVariableRecord &DVR);
2756   void printDbgLabelRecord(const DbgLabelRecord &DLR);
2757   void printDbgRecord(const DbgRecord &DR);
2758   void printDbgRecordLine(const DbgRecord &DR);
2759 
2760   void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
2761   void printUseLists(const Function *F);
2762 
2763   void printModuleSummaryIndex();
2764   void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2765   void printSummary(const GlobalValueSummary &Summary);
2766   void printAliasSummary(const AliasSummary *AS);
2767   void printGlobalVarSummary(const GlobalVarSummary *GS);
2768   void printFunctionSummary(const FunctionSummary *FS);
2769   void printTypeIdSummary(const TypeIdSummary &TIS);
2770   void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
2771   void printTypeTestResolution(const TypeTestResolution &TTRes);
2772   void printArgs(const std::vector<uint64_t> &Args);
2773   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2774   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2775   void printVFuncId(const FunctionSummary::VFuncId VFId);
2776   void
2777   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
2778                       const char *Tag);
2779   void
2780   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
2781                    const char *Tag);
2782 
2783 private:
2784   /// Print out metadata attachments.
2785   void printMetadataAttachments(
2786       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2787       StringRef Separator);
2788 
2789   // printInfoComment - Print a little comment after the instruction indicating
2790   // which slot it occupies.
2791   void printInfoComment(const Value &V);
2792 
2793   // printGCRelocateComment - print comment after call to the gc.relocate
2794   // intrinsic indicating base and derived pointer names.
2795   void printGCRelocateComment(const GCRelocateInst &Relocate);
2796 };
2797 
2798 } // end anonymous namespace
2799 
AssemblyWriter(formatted_raw_ostream & o,SlotTracker & Mac,const Module * M,AssemblyAnnotationWriter * AAW,bool IsForDebug,bool ShouldPreserveUseListOrder)2800 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2801                                const Module *M, AssemblyAnnotationWriter *AAW,
2802                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2803     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2804       IsForDebug(IsForDebug),
2805       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2806   if (!TheModule)
2807     return;
2808   for (const GlobalObject &GO : TheModule->global_objects())
2809     if (const Comdat *C = GO.getComdat())
2810       Comdats.insert(C);
2811 }
2812 
AssemblyWriter(formatted_raw_ostream & o,SlotTracker & Mac,const ModuleSummaryIndex * Index,bool IsForDebug)2813 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2814                                const ModuleSummaryIndex *Index, bool IsForDebug)
2815     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2816       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2817 
writeOperand(const Value * Operand,bool PrintType)2818 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2819   if (!Operand) {
2820     Out << "<null operand!>";
2821     return;
2822   }
2823   if (PrintType) {
2824     TypePrinter.print(Operand->getType(), Out);
2825     Out << ' ';
2826   }
2827   auto WriterCtx = getContext();
2828   WriteAsOperandInternal(Out, Operand, WriterCtx);
2829 }
2830 
writeSyncScope(const LLVMContext & Context,SyncScope::ID SSID)2831 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2832                                     SyncScope::ID SSID) {
2833   switch (SSID) {
2834   case SyncScope::System: {
2835     break;
2836   }
2837   default: {
2838     if (SSNs.empty())
2839       Context.getSyncScopeNames(SSNs);
2840 
2841     Out << " syncscope(\"";
2842     printEscapedString(SSNs[SSID], Out);
2843     Out << "\")";
2844     break;
2845   }
2846   }
2847 }
2848 
writeAtomic(const LLVMContext & Context,AtomicOrdering Ordering,SyncScope::ID SSID)2849 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2850                                  AtomicOrdering Ordering,
2851                                  SyncScope::ID SSID) {
2852   if (Ordering == AtomicOrdering::NotAtomic)
2853     return;
2854 
2855   writeSyncScope(Context, SSID);
2856   Out << " " << toIRString(Ordering);
2857 }
2858 
writeAtomicCmpXchg(const LLVMContext & Context,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID)2859 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2860                                         AtomicOrdering SuccessOrdering,
2861                                         AtomicOrdering FailureOrdering,
2862                                         SyncScope::ID SSID) {
2863   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2864          FailureOrdering != AtomicOrdering::NotAtomic);
2865 
2866   writeSyncScope(Context, SSID);
2867   Out << " " << toIRString(SuccessOrdering);
2868   Out << " " << toIRString(FailureOrdering);
2869 }
2870 
writeParamOperand(const Value * Operand,AttributeSet Attrs)2871 void AssemblyWriter::writeParamOperand(const Value *Operand,
2872                                        AttributeSet Attrs) {
2873   if (!Operand) {
2874     Out << "<null operand!>";
2875     return;
2876   }
2877 
2878   // Print the type
2879   TypePrinter.print(Operand->getType(), Out);
2880   // Print parameter attributes list
2881   if (Attrs.hasAttributes()) {
2882     Out << ' ';
2883     writeAttributeSet(Attrs);
2884   }
2885   Out << ' ';
2886   // Print the operand
2887   auto WriterCtx = getContext();
2888   WriteAsOperandInternal(Out, Operand, WriterCtx);
2889 }
2890 
writeOperandBundles(const CallBase * Call)2891 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2892   if (!Call->hasOperandBundles())
2893     return;
2894 
2895   Out << " [ ";
2896 
2897   bool FirstBundle = true;
2898   for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2899     OperandBundleUse BU = Call->getOperandBundleAt(i);
2900 
2901     if (!FirstBundle)
2902       Out << ", ";
2903     FirstBundle = false;
2904 
2905     Out << '"';
2906     printEscapedString(BU.getTagName(), Out);
2907     Out << '"';
2908 
2909     Out << '(';
2910 
2911     bool FirstInput = true;
2912     auto WriterCtx = getContext();
2913     for (const auto &Input : BU.Inputs) {
2914       if (!FirstInput)
2915         Out << ", ";
2916       FirstInput = false;
2917 
2918       if (Input == nullptr)
2919         Out << "<null operand bundle!>";
2920       else {
2921         TypePrinter.print(Input->getType(), Out);
2922         Out << " ";
2923         WriteAsOperandInternal(Out, Input, WriterCtx);
2924       }
2925     }
2926 
2927     Out << ')';
2928   }
2929 
2930   Out << " ]";
2931 }
2932 
printModule(const Module * M)2933 void AssemblyWriter::printModule(const Module *M) {
2934   Machine.initializeIfNeeded();
2935 
2936   if (ShouldPreserveUseListOrder)
2937     UseListOrders = predictUseListOrder(M);
2938 
2939   if (!M->getModuleIdentifier().empty() &&
2940       // Don't print the ID if it will start a new line (which would
2941       // require a comment char before it).
2942       M->getModuleIdentifier().find('\n') == std::string::npos)
2943     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2944 
2945   if (!M->getSourceFileName().empty()) {
2946     Out << "source_filename = \"";
2947     printEscapedString(M->getSourceFileName(), Out);
2948     Out << "\"\n";
2949   }
2950 
2951   const std::string &DL = M->getDataLayoutStr();
2952   if (!DL.empty())
2953     Out << "target datalayout = \"" << DL << "\"\n";
2954   if (!M->getTargetTriple().empty())
2955     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2956 
2957   if (!M->getModuleInlineAsm().empty()) {
2958     Out << '\n';
2959 
2960     // Split the string into lines, to make it easier to read the .ll file.
2961     StringRef Asm = M->getModuleInlineAsm();
2962     do {
2963       StringRef Front;
2964       std::tie(Front, Asm) = Asm.split('\n');
2965 
2966       // We found a newline, print the portion of the asm string from the
2967       // last newline up to this newline.
2968       Out << "module asm \"";
2969       printEscapedString(Front, Out);
2970       Out << "\"\n";
2971     } while (!Asm.empty());
2972   }
2973 
2974   printTypeIdentities();
2975 
2976   // Output all comdats.
2977   if (!Comdats.empty())
2978     Out << '\n';
2979   for (const Comdat *C : Comdats) {
2980     printComdat(C);
2981     if (C != Comdats.back())
2982       Out << '\n';
2983   }
2984 
2985   // Output all globals.
2986   if (!M->global_empty()) Out << '\n';
2987   for (const GlobalVariable &GV : M->globals()) {
2988     printGlobal(&GV); Out << '\n';
2989   }
2990 
2991   // Output all aliases.
2992   if (!M->alias_empty()) Out << "\n";
2993   for (const GlobalAlias &GA : M->aliases())
2994     printAlias(&GA);
2995 
2996   // Output all ifuncs.
2997   if (!M->ifunc_empty()) Out << "\n";
2998   for (const GlobalIFunc &GI : M->ifuncs())
2999     printIFunc(&GI);
3000 
3001   // Output all of the functions.
3002   for (const Function &F : *M) {
3003     Out << '\n';
3004     printFunction(&F);
3005   }
3006 
3007   // Output global use-lists.
3008   printUseLists(nullptr);
3009 
3010   // Output all attribute groups.
3011   if (!Machine.as_empty()) {
3012     Out << '\n';
3013     writeAllAttributeGroups();
3014   }
3015 
3016   // Output named metadata.
3017   if (!M->named_metadata_empty()) Out << '\n';
3018 
3019   for (const NamedMDNode &Node : M->named_metadata())
3020     printNamedMDNode(&Node);
3021 
3022   // Output metadata.
3023   if (!Machine.mdn_empty()) {
3024     Out << '\n';
3025     writeAllMDNodes();
3026   }
3027 }
3028 
printModuleSummaryIndex()3029 void AssemblyWriter::printModuleSummaryIndex() {
3030   assert(TheIndex);
3031   int NumSlots = Machine.initializeIndexIfNeeded();
3032 
3033   Out << "\n";
3034 
3035   // Print module path entries. To print in order, add paths to a vector
3036   // indexed by module slot.
3037   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
3038   std::string RegularLTOModuleName =
3039       ModuleSummaryIndex::getRegularLTOModuleName();
3040   moduleVec.resize(TheIndex->modulePaths().size());
3041   for (auto &[ModPath, ModHash] : TheIndex->modulePaths())
3042     moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(
3043         // An empty module path is a special entry for a regular LTO module
3044         // created during the thin link.
3045         ModPath.empty() ? RegularLTOModuleName : std::string(ModPath), ModHash);
3046 
3047   unsigned i = 0;
3048   for (auto &ModPair : moduleVec) {
3049     Out << "^" << i++ << " = module: (";
3050     Out << "path: \"";
3051     printEscapedString(ModPair.first, Out);
3052     Out << "\", hash: (";
3053     FieldSeparator FS;
3054     for (auto Hash : ModPair.second)
3055       Out << FS << Hash;
3056     Out << "))\n";
3057   }
3058 
3059   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
3060   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
3061   for (auto &GlobalList : *TheIndex) {
3062     auto GUID = GlobalList.first;
3063     for (auto &Summary : GlobalList.second.SummaryList)
3064       SummaryToGUIDMap[Summary.get()] = GUID;
3065   }
3066 
3067   // Print the global value summary entries.
3068   for (auto &GlobalList : *TheIndex) {
3069     auto GUID = GlobalList.first;
3070     auto VI = TheIndex->getValueInfo(GlobalList);
3071     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
3072   }
3073 
3074   // Print the TypeIdMap entries.
3075   for (const auto &TID : TheIndex->typeIds()) {
3076     Out << "^" << Machine.getTypeIdSlot(TID.second.first)
3077         << " = typeid: (name: \"" << TID.second.first << "\"";
3078     printTypeIdSummary(TID.second.second);
3079     Out << ") ; guid = " << TID.first << "\n";
3080   }
3081 
3082   // Print the TypeIdCompatibleVtableMap entries.
3083   for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
3084     auto GUID = GlobalValue::getGUID(TId.first);
3085     Out << "^" << Machine.getTypeIdCompatibleVtableSlot(TId.first)
3086         << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
3087     printTypeIdCompatibleVtableSummary(TId.second);
3088     Out << ") ; guid = " << GUID << "\n";
3089   }
3090 
3091   // Don't emit flags when it's not really needed (value is zero by default).
3092   if (TheIndex->getFlags()) {
3093     Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
3094     ++NumSlots;
3095   }
3096 
3097   Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
3098       << "\n";
3099 }
3100 
3101 static const char *
getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K)3102 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
3103   switch (K) {
3104   case WholeProgramDevirtResolution::Indir:
3105     return "indir";
3106   case WholeProgramDevirtResolution::SingleImpl:
3107     return "singleImpl";
3108   case WholeProgramDevirtResolution::BranchFunnel:
3109     return "branchFunnel";
3110   }
3111   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
3112 }
3113 
getWholeProgDevirtResByArgKindName(WholeProgramDevirtResolution::ByArg::Kind K)3114 static const char *getWholeProgDevirtResByArgKindName(
3115     WholeProgramDevirtResolution::ByArg::Kind K) {
3116   switch (K) {
3117   case WholeProgramDevirtResolution::ByArg::Indir:
3118     return "indir";
3119   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
3120     return "uniformRetVal";
3121   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
3122     return "uniqueRetVal";
3123   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
3124     return "virtualConstProp";
3125   }
3126   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
3127 }
3128 
getTTResKindName(TypeTestResolution::Kind K)3129 static const char *getTTResKindName(TypeTestResolution::Kind K) {
3130   switch (K) {
3131   case TypeTestResolution::Unknown:
3132     return "unknown";
3133   case TypeTestResolution::Unsat:
3134     return "unsat";
3135   case TypeTestResolution::ByteArray:
3136     return "byteArray";
3137   case TypeTestResolution::Inline:
3138     return "inline";
3139   case TypeTestResolution::Single:
3140     return "single";
3141   case TypeTestResolution::AllOnes:
3142     return "allOnes";
3143   }
3144   llvm_unreachable("invalid TypeTestResolution kind");
3145 }
3146 
printTypeTestResolution(const TypeTestResolution & TTRes)3147 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
3148   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
3149       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
3150 
3151   // The following fields are only used if the target does not support the use
3152   // of absolute symbols to store constants. Print only if non-zero.
3153   if (TTRes.AlignLog2)
3154     Out << ", alignLog2: " << TTRes.AlignLog2;
3155   if (TTRes.SizeM1)
3156     Out << ", sizeM1: " << TTRes.SizeM1;
3157   if (TTRes.BitMask)
3158     // BitMask is uint8_t which causes it to print the corresponding char.
3159     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
3160   if (TTRes.InlineBits)
3161     Out << ", inlineBits: " << TTRes.InlineBits;
3162 
3163   Out << ")";
3164 }
3165 
printTypeIdSummary(const TypeIdSummary & TIS)3166 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
3167   Out << ", summary: (";
3168   printTypeTestResolution(TIS.TTRes);
3169   if (!TIS.WPDRes.empty()) {
3170     Out << ", wpdResolutions: (";
3171     FieldSeparator FS;
3172     for (auto &WPDRes : TIS.WPDRes) {
3173       Out << FS;
3174       Out << "(offset: " << WPDRes.first << ", ";
3175       printWPDRes(WPDRes.second);
3176       Out << ")";
3177     }
3178     Out << ")";
3179   }
3180   Out << ")";
3181 }
3182 
printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo & TI)3183 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3184     const TypeIdCompatibleVtableInfo &TI) {
3185   Out << ", summary: (";
3186   FieldSeparator FS;
3187   for (auto &P : TI) {
3188     Out << FS;
3189     Out << "(offset: " << P.AddressPointOffset << ", ";
3190     Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
3191     Out << ")";
3192   }
3193   Out << ")";
3194 }
3195 
printArgs(const std::vector<uint64_t> & Args)3196 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
3197   Out << "args: (";
3198   FieldSeparator FS;
3199   for (auto arg : Args) {
3200     Out << FS;
3201     Out << arg;
3202   }
3203   Out << ")";
3204 }
3205 
printWPDRes(const WholeProgramDevirtResolution & WPDRes)3206 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
3207   Out << "wpdRes: (kind: ";
3208   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
3209 
3210   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
3211     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
3212 
3213   if (!WPDRes.ResByArg.empty()) {
3214     Out << ", resByArg: (";
3215     FieldSeparator FS;
3216     for (auto &ResByArg : WPDRes.ResByArg) {
3217       Out << FS;
3218       printArgs(ResByArg.first);
3219       Out << ", byArg: (kind: ";
3220       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
3221       if (ResByArg.second.TheKind ==
3222               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3223           ResByArg.second.TheKind ==
3224               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3225         Out << ", info: " << ResByArg.second.Info;
3226 
3227       // The following fields are only used if the target does not support the
3228       // use of absolute symbols to store constants. Print only if non-zero.
3229       if (ResByArg.second.Byte || ResByArg.second.Bit)
3230         Out << ", byte: " << ResByArg.second.Byte
3231             << ", bit: " << ResByArg.second.Bit;
3232 
3233       Out << ")";
3234     }
3235     Out << ")";
3236   }
3237   Out << ")";
3238 }
3239 
getSummaryKindName(GlobalValueSummary::SummaryKind SK)3240 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
3241   switch (SK) {
3242   case GlobalValueSummary::AliasKind:
3243     return "alias";
3244   case GlobalValueSummary::FunctionKind:
3245     return "function";
3246   case GlobalValueSummary::GlobalVarKind:
3247     return "variable";
3248   }
3249   llvm_unreachable("invalid summary kind");
3250 }
3251 
printAliasSummary(const AliasSummary * AS)3252 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
3253   Out << ", aliasee: ";
3254   // The indexes emitted for distributed backends may not include the
3255   // aliasee summary (only if it is being imported directly). Handle
3256   // that case by just emitting "null" as the aliasee.
3257   if (AS->hasAliasee())
3258     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
3259   else
3260     Out << "null";
3261 }
3262 
printGlobalVarSummary(const GlobalVarSummary * GS)3263 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
3264   auto VTableFuncs = GS->vTableFuncs();
3265   Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3266       << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3267       << "constant: " << GS->VarFlags.Constant;
3268   if (!VTableFuncs.empty())
3269     Out << ", "
3270         << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3271   Out << ")";
3272 
3273   if (!VTableFuncs.empty()) {
3274     Out << ", vTableFuncs: (";
3275     FieldSeparator FS;
3276     for (auto &P : VTableFuncs) {
3277       Out << FS;
3278       Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
3279           << ", offset: " << P.VTableOffset;
3280       Out << ")";
3281     }
3282     Out << ")";
3283   }
3284 }
3285 
getLinkageName(GlobalValue::LinkageTypes LT)3286 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
3287   switch (LT) {
3288   case GlobalValue::ExternalLinkage:
3289     return "external";
3290   case GlobalValue::PrivateLinkage:
3291     return "private";
3292   case GlobalValue::InternalLinkage:
3293     return "internal";
3294   case GlobalValue::LinkOnceAnyLinkage:
3295     return "linkonce";
3296   case GlobalValue::LinkOnceODRLinkage:
3297     return "linkonce_odr";
3298   case GlobalValue::WeakAnyLinkage:
3299     return "weak";
3300   case GlobalValue::WeakODRLinkage:
3301     return "weak_odr";
3302   case GlobalValue::CommonLinkage:
3303     return "common";
3304   case GlobalValue::AppendingLinkage:
3305     return "appending";
3306   case GlobalValue::ExternalWeakLinkage:
3307     return "extern_weak";
3308   case GlobalValue::AvailableExternallyLinkage:
3309     return "available_externally";
3310   }
3311   llvm_unreachable("invalid linkage");
3312 }
3313 
3314 // When printing the linkage types in IR where the ExternalLinkage is
3315 // not printed, and other linkage types are expected to be printed with
3316 // a space after the name.
getLinkageNameWithSpace(GlobalValue::LinkageTypes LT)3317 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
3318   if (LT == GlobalValue::ExternalLinkage)
3319     return "";
3320   return getLinkageName(LT) + " ";
3321 }
3322 
getVisibilityName(GlobalValue::VisibilityTypes Vis)3323 static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {
3324   switch (Vis) {
3325   case GlobalValue::DefaultVisibility:
3326     return "default";
3327   case GlobalValue::HiddenVisibility:
3328     return "hidden";
3329   case GlobalValue::ProtectedVisibility:
3330     return "protected";
3331   }
3332   llvm_unreachable("invalid visibility");
3333 }
3334 
getImportTypeName(GlobalValueSummary::ImportKind IK)3335 static const char *getImportTypeName(GlobalValueSummary::ImportKind IK) {
3336   switch (IK) {
3337   case GlobalValueSummary::Definition:
3338     return "definition";
3339   case GlobalValueSummary::Declaration:
3340     return "declaration";
3341   }
3342   llvm_unreachable("invalid import kind");
3343 }
3344 
printFunctionSummary(const FunctionSummary * FS)3345 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
3346   Out << ", insts: " << FS->instCount();
3347   if (FS->fflags().anyFlagSet())
3348     Out << ", " << FS->fflags();
3349 
3350   if (!FS->calls().empty()) {
3351     Out << ", calls: (";
3352     FieldSeparator IFS;
3353     for (auto &Call : FS->calls()) {
3354       Out << IFS;
3355       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
3356       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
3357         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
3358       else if (Call.second.RelBlockFreq)
3359         Out << ", relbf: " << Call.second.RelBlockFreq;
3360       // Follow the convention of emitting flags as a boolean value, but only
3361       // emit if true to avoid unnecessary verbosity and test churn.
3362       if (Call.second.HasTailCall)
3363         Out << ", tail: 1";
3364       Out << ")";
3365     }
3366     Out << ")";
3367   }
3368 
3369   if (const auto *TIdInfo = FS->getTypeIdInfo())
3370     printTypeIdInfo(*TIdInfo);
3371 
3372   // The AllocationType identifiers capture the profiled context behavior
3373   // reaching a specific static allocation site (possibly cloned).
3374   auto AllocTypeName = [](uint8_t Type) -> const char * {
3375     switch (Type) {
3376     case (uint8_t)AllocationType::None:
3377       return "none";
3378     case (uint8_t)AllocationType::NotCold:
3379       return "notcold";
3380     case (uint8_t)AllocationType::Cold:
3381       return "cold";
3382     case (uint8_t)AllocationType::Hot:
3383       return "hot";
3384     }
3385     llvm_unreachable("Unexpected alloc type");
3386   };
3387 
3388   if (!FS->allocs().empty()) {
3389     Out << ", allocs: (";
3390     FieldSeparator AFS;
3391     for (auto &AI : FS->allocs()) {
3392       Out << AFS;
3393       Out << "(versions: (";
3394       FieldSeparator VFS;
3395       for (auto V : AI.Versions) {
3396         Out << VFS;
3397         Out << AllocTypeName(V);
3398       }
3399       Out << "), memProf: (";
3400       FieldSeparator MIBFS;
3401       for (auto &MIB : AI.MIBs) {
3402         Out << MIBFS;
3403         Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3404         Out << ", stackIds: (";
3405         FieldSeparator SIDFS;
3406         for (auto Id : MIB.StackIdIndices) {
3407           Out << SIDFS;
3408           Out << TheIndex->getStackIdAtIndex(Id);
3409         }
3410         Out << "))";
3411       }
3412       Out << "))";
3413     }
3414     Out << ")";
3415   }
3416 
3417   if (!FS->callsites().empty()) {
3418     Out << ", callsites: (";
3419     FieldSeparator SNFS;
3420     for (auto &CI : FS->callsites()) {
3421       Out << SNFS;
3422       if (CI.Callee)
3423         Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
3424       else
3425         Out << "(callee: null";
3426       Out << ", clones: (";
3427       FieldSeparator VFS;
3428       for (auto V : CI.Clones) {
3429         Out << VFS;
3430         Out << V;
3431       }
3432       Out << "), stackIds: (";
3433       FieldSeparator SIDFS;
3434       for (auto Id : CI.StackIdIndices) {
3435         Out << SIDFS;
3436         Out << TheIndex->getStackIdAtIndex(Id);
3437       }
3438       Out << "))";
3439     }
3440     Out << ")";
3441   }
3442 
3443   auto PrintRange = [&](const ConstantRange &Range) {
3444     Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3445   };
3446 
3447   if (!FS->paramAccesses().empty()) {
3448     Out << ", params: (";
3449     FieldSeparator IFS;
3450     for (auto &PS : FS->paramAccesses()) {
3451       Out << IFS;
3452       Out << "(param: " << PS.ParamNo;
3453       Out << ", offset: ";
3454       PrintRange(PS.Use);
3455       if (!PS.Calls.empty()) {
3456         Out << ", calls: (";
3457         FieldSeparator IFS;
3458         for (auto &Call : PS.Calls) {
3459           Out << IFS;
3460           Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
3461           Out << ", param: " << Call.ParamNo;
3462           Out << ", offset: ";
3463           PrintRange(Call.Offsets);
3464           Out << ")";
3465         }
3466         Out << ")";
3467       }
3468       Out << ")";
3469     }
3470     Out << ")";
3471   }
3472 }
3473 
printTypeIdInfo(const FunctionSummary::TypeIdInfo & TIDInfo)3474 void AssemblyWriter::printTypeIdInfo(
3475     const FunctionSummary::TypeIdInfo &TIDInfo) {
3476   Out << ", typeIdInfo: (";
3477   FieldSeparator TIDFS;
3478   if (!TIDInfo.TypeTests.empty()) {
3479     Out << TIDFS;
3480     Out << "typeTests: (";
3481     FieldSeparator FS;
3482     for (auto &GUID : TIDInfo.TypeTests) {
3483       auto TidIter = TheIndex->typeIds().equal_range(GUID);
3484       if (TidIter.first == TidIter.second) {
3485         Out << FS;
3486         Out << GUID;
3487         continue;
3488       }
3489       // Print all type id that correspond to this GUID.
3490       for (auto It = TidIter.first; It != TidIter.second; ++It) {
3491         Out << FS;
3492         auto Slot = Machine.getTypeIdSlot(It->second.first);
3493         assert(Slot != -1);
3494         Out << "^" << Slot;
3495       }
3496     }
3497     Out << ")";
3498   }
3499   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3500     Out << TIDFS;
3501     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3502   }
3503   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3504     Out << TIDFS;
3505     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3506   }
3507   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3508     Out << TIDFS;
3509     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3510                      "typeTestAssumeConstVCalls");
3511   }
3512   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3513     Out << TIDFS;
3514     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3515                      "typeCheckedLoadConstVCalls");
3516   }
3517   Out << ")";
3518 }
3519 
printVFuncId(const FunctionSummary::VFuncId VFId)3520 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3521   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3522   if (TidIter.first == TidIter.second) {
3523     Out << "vFuncId: (";
3524     Out << "guid: " << VFId.GUID;
3525     Out << ", offset: " << VFId.Offset;
3526     Out << ")";
3527     return;
3528   }
3529   // Print all type id that correspond to this GUID.
3530   FieldSeparator FS;
3531   for (auto It = TidIter.first; It != TidIter.second; ++It) {
3532     Out << FS;
3533     Out << "vFuncId: (";
3534     auto Slot = Machine.getTypeIdSlot(It->second.first);
3535     assert(Slot != -1);
3536     Out << "^" << Slot;
3537     Out << ", offset: " << VFId.Offset;
3538     Out << ")";
3539   }
3540 }
3541 
printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> & VCallList,const char * Tag)3542 void AssemblyWriter::printNonConstVCalls(
3543     const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
3544   Out << Tag << ": (";
3545   FieldSeparator FS;
3546   for (auto &VFuncId : VCallList) {
3547     Out << FS;
3548     printVFuncId(VFuncId);
3549   }
3550   Out << ")";
3551 }
3552 
printConstVCalls(const std::vector<FunctionSummary::ConstVCall> & VCallList,const char * Tag)3553 void AssemblyWriter::printConstVCalls(
3554     const std::vector<FunctionSummary::ConstVCall> &VCallList,
3555     const char *Tag) {
3556   Out << Tag << ": (";
3557   FieldSeparator FS;
3558   for (auto &ConstVCall : VCallList) {
3559     Out << FS;
3560     Out << "(";
3561     printVFuncId(ConstVCall.VFunc);
3562     if (!ConstVCall.Args.empty()) {
3563       Out << ", ";
3564       printArgs(ConstVCall.Args);
3565     }
3566     Out << ")";
3567   }
3568   Out << ")";
3569 }
3570 
printSummary(const GlobalValueSummary & Summary)3571 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3572   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3573   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3574   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3575   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3576       << ", flags: (";
3577   Out << "linkage: " << getLinkageName(LT);
3578   Out << ", visibility: "
3579       << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility);
3580   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3581   Out << ", live: " << GVFlags.Live;
3582   Out << ", dsoLocal: " << GVFlags.DSOLocal;
3583   Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3584   Out << ", importType: "
3585       << getImportTypeName(GlobalValueSummary::ImportKind(GVFlags.ImportType));
3586   Out << ")";
3587 
3588   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3589     printAliasSummary(cast<AliasSummary>(&Summary));
3590   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3591     printFunctionSummary(cast<FunctionSummary>(&Summary));
3592   else
3593     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3594 
3595   auto RefList = Summary.refs();
3596   if (!RefList.empty()) {
3597     Out << ", refs: (";
3598     FieldSeparator FS;
3599     for (auto &Ref : RefList) {
3600       Out << FS;
3601       if (Ref.isReadOnly())
3602         Out << "readonly ";
3603       else if (Ref.isWriteOnly())
3604         Out << "writeonly ";
3605       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3606     }
3607     Out << ")";
3608   }
3609 
3610   Out << ")";
3611 }
3612 
printSummaryInfo(unsigned Slot,const ValueInfo & VI)3613 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3614   Out << "^" << Slot << " = gv: (";
3615   if (!VI.name().empty())
3616     Out << "name: \"" << VI.name() << "\"";
3617   else
3618     Out << "guid: " << VI.getGUID();
3619   if (!VI.getSummaryList().empty()) {
3620     Out << ", summaries: (";
3621     FieldSeparator FS;
3622     for (auto &Summary : VI.getSummaryList()) {
3623       Out << FS;
3624       printSummary(*Summary);
3625     }
3626     Out << ")";
3627   }
3628   Out << ")";
3629   if (!VI.name().empty())
3630     Out << " ; guid = " << VI.getGUID();
3631   Out << "\n";
3632 }
3633 
printMetadataIdentifier(StringRef Name,formatted_raw_ostream & Out)3634 static void printMetadataIdentifier(StringRef Name,
3635                                     formatted_raw_ostream &Out) {
3636   if (Name.empty()) {
3637     Out << "<empty name> ";
3638   } else {
3639     unsigned char FirstC = static_cast<unsigned char>(Name[0]);
3640     if (isalpha(FirstC) || FirstC == '-' || FirstC == '$' || FirstC == '.' ||
3641         FirstC == '_')
3642       Out << FirstC;
3643     else
3644       Out << '\\' << hexdigit(FirstC >> 4) << hexdigit(FirstC & 0x0F);
3645     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3646       unsigned char C = Name[i];
3647       if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
3648         Out << C;
3649       else
3650         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3651     }
3652   }
3653 }
3654 
printNamedMDNode(const NamedMDNode * NMD)3655 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3656   Out << '!';
3657   printMetadataIdentifier(NMD->getName(), Out);
3658   Out << " = !{";
3659   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3660     if (i)
3661       Out << ", ";
3662 
3663     // Write DIExpressions inline.
3664     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3665     MDNode *Op = NMD->getOperand(i);
3666     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3667       writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
3668       continue;
3669     }
3670 
3671     int Slot = Machine.getMetadataSlot(Op);
3672     if (Slot == -1)
3673       Out << "<badref>";
3674     else
3675       Out << '!' << Slot;
3676   }
3677   Out << "}\n";
3678 }
3679 
PrintVisibility(GlobalValue::VisibilityTypes Vis,formatted_raw_ostream & Out)3680 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3681                             formatted_raw_ostream &Out) {
3682   switch (Vis) {
3683   case GlobalValue::DefaultVisibility: break;
3684   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
3685   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3686   }
3687 }
3688 
PrintDSOLocation(const GlobalValue & GV,formatted_raw_ostream & Out)3689 static void PrintDSOLocation(const GlobalValue &GV,
3690                              formatted_raw_ostream &Out) {
3691   if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
3692     Out << "dso_local ";
3693 }
3694 
PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,formatted_raw_ostream & Out)3695 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3696                                  formatted_raw_ostream &Out) {
3697   switch (SCT) {
3698   case GlobalValue::DefaultStorageClass: break;
3699   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3700   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3701   }
3702 }
3703 
PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,formatted_raw_ostream & Out)3704 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3705                                   formatted_raw_ostream &Out) {
3706   switch (TLM) {
3707     case GlobalVariable::NotThreadLocal:
3708       break;
3709     case GlobalVariable::GeneralDynamicTLSModel:
3710       Out << "thread_local ";
3711       break;
3712     case GlobalVariable::LocalDynamicTLSModel:
3713       Out << "thread_local(localdynamic) ";
3714       break;
3715     case GlobalVariable::InitialExecTLSModel:
3716       Out << "thread_local(initialexec) ";
3717       break;
3718     case GlobalVariable::LocalExecTLSModel:
3719       Out << "thread_local(localexec) ";
3720       break;
3721   }
3722 }
3723 
getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA)3724 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3725   switch (UA) {
3726   case GlobalVariable::UnnamedAddr::None:
3727     return "";
3728   case GlobalVariable::UnnamedAddr::Local:
3729     return "local_unnamed_addr";
3730   case GlobalVariable::UnnamedAddr::Global:
3731     return "unnamed_addr";
3732   }
3733   llvm_unreachable("Unknown UnnamedAddr");
3734 }
3735 
maybePrintComdat(formatted_raw_ostream & Out,const GlobalObject & GO)3736 static void maybePrintComdat(formatted_raw_ostream &Out,
3737                              const GlobalObject &GO) {
3738   const Comdat *C = GO.getComdat();
3739   if (!C)
3740     return;
3741 
3742   if (isa<GlobalVariable>(GO))
3743     Out << ',';
3744   Out << " comdat";
3745 
3746   if (GO.getName() == C->getName())
3747     return;
3748 
3749   Out << '(';
3750   PrintLLVMName(Out, C->getName(), ComdatPrefix);
3751   Out << ')';
3752 }
3753 
printGlobal(const GlobalVariable * GV)3754 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3755   if (GV->isMaterializable())
3756     Out << "; Materializable\n";
3757 
3758   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
3759   WriteAsOperandInternal(Out, GV, WriterCtx);
3760   Out << " = ";
3761 
3762   if (!GV->hasInitializer() && GV->hasExternalLinkage())
3763     Out << "external ";
3764 
3765   Out << getLinkageNameWithSpace(GV->getLinkage());
3766   PrintDSOLocation(*GV, Out);
3767   PrintVisibility(GV->getVisibility(), Out);
3768   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3769   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3770   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3771   if (!UA.empty())
3772       Out << UA << ' ';
3773 
3774   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3775     Out << "addrspace(" << AddressSpace << ") ";
3776   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3777   Out << (GV->isConstant() ? "constant " : "global ");
3778   TypePrinter.print(GV->getValueType(), Out);
3779 
3780   if (GV->hasInitializer()) {
3781     Out << ' ';
3782     writeOperand(GV->getInitializer(), false);
3783   }
3784 
3785   if (GV->hasSection()) {
3786     Out << ", section \"";
3787     printEscapedString(GV->getSection(), Out);
3788     Out << '"';
3789   }
3790   if (GV->hasPartition()) {
3791     Out << ", partition \"";
3792     printEscapedString(GV->getPartition(), Out);
3793     Out << '"';
3794   }
3795   if (auto CM = GV->getCodeModel()) {
3796     Out << ", code_model \"";
3797     switch (*CM) {
3798     case CodeModel::Tiny:
3799       Out << "tiny";
3800       break;
3801     case CodeModel::Small:
3802       Out << "small";
3803       break;
3804     case CodeModel::Kernel:
3805       Out << "kernel";
3806       break;
3807     case CodeModel::Medium:
3808       Out << "medium";
3809       break;
3810     case CodeModel::Large:
3811       Out << "large";
3812       break;
3813     }
3814     Out << '"';
3815   }
3816 
3817   using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;
3818   if (GV->hasSanitizerMetadata()) {
3819     SanitizerMetadata MD = GV->getSanitizerMetadata();
3820     if (MD.NoAddress)
3821       Out << ", no_sanitize_address";
3822     if (MD.NoHWAddress)
3823       Out << ", no_sanitize_hwaddress";
3824     if (MD.Memtag)
3825       Out << ", sanitize_memtag";
3826     if (MD.IsDynInit)
3827       Out << ", sanitize_address_dyninit";
3828   }
3829 
3830   maybePrintComdat(Out, *GV);
3831   if (MaybeAlign A = GV->getAlign())
3832     Out << ", align " << A->value();
3833 
3834   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3835   GV->getAllMetadata(MDs);
3836   printMetadataAttachments(MDs, ", ");
3837 
3838   auto Attrs = GV->getAttributes();
3839   if (Attrs.hasAttributes())
3840     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3841 
3842   printInfoComment(*GV);
3843 }
3844 
printAlias(const GlobalAlias * GA)3845 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
3846   if (GA->isMaterializable())
3847     Out << "; Materializable\n";
3848 
3849   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
3850   WriteAsOperandInternal(Out, GA, WriterCtx);
3851   Out << " = ";
3852 
3853   Out << getLinkageNameWithSpace(GA->getLinkage());
3854   PrintDSOLocation(*GA, Out);
3855   PrintVisibility(GA->getVisibility(), Out);
3856   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
3857   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
3858   StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr());
3859   if (!UA.empty())
3860       Out << UA << ' ';
3861 
3862   Out << "alias ";
3863 
3864   TypePrinter.print(GA->getValueType(), Out);
3865   Out << ", ";
3866 
3867   if (const Constant *Aliasee = GA->getAliasee()) {
3868     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
3869   } else {
3870     TypePrinter.print(GA->getType(), Out);
3871     Out << " <<NULL ALIASEE>>";
3872   }
3873 
3874   if (GA->hasPartition()) {
3875     Out << ", partition \"";
3876     printEscapedString(GA->getPartition(), Out);
3877     Out << '"';
3878   }
3879 
3880   printInfoComment(*GA);
3881   Out << '\n';
3882 }
3883 
printIFunc(const GlobalIFunc * GI)3884 void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
3885   if (GI->isMaterializable())
3886     Out << "; Materializable\n";
3887 
3888   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
3889   WriteAsOperandInternal(Out, GI, WriterCtx);
3890   Out << " = ";
3891 
3892   Out << getLinkageNameWithSpace(GI->getLinkage());
3893   PrintDSOLocation(*GI, Out);
3894   PrintVisibility(GI->getVisibility(), Out);
3895 
3896   Out << "ifunc ";
3897 
3898   TypePrinter.print(GI->getValueType(), Out);
3899   Out << ", ";
3900 
3901   if (const Constant *Resolver = GI->getResolver()) {
3902     writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
3903   } else {
3904     TypePrinter.print(GI->getType(), Out);
3905     Out << " <<NULL RESOLVER>>";
3906   }
3907 
3908   if (GI->hasPartition()) {
3909     Out << ", partition \"";
3910     printEscapedString(GI->getPartition(), Out);
3911     Out << '"';
3912   }
3913 
3914   printInfoComment(*GI);
3915   Out << '\n';
3916 }
3917 
printComdat(const Comdat * C)3918 void AssemblyWriter::printComdat(const Comdat *C) {
3919   C->print(Out);
3920 }
3921 
printTypeIdentities()3922 void AssemblyWriter::printTypeIdentities() {
3923   if (TypePrinter.empty())
3924     return;
3925 
3926   Out << '\n';
3927 
3928   // Emit all numbered types.
3929   auto &NumberedTypes = TypePrinter.getNumberedTypes();
3930   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3931     Out << '%' << I << " = type ";
3932 
3933     // Make sure we print out at least one level of the type structure, so
3934     // that we do not get %2 = type %2
3935     TypePrinter.printStructBody(NumberedTypes[I], Out);
3936     Out << '\n';
3937   }
3938 
3939   auto &NamedTypes = TypePrinter.getNamedTypes();
3940   for (StructType *NamedType : NamedTypes) {
3941     PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
3942     Out << " = type ";
3943 
3944     // Make sure we print out at least one level of the type structure, so
3945     // that we do not get %FILE = type %FILE
3946     TypePrinter.printStructBody(NamedType, Out);
3947     Out << '\n';
3948   }
3949 }
3950 
3951 /// printFunction - Print all aspects of a function.
printFunction(const Function * F)3952 void AssemblyWriter::printFunction(const Function *F) {
3953   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3954 
3955   if (F->isMaterializable())
3956     Out << "; Materializable\n";
3957 
3958   const AttributeList &Attrs = F->getAttributes();
3959   if (Attrs.hasFnAttrs()) {
3960     AttributeSet AS = Attrs.getFnAttrs();
3961     std::string AttrStr;
3962 
3963     for (const Attribute &Attr : AS) {
3964       if (!Attr.isStringAttribute()) {
3965         if (!AttrStr.empty()) AttrStr += ' ';
3966         AttrStr += Attr.getAsString();
3967       }
3968     }
3969 
3970     if (!AttrStr.empty())
3971       Out << "; Function Attrs: " << AttrStr << '\n';
3972   }
3973 
3974   Machine.incorporateFunction(F);
3975 
3976   if (F->isDeclaration()) {
3977     Out << "declare";
3978     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3979     F->getAllMetadata(MDs);
3980     printMetadataAttachments(MDs, " ");
3981     Out << ' ';
3982   } else
3983     Out << "define ";
3984 
3985   Out << getLinkageNameWithSpace(F->getLinkage());
3986   PrintDSOLocation(*F, Out);
3987   PrintVisibility(F->getVisibility(), Out);
3988   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3989 
3990   // Print the calling convention.
3991   if (F->getCallingConv() != CallingConv::C) {
3992     PrintCallingConv(F->getCallingConv(), Out);
3993     Out << " ";
3994   }
3995 
3996   FunctionType *FT = F->getFunctionType();
3997   if (Attrs.hasRetAttrs())
3998     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3999   TypePrinter.print(F->getReturnType(), Out);
4000   AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
4001   Out << ' ';
4002   WriteAsOperandInternal(Out, F, WriterCtx);
4003   Out << '(';
4004 
4005   // Loop over the arguments, printing them...
4006   if (F->isDeclaration() && !IsForDebug) {
4007     // We're only interested in the type here - don't print argument names.
4008     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
4009       // Insert commas as we go... the first arg doesn't get a comma
4010       if (I)
4011         Out << ", ";
4012       // Output type...
4013       TypePrinter.print(FT->getParamType(I), Out);
4014 
4015       AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
4016       if (ArgAttrs.hasAttributes()) {
4017         Out << ' ';
4018         writeAttributeSet(ArgAttrs);
4019       }
4020     }
4021   } else {
4022     // The arguments are meaningful here, print them in detail.
4023     for (const Argument &Arg : F->args()) {
4024       // Insert commas as we go... the first arg doesn't get a comma
4025       if (Arg.getArgNo() != 0)
4026         Out << ", ";
4027       printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
4028     }
4029   }
4030 
4031   // Finish printing arguments...
4032   if (FT->isVarArg()) {
4033     if (FT->getNumParams()) Out << ", ";
4034     Out << "...";  // Output varargs portion of signature!
4035   }
4036   Out << ')';
4037   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
4038   if (!UA.empty())
4039     Out << ' ' << UA;
4040   // We print the function address space if it is non-zero or if we are writing
4041   // a module with a non-zero program address space or if there is no valid
4042   // Module* so that the file can be parsed without the datalayout string.
4043   const Module *Mod = F->getParent();
4044   if (F->getAddressSpace() != 0 || !Mod ||
4045       Mod->getDataLayout().getProgramAddressSpace() != 0)
4046     Out << " addrspace(" << F->getAddressSpace() << ")";
4047   if (Attrs.hasFnAttrs())
4048     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
4049   if (F->hasSection()) {
4050     Out << " section \"";
4051     printEscapedString(F->getSection(), Out);
4052     Out << '"';
4053   }
4054   if (F->hasPartition()) {
4055     Out << " partition \"";
4056     printEscapedString(F->getPartition(), Out);
4057     Out << '"';
4058   }
4059   maybePrintComdat(Out, *F);
4060   if (MaybeAlign A = F->getAlign())
4061     Out << " align " << A->value();
4062   if (F->hasGC())
4063     Out << " gc \"" << F->getGC() << '"';
4064   if (F->hasPrefixData()) {
4065     Out << " prefix ";
4066     writeOperand(F->getPrefixData(), true);
4067   }
4068   if (F->hasPrologueData()) {
4069     Out << " prologue ";
4070     writeOperand(F->getPrologueData(), true);
4071   }
4072   if (F->hasPersonalityFn()) {
4073     Out << " personality ";
4074     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
4075   }
4076 
4077   if (F->isDeclaration()) {
4078     Out << '\n';
4079   } else {
4080     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4081     F->getAllMetadata(MDs);
4082     printMetadataAttachments(MDs, " ");
4083 
4084     Out << " {";
4085     // Output all of the function's basic blocks.
4086     for (const BasicBlock &BB : *F)
4087       printBasicBlock(&BB);
4088 
4089     // Output the function's use-lists.
4090     printUseLists(F);
4091 
4092     Out << "}\n";
4093   }
4094 
4095   Machine.purgeFunction();
4096 }
4097 
4098 /// printArgument - This member is called for every argument that is passed into
4099 /// the function.  Simply print it out
printArgument(const Argument * Arg,AttributeSet Attrs)4100 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
4101   // Output type...
4102   TypePrinter.print(Arg->getType(), Out);
4103 
4104   // Output parameter attributes list
4105   if (Attrs.hasAttributes()) {
4106     Out << ' ';
4107     writeAttributeSet(Attrs);
4108   }
4109 
4110   // Output name, if available...
4111   if (Arg->hasName()) {
4112     Out << ' ';
4113     PrintLLVMName(Out, Arg);
4114   } else {
4115     int Slot = Machine.getLocalSlot(Arg);
4116     assert(Slot != -1 && "expect argument in function here");
4117     Out << " %" << Slot;
4118   }
4119 }
4120 
4121 /// printBasicBlock - This member is called for each basic block in a method.
printBasicBlock(const BasicBlock * BB)4122 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
4123   bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
4124   if (BB->hasName()) {              // Print out the label if it exists...
4125     Out << "\n";
4126     PrintLLVMName(Out, BB->getName(), LabelPrefix);
4127     Out << ':';
4128   } else if (!IsEntryBlock) {
4129     Out << "\n";
4130     int Slot = Machine.getLocalSlot(BB);
4131     if (Slot != -1)
4132       Out << Slot << ":";
4133     else
4134       Out << "<badref>:";
4135   }
4136 
4137   if (!IsEntryBlock) {
4138     // Output predecessors for the block.
4139     Out.PadToColumn(50);
4140     Out << ";";
4141     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
4142 
4143     if (PI == PE) {
4144       Out << " No predecessors!";
4145     } else {
4146       Out << " preds = ";
4147       writeOperand(*PI, false);
4148       for (++PI; PI != PE; ++PI) {
4149         Out << ", ";
4150         writeOperand(*PI, false);
4151       }
4152     }
4153   }
4154 
4155   Out << "\n";
4156 
4157   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
4158 
4159   // Output all of the instructions in the basic block...
4160   for (const Instruction &I : *BB) {
4161     for (const DbgRecord &DR : I.getDbgRecordRange())
4162       printDbgRecordLine(DR);
4163     printInstructionLine(I);
4164   }
4165 
4166   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
4167 }
4168 
4169 /// printInstructionLine - Print an instruction and a newline character.
printInstructionLine(const Instruction & I)4170 void AssemblyWriter::printInstructionLine(const Instruction &I) {
4171   printInstruction(I);
4172   Out << '\n';
4173 }
4174 
4175 /// printGCRelocateComment - print comment after call to the gc.relocate
4176 /// intrinsic indicating base and derived pointer names.
printGCRelocateComment(const GCRelocateInst & Relocate)4177 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
4178   Out << " ; (";
4179   writeOperand(Relocate.getBasePtr(), false);
4180   Out << ", ";
4181   writeOperand(Relocate.getDerivedPtr(), false);
4182   Out << ")";
4183 }
4184 
4185 /// printInfoComment - Print a little comment after the instruction indicating
4186 /// which slot it occupies.
printInfoComment(const Value & V)4187 void AssemblyWriter::printInfoComment(const Value &V) {
4188   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
4189     printGCRelocateComment(*Relocate);
4190 
4191   if (AnnotationWriter) {
4192     AnnotationWriter->printInfoComment(V, Out);
4193   }
4194 }
4195 
maybePrintCallAddrSpace(const Value * Operand,const Instruction * I,raw_ostream & Out)4196 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
4197                                     raw_ostream &Out) {
4198   // We print the address space of the call if it is non-zero.
4199   if (Operand == nullptr) {
4200     Out << " <cannot get addrspace!>";
4201     return;
4202   }
4203   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
4204   bool PrintAddrSpace = CallAddrSpace != 0;
4205   if (!PrintAddrSpace) {
4206     const Module *Mod = getModuleFromVal(I);
4207     // We also print it if it is zero but not equal to the program address space
4208     // or if we can't find a valid Module* to make it possible to parse
4209     // the resulting file even without a datalayout string.
4210     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
4211       PrintAddrSpace = true;
4212   }
4213   if (PrintAddrSpace)
4214     Out << " addrspace(" << CallAddrSpace << ")";
4215 }
4216 
4217 // This member is called for each Instruction in a function..
printInstruction(const Instruction & I)4218 void AssemblyWriter::printInstruction(const Instruction &I) {
4219   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
4220 
4221   // Print out indentation for an instruction.
4222   Out << "  ";
4223 
4224   // Print out name if it exists...
4225   if (I.hasName()) {
4226     PrintLLVMName(Out, &I);
4227     Out << " = ";
4228   } else if (!I.getType()->isVoidTy()) {
4229     // Print out the def slot taken.
4230     int SlotNum = Machine.getLocalSlot(&I);
4231     if (SlotNum == -1)
4232       Out << "<badref> = ";
4233     else
4234       Out << '%' << SlotNum << " = ";
4235   }
4236 
4237   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4238     if (CI->isMustTailCall())
4239       Out << "musttail ";
4240     else if (CI->isTailCall())
4241       Out << "tail ";
4242     else if (CI->isNoTailCall())
4243       Out << "notail ";
4244   }
4245 
4246   // Print out the opcode...
4247   Out << I.getOpcodeName();
4248 
4249   // If this is an atomic load or store, print out the atomic marker.
4250   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
4251       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
4252     Out << " atomic";
4253 
4254   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
4255     Out << " weak";
4256 
4257   // If this is a volatile operation, print out the volatile marker.
4258   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
4259       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
4260       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
4261       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
4262     Out << " volatile";
4263 
4264   // Print out optimization information.
4265   WriteOptimizationInfo(Out, &I);
4266 
4267   // Print out the compare instruction predicates
4268   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
4269     Out << ' ' << CI->getPredicate();
4270 
4271   // Print out the atomicrmw operation
4272   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
4273     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
4274 
4275   // Print out the type of the operands...
4276   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
4277 
4278   // Special case conditional branches to swizzle the condition out to the front
4279   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
4280     const BranchInst &BI(cast<BranchInst>(I));
4281     Out << ' ';
4282     writeOperand(BI.getCondition(), true);
4283     Out << ", ";
4284     writeOperand(BI.getSuccessor(0), true);
4285     Out << ", ";
4286     writeOperand(BI.getSuccessor(1), true);
4287 
4288   } else if (isa<SwitchInst>(I)) {
4289     const SwitchInst& SI(cast<SwitchInst>(I));
4290     // Special case switch instruction to get formatting nice and correct.
4291     Out << ' ';
4292     writeOperand(SI.getCondition(), true);
4293     Out << ", ";
4294     writeOperand(SI.getDefaultDest(), true);
4295     Out << " [";
4296     for (auto Case : SI.cases()) {
4297       Out << "\n    ";
4298       writeOperand(Case.getCaseValue(), true);
4299       Out << ", ";
4300       writeOperand(Case.getCaseSuccessor(), true);
4301     }
4302     Out << "\n  ]";
4303   } else if (isa<IndirectBrInst>(I)) {
4304     // Special case indirectbr instruction to get formatting nice and correct.
4305     Out << ' ';
4306     writeOperand(Operand, true);
4307     Out << ", [";
4308 
4309     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
4310       if (i != 1)
4311         Out << ", ";
4312       writeOperand(I.getOperand(i), true);
4313     }
4314     Out << ']';
4315   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
4316     Out << ' ';
4317     TypePrinter.print(I.getType(), Out);
4318     Out << ' ';
4319 
4320     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
4321       if (op) Out << ", ";
4322       Out << "[ ";
4323       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
4324       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
4325     }
4326   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
4327     Out << ' ';
4328     writeOperand(I.getOperand(0), true);
4329     for (unsigned i : EVI->indices())
4330       Out << ", " << i;
4331   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
4332     Out << ' ';
4333     writeOperand(I.getOperand(0), true); Out << ", ";
4334     writeOperand(I.getOperand(1), true);
4335     for (unsigned i : IVI->indices())
4336       Out << ", " << i;
4337   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
4338     Out << ' ';
4339     TypePrinter.print(I.getType(), Out);
4340     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4341       Out << '\n';
4342 
4343     if (LPI->isCleanup())
4344       Out << "          cleanup";
4345 
4346     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
4347       if (i != 0 || LPI->isCleanup()) Out << "\n";
4348       if (LPI->isCatch(i))
4349         Out << "          catch ";
4350       else
4351         Out << "          filter ";
4352 
4353       writeOperand(LPI->getClause(i), true);
4354     }
4355   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
4356     Out << " within ";
4357     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
4358     Out << " [";
4359     unsigned Op = 0;
4360     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
4361       if (Op > 0)
4362         Out << ", ";
4363       writeOperand(PadBB, /*PrintType=*/true);
4364       ++Op;
4365     }
4366     Out << "] unwind ";
4367     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4368       writeOperand(UnwindDest, /*PrintType=*/true);
4369     else
4370       Out << "to caller";
4371   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
4372     Out << " within ";
4373     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
4374     Out << " [";
4375     for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
4376       if (Op > 0)
4377         Out << ", ";
4378       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
4379     }
4380     Out << ']';
4381   } else if (isa<ReturnInst>(I) && !Operand) {
4382     Out << " void";
4383   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
4384     Out << " from ";
4385     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4386 
4387     Out << " to ";
4388     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4389   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
4390     Out << " from ";
4391     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4392 
4393     Out << " unwind ";
4394     if (CRI->hasUnwindDest())
4395       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4396     else
4397       Out << "to caller";
4398   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4399     // Print the calling convention being used.
4400     if (CI->getCallingConv() != CallingConv::C) {
4401       Out << " ";
4402       PrintCallingConv(CI->getCallingConv(), Out);
4403     }
4404 
4405     Operand = CI->getCalledOperand();
4406     FunctionType *FTy = CI->getFunctionType();
4407     Type *RetTy = FTy->getReturnType();
4408     const AttributeList &PAL = CI->getAttributes();
4409 
4410     if (PAL.hasRetAttrs())
4411       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4412 
4413     // Only print addrspace(N) if necessary:
4414     maybePrintCallAddrSpace(Operand, &I, Out);
4415 
4416     // If possible, print out the short form of the call instruction.  We can
4417     // only do this if the first argument is a pointer to a nonvararg function,
4418     // and if the return type is not a pointer to a function.
4419     Out << ' ';
4420     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4421     Out << ' ';
4422     writeOperand(Operand, false);
4423     Out << '(';
4424     for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
4425       if (op > 0)
4426         Out << ", ";
4427       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
4428     }
4429 
4430     // Emit an ellipsis if this is a musttail call in a vararg function.  This
4431     // is only to aid readability, musttail calls forward varargs by default.
4432     if (CI->isMustTailCall() && CI->getParent() &&
4433         CI->getParent()->getParent() &&
4434         CI->getParent()->getParent()->isVarArg()) {
4435       if (CI->arg_size() > 0)
4436         Out << ", ";
4437       Out << "...";
4438     }
4439 
4440     Out << ')';
4441     if (PAL.hasFnAttrs())
4442       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4443 
4444     writeOperandBundles(CI);
4445   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
4446     Operand = II->getCalledOperand();
4447     FunctionType *FTy = II->getFunctionType();
4448     Type *RetTy = FTy->getReturnType();
4449     const AttributeList &PAL = II->getAttributes();
4450 
4451     // Print the calling convention being used.
4452     if (II->getCallingConv() != CallingConv::C) {
4453       Out << " ";
4454       PrintCallingConv(II->getCallingConv(), Out);
4455     }
4456 
4457     if (PAL.hasRetAttrs())
4458       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4459 
4460     // Only print addrspace(N) if necessary:
4461     maybePrintCallAddrSpace(Operand, &I, Out);
4462 
4463     // If possible, print out the short form of the invoke instruction. We can
4464     // only do this if the first argument is a pointer to a nonvararg function,
4465     // and if the return type is not a pointer to a function.
4466     //
4467     Out << ' ';
4468     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4469     Out << ' ';
4470     writeOperand(Operand, false);
4471     Out << '(';
4472     for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
4473       if (op)
4474         Out << ", ";
4475       writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
4476     }
4477 
4478     Out << ')';
4479     if (PAL.hasFnAttrs())
4480       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4481 
4482     writeOperandBundles(II);
4483 
4484     Out << "\n          to ";
4485     writeOperand(II->getNormalDest(), true);
4486     Out << " unwind ";
4487     writeOperand(II->getUnwindDest(), true);
4488   } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
4489     Operand = CBI->getCalledOperand();
4490     FunctionType *FTy = CBI->getFunctionType();
4491     Type *RetTy = FTy->getReturnType();
4492     const AttributeList &PAL = CBI->getAttributes();
4493 
4494     // Print the calling convention being used.
4495     if (CBI->getCallingConv() != CallingConv::C) {
4496       Out << " ";
4497       PrintCallingConv(CBI->getCallingConv(), Out);
4498     }
4499 
4500     if (PAL.hasRetAttrs())
4501       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4502 
4503     // If possible, print out the short form of the callbr instruction. We can
4504     // only do this if the first argument is a pointer to a nonvararg function,
4505     // and if the return type is not a pointer to a function.
4506     //
4507     Out << ' ';
4508     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4509     Out << ' ';
4510     writeOperand(Operand, false);
4511     Out << '(';
4512     for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
4513       if (op)
4514         Out << ", ";
4515       writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
4516     }
4517 
4518     Out << ')';
4519     if (PAL.hasFnAttrs())
4520       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4521 
4522     writeOperandBundles(CBI);
4523 
4524     Out << "\n          to ";
4525     writeOperand(CBI->getDefaultDest(), true);
4526     Out << " [";
4527     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
4528       if (i != 0)
4529         Out << ", ";
4530       writeOperand(CBI->getIndirectDest(i), true);
4531     }
4532     Out << ']';
4533   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4534     Out << ' ';
4535     if (AI->isUsedWithInAlloca())
4536       Out << "inalloca ";
4537     if (AI->isSwiftError())
4538       Out << "swifterror ";
4539     TypePrinter.print(AI->getAllocatedType(), Out);
4540 
4541     // Explicitly write the array size if the code is broken, if it's an array
4542     // allocation, or if the type is not canonical for scalar allocations.  The
4543     // latter case prevents the type from mutating when round-tripping through
4544     // assembly.
4545     if (!AI->getArraySize() || AI->isArrayAllocation() ||
4546         !AI->getArraySize()->getType()->isIntegerTy(32)) {
4547       Out << ", ";
4548       writeOperand(AI->getArraySize(), true);
4549     }
4550     if (MaybeAlign A = AI->getAlign()) {
4551       Out << ", align " << A->value();
4552     }
4553 
4554     unsigned AddrSpace = AI->getAddressSpace();
4555     if (AddrSpace != 0) {
4556       Out << ", addrspace(" << AddrSpace << ')';
4557     }
4558   } else if (isa<CastInst>(I)) {
4559     if (Operand) {
4560       Out << ' ';
4561       writeOperand(Operand, true);   // Work with broken code
4562     }
4563     Out << " to ";
4564     TypePrinter.print(I.getType(), Out);
4565   } else if (isa<VAArgInst>(I)) {
4566     if (Operand) {
4567       Out << ' ';
4568       writeOperand(Operand, true);   // Work with broken code
4569     }
4570     Out << ", ";
4571     TypePrinter.print(I.getType(), Out);
4572   } else if (Operand) {   // Print the normal way.
4573     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4574       Out << ' ';
4575       TypePrinter.print(GEP->getSourceElementType(), Out);
4576       Out << ',';
4577     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4578       Out << ' ';
4579       TypePrinter.print(LI->getType(), Out);
4580       Out << ',';
4581     }
4582 
4583     // PrintAllTypes - Instructions who have operands of all the same type
4584     // omit the type from all but the first operand.  If the instruction has
4585     // different type operands (for example br), then they are all printed.
4586     bool PrintAllTypes = false;
4587     Type *TheType = Operand->getType();
4588 
4589     // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
4590     // types.
4591     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
4592         isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||
4593         isa<AtomicRMWInst>(I)) {
4594       PrintAllTypes = true;
4595     } else {
4596       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4597         Operand = I.getOperand(i);
4598         // note that Operand shouldn't be null, but the test helps make dump()
4599         // more tolerant of malformed IR
4600         if (Operand && Operand->getType() != TheType) {
4601           PrintAllTypes = true;    // We have differing types!  Print them all!
4602           break;
4603         }
4604       }
4605     }
4606 
4607     if (!PrintAllTypes) {
4608       Out << ' ';
4609       TypePrinter.print(TheType, Out);
4610     }
4611 
4612     Out << ' ';
4613     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4614       if (i) Out << ", ";
4615       writeOperand(I.getOperand(i), PrintAllTypes);
4616     }
4617   }
4618 
4619   // Print atomic ordering/alignment for memory operations
4620   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4621     if (LI->isAtomic())
4622       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4623     if (MaybeAlign A = LI->getAlign())
4624       Out << ", align " << A->value();
4625   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4626     if (SI->isAtomic())
4627       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4628     if (MaybeAlign A = SI->getAlign())
4629       Out << ", align " << A->value();
4630   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4631     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4632                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
4633     Out << ", align " << CXI->getAlign().value();
4634   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4635     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4636                 RMWI->getSyncScopeID());
4637     Out << ", align " << RMWI->getAlign().value();
4638   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4639     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4640   } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
4641     PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
4642   }
4643 
4644   // Print Metadata info.
4645   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4646   I.getAllMetadata(InstMD);
4647   printMetadataAttachments(InstMD, ", ");
4648 
4649   // Print a nice comment.
4650   printInfoComment(I);
4651 }
4652 
printDbgMarker(const DbgMarker & Marker)4653 void AssemblyWriter::printDbgMarker(const DbgMarker &Marker) {
4654   // There's no formal representation of a DbgMarker -- print purely as a
4655   // debugging aid.
4656   for (const DbgRecord &DPR : Marker.StoredDbgRecords) {
4657     printDbgRecord(DPR);
4658     Out << "\n";
4659   }
4660 
4661   Out << "  DbgMarker -> { ";
4662   printInstruction(*Marker.MarkedInstr);
4663   Out << " }";
4664   return;
4665 }
4666 
printDbgRecord(const DbgRecord & DR)4667 void AssemblyWriter::printDbgRecord(const DbgRecord &DR) {
4668   if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR))
4669     printDbgVariableRecord(*DVR);
4670   else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR))
4671     printDbgLabelRecord(*DLR);
4672   else
4673     llvm_unreachable("Unexpected DbgRecord kind");
4674 }
4675 
printDbgVariableRecord(const DbgVariableRecord & DVR)4676 void AssemblyWriter::printDbgVariableRecord(const DbgVariableRecord &DVR) {
4677   auto WriterCtx = getContext();
4678   Out << "#dbg_";
4679   switch (DVR.getType()) {
4680   case DbgVariableRecord::LocationType::Value:
4681     Out << "value";
4682     break;
4683   case DbgVariableRecord::LocationType::Declare:
4684     Out << "declare";
4685     break;
4686   case DbgVariableRecord::LocationType::Assign:
4687     Out << "assign";
4688     break;
4689   default:
4690     llvm_unreachable(
4691         "Tried to print a DbgVariableRecord with an invalid LocationType!");
4692   }
4693   Out << "(";
4694   WriteAsOperandInternal(Out, DVR.getRawLocation(), WriterCtx, true);
4695   Out << ", ";
4696   WriteAsOperandInternal(Out, DVR.getRawVariable(), WriterCtx, true);
4697   Out << ", ";
4698   WriteAsOperandInternal(Out, DVR.getRawExpression(), WriterCtx, true);
4699   Out << ", ";
4700   if (DVR.isDbgAssign()) {
4701     WriteAsOperandInternal(Out, DVR.getRawAssignID(), WriterCtx, true);
4702     Out << ", ";
4703     WriteAsOperandInternal(Out, DVR.getRawAddress(), WriterCtx, true);
4704     Out << ", ";
4705     WriteAsOperandInternal(Out, DVR.getRawAddressExpression(), WriterCtx, true);
4706     Out << ", ";
4707   }
4708   WriteAsOperandInternal(Out, DVR.getDebugLoc().getAsMDNode(), WriterCtx, true);
4709   Out << ")";
4710 }
4711 
4712 /// printDbgRecordLine - Print a DbgRecord with indentation and a newline
4713 /// character.
printDbgRecordLine(const DbgRecord & DR)4714 void AssemblyWriter::printDbgRecordLine(const DbgRecord &DR) {
4715   // Print lengthier indentation to bring out-of-line with instructions.
4716   Out << "    ";
4717   printDbgRecord(DR);
4718   Out << '\n';
4719 }
4720 
printDbgLabelRecord(const DbgLabelRecord & Label)4721 void AssemblyWriter::printDbgLabelRecord(const DbgLabelRecord &Label) {
4722   auto WriterCtx = getContext();
4723   Out << "#dbg_label(";
4724   WriteAsOperandInternal(Out, Label.getRawLabel(), WriterCtx, true);
4725   Out << ", ";
4726   WriteAsOperandInternal(Out, Label.getDebugLoc(), WriterCtx, true);
4727   Out << ")";
4728 }
4729 
printMetadataAttachments(const SmallVectorImpl<std::pair<unsigned,MDNode * >> & MDs,StringRef Separator)4730 void AssemblyWriter::printMetadataAttachments(
4731     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4732     StringRef Separator) {
4733   if (MDs.empty())
4734     return;
4735 
4736   if (MDNames.empty())
4737     MDs[0].second->getContext().getMDKindNames(MDNames);
4738 
4739   auto WriterCtx = getContext();
4740   for (const auto &I : MDs) {
4741     unsigned Kind = I.first;
4742     Out << Separator;
4743     if (Kind < MDNames.size()) {
4744       Out << "!";
4745       printMetadataIdentifier(MDNames[Kind], Out);
4746     } else
4747       Out << "!<unknown kind #" << Kind << ">";
4748     Out << ' ';
4749     WriteAsOperandInternal(Out, I.second, WriterCtx);
4750   }
4751 }
4752 
writeMDNode(unsigned Slot,const MDNode * Node)4753 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4754   Out << '!' << Slot << " = ";
4755   printMDNodeBody(Node);
4756   Out << "\n";
4757 }
4758 
writeAllMDNodes()4759 void AssemblyWriter::writeAllMDNodes() {
4760   SmallVector<const MDNode *, 16> Nodes;
4761   Nodes.resize(Machine.mdn_size());
4762   for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
4763     Nodes[I.second] = cast<MDNode>(I.first);
4764 
4765   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4766     writeMDNode(i, Nodes[i]);
4767   }
4768 }
4769 
printMDNodeBody(const MDNode * Node)4770 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4771   auto WriterCtx = getContext();
4772   WriteMDNodeBodyInternal(Out, Node, WriterCtx);
4773 }
4774 
writeAttribute(const Attribute & Attr,bool InAttrGroup)4775 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4776   if (!Attr.isTypeAttribute()) {
4777     Out << Attr.getAsString(InAttrGroup);
4778     return;
4779   }
4780 
4781   Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());
4782   if (Type *Ty = Attr.getValueAsType()) {
4783     Out << '(';
4784     TypePrinter.print(Ty, Out);
4785     Out << ')';
4786   }
4787 }
4788 
writeAttributeSet(const AttributeSet & AttrSet,bool InAttrGroup)4789 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4790                                        bool InAttrGroup) {
4791   bool FirstAttr = true;
4792   for (const auto &Attr : AttrSet) {
4793     if (!FirstAttr)
4794       Out << ' ';
4795     writeAttribute(Attr, InAttrGroup);
4796     FirstAttr = false;
4797   }
4798 }
4799 
writeAllAttributeGroups()4800 void AssemblyWriter::writeAllAttributeGroups() {
4801   std::vector<std::pair<AttributeSet, unsigned>> asVec;
4802   asVec.resize(Machine.as_size());
4803 
4804   for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
4805     asVec[I.second] = I;
4806 
4807   for (const auto &I : asVec)
4808     Out << "attributes #" << I.second << " = { "
4809         << I.first.getAsString(true) << " }\n";
4810 }
4811 
printUseListOrder(const Value * V,const std::vector<unsigned> & Shuffle)4812 void AssemblyWriter::printUseListOrder(const Value *V,
4813                                        const std::vector<unsigned> &Shuffle) {
4814   bool IsInFunction = Machine.getFunction();
4815   if (IsInFunction)
4816     Out << "  ";
4817 
4818   Out << "uselistorder";
4819   if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
4820     Out << "_bb ";
4821     writeOperand(BB->getParent(), false);
4822     Out << ", ";
4823     writeOperand(BB, false);
4824   } else {
4825     Out << " ";
4826     writeOperand(V, true);
4827   }
4828   Out << ", { ";
4829 
4830   assert(Shuffle.size() >= 2 && "Shuffle too small");
4831   Out << Shuffle[0];
4832   for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)
4833     Out << ", " << Shuffle[I];
4834   Out << " }\n";
4835 }
4836 
printUseLists(const Function * F)4837 void AssemblyWriter::printUseLists(const Function *F) {
4838   auto It = UseListOrders.find(F);
4839   if (It == UseListOrders.end())
4840     return;
4841 
4842   Out << "\n; uselistorder directives\n";
4843   for (const auto &Pair : It->second)
4844     printUseListOrder(Pair.first, Pair.second);
4845 }
4846 
4847 //===----------------------------------------------------------------------===//
4848 //                       External Interface declarations
4849 //===----------------------------------------------------------------------===//
4850 
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const4851 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4852                      bool ShouldPreserveUseListOrder,
4853                      bool IsForDebug) const {
4854   SlotTracker SlotTable(this->getParent());
4855   formatted_raw_ostream OS(ROS);
4856   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4857                    IsForDebug,
4858                    ShouldPreserveUseListOrder);
4859   W.printFunction(this);
4860 }
4861 
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const4862 void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4863                      bool ShouldPreserveUseListOrder,
4864                      bool IsForDebug) const {
4865   SlotTracker SlotTable(this->getParent());
4866   formatted_raw_ostream OS(ROS);
4867   AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
4868                    IsForDebug,
4869                    ShouldPreserveUseListOrder);
4870   W.printBasicBlock(this);
4871 }
4872 
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const4873 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4874                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4875   SlotTracker SlotTable(this);
4876   formatted_raw_ostream OS(ROS);
4877   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4878                    ShouldPreserveUseListOrder);
4879   W.printModule(this);
4880 }
4881 
print(raw_ostream & ROS,bool IsForDebug) const4882 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4883   SlotTracker SlotTable(getParent());
4884   formatted_raw_ostream OS(ROS);
4885   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4886   W.printNamedMDNode(this);
4887 }
4888 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const4889 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4890                         bool IsForDebug) const {
4891   std::optional<SlotTracker> LocalST;
4892   SlotTracker *SlotTable;
4893   if (auto *ST = MST.getMachine())
4894     SlotTable = ST;
4895   else {
4896     LocalST.emplace(getParent());
4897     SlotTable = &*LocalST;
4898   }
4899 
4900   formatted_raw_ostream OS(ROS);
4901   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4902   W.printNamedMDNode(this);
4903 }
4904 
print(raw_ostream & ROS,bool) const4905 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4906   PrintLLVMName(ROS, getName(), ComdatPrefix);
4907   ROS << " = comdat ";
4908 
4909   switch (getSelectionKind()) {
4910   case Comdat::Any:
4911     ROS << "any";
4912     break;
4913   case Comdat::ExactMatch:
4914     ROS << "exactmatch";
4915     break;
4916   case Comdat::Largest:
4917     ROS << "largest";
4918     break;
4919   case Comdat::NoDeduplicate:
4920     ROS << "nodeduplicate";
4921     break;
4922   case Comdat::SameSize:
4923     ROS << "samesize";
4924     break;
4925   }
4926 
4927   ROS << '\n';
4928 }
4929 
print(raw_ostream & OS,bool,bool NoDetails) const4930 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4931   TypePrinting TP;
4932   TP.print(const_cast<Type*>(this), OS);
4933 
4934   if (NoDetails)
4935     return;
4936 
4937   // If the type is a named struct type, print the body as well.
4938   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4939     if (!STy->isLiteral()) {
4940       OS << " = type ";
4941       TP.printStructBody(STy, OS);
4942     }
4943 }
4944 
isReferencingMDNode(const Instruction & I)4945 static bool isReferencingMDNode(const Instruction &I) {
4946   if (const auto *CI = dyn_cast<CallInst>(&I))
4947     if (Function *F = CI->getCalledFunction())
4948       if (F->isIntrinsic())
4949         for (auto &Op : I.operands())
4950           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4951             if (isa<MDNode>(V->getMetadata()))
4952               return true;
4953   return false;
4954 }
4955 
print(raw_ostream & ROS,bool IsForDebug) const4956 void DbgMarker::print(raw_ostream &ROS, bool IsForDebug) const {
4957 
4958   ModuleSlotTracker MST(getModuleFromDPI(this), true);
4959   print(ROS, MST, IsForDebug);
4960 }
4961 
print(raw_ostream & ROS,bool IsForDebug) const4962 void DbgVariableRecord::print(raw_ostream &ROS, bool IsForDebug) const {
4963 
4964   ModuleSlotTracker MST(getModuleFromDPI(this), true);
4965   print(ROS, MST, IsForDebug);
4966 }
4967 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const4968 void DbgMarker::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4969                       bool IsForDebug) const {
4970   formatted_raw_ostream OS(ROS);
4971   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4972   SlotTracker &SlotTable =
4973       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4974   auto incorporateFunction = [&](const Function *F) {
4975     if (F)
4976       MST.incorporateFunction(*F);
4977   };
4978   incorporateFunction(getParent() ? getParent()->getParent() : nullptr);
4979   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
4980   W.printDbgMarker(*this);
4981 }
4982 
print(raw_ostream & ROS,bool IsForDebug) const4983 void DbgLabelRecord::print(raw_ostream &ROS, bool IsForDebug) const {
4984 
4985   ModuleSlotTracker MST(getModuleFromDPI(this), true);
4986   print(ROS, MST, IsForDebug);
4987 }
4988 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const4989 void DbgVariableRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4990                               bool IsForDebug) const {
4991   formatted_raw_ostream OS(ROS);
4992   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4993   SlotTracker &SlotTable =
4994       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4995   auto incorporateFunction = [&](const Function *F) {
4996     if (F)
4997       MST.incorporateFunction(*F);
4998   };
4999   incorporateFunction(Marker && Marker->getParent()
5000                           ? Marker->getParent()->getParent()
5001                           : nullptr);
5002   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
5003   W.printDbgVariableRecord(*this);
5004 }
5005 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const5006 void DbgLabelRecord::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5007                            bool IsForDebug) const {
5008   formatted_raw_ostream OS(ROS);
5009   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5010   SlotTracker &SlotTable =
5011       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5012   auto incorporateFunction = [&](const Function *F) {
5013     if (F)
5014       MST.incorporateFunction(*F);
5015   };
5016   incorporateFunction(Marker->getParent() ? Marker->getParent()->getParent()
5017                                           : nullptr);
5018   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
5019   W.printDbgLabelRecord(*this);
5020 }
5021 
print(raw_ostream & ROS,bool IsForDebug) const5022 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
5023   bool ShouldInitializeAllMetadata = false;
5024   if (auto *I = dyn_cast<Instruction>(this))
5025     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
5026   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
5027     ShouldInitializeAllMetadata = true;
5028 
5029   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
5030   print(ROS, MST, IsForDebug);
5031 }
5032 
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const5033 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
5034                   bool IsForDebug) const {
5035   formatted_raw_ostream OS(ROS);
5036   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5037   SlotTracker &SlotTable =
5038       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5039   auto incorporateFunction = [&](const Function *F) {
5040     if (F)
5041       MST.incorporateFunction(*F);
5042   };
5043 
5044   if (const Instruction *I = dyn_cast<Instruction>(this)) {
5045     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
5046     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
5047     W.printInstruction(*I);
5048   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
5049     incorporateFunction(BB->getParent());
5050     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
5051     W.printBasicBlock(BB);
5052   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
5053     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
5054     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
5055       W.printGlobal(V);
5056     else if (const Function *F = dyn_cast<Function>(GV))
5057       W.printFunction(F);
5058     else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
5059       W.printAlias(A);
5060     else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
5061       W.printIFunc(I);
5062     else
5063       llvm_unreachable("Unknown GlobalValue to print out!");
5064   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
5065     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
5066   } else if (const Constant *C = dyn_cast<Constant>(this)) {
5067     TypePrinting TypePrinter;
5068     TypePrinter.print(C->getType(), OS);
5069     OS << ' ';
5070     AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
5071     WriteConstantInternal(OS, C, WriterCtx);
5072   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
5073     this->printAsOperand(OS, /* PrintType */ true, MST);
5074   } else {
5075     llvm_unreachable("Unknown value to print out!");
5076   }
5077 }
5078 
5079 /// Print without a type, skipping the TypePrinting object.
5080 ///
5081 /// \return \c true iff printing was successful.
printWithoutType(const Value & V,raw_ostream & O,SlotTracker * Machine,const Module * M)5082 static bool printWithoutType(const Value &V, raw_ostream &O,
5083                              SlotTracker *Machine, const Module *M) {
5084   if (V.hasName() || isa<GlobalValue>(V) ||
5085       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
5086     AsmWriterContext WriterCtx(nullptr, Machine, M);
5087     WriteAsOperandInternal(O, &V, WriterCtx);
5088     return true;
5089   }
5090   return false;
5091 }
5092 
printAsOperandImpl(const Value & V,raw_ostream & O,bool PrintType,ModuleSlotTracker & MST)5093 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
5094                                ModuleSlotTracker &MST) {
5095   TypePrinting TypePrinter(MST.getModule());
5096   if (PrintType) {
5097     TypePrinter.print(V.getType(), O);
5098     O << ' ';
5099   }
5100 
5101   AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
5102   WriteAsOperandInternal(O, &V, WriterCtx);
5103 }
5104 
printAsOperand(raw_ostream & O,bool PrintType,const Module * M) const5105 void Value::printAsOperand(raw_ostream &O, bool PrintType,
5106                            const Module *M) const {
5107   if (!M)
5108     M = getModuleFromVal(this);
5109 
5110   if (!PrintType)
5111     if (printWithoutType(*this, O, nullptr, M))
5112       return;
5113 
5114   SlotTracker Machine(
5115       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
5116   ModuleSlotTracker MST(Machine, M);
5117   printAsOperandImpl(*this, O, PrintType, MST);
5118 }
5119 
printAsOperand(raw_ostream & O,bool PrintType,ModuleSlotTracker & MST) const5120 void Value::printAsOperand(raw_ostream &O, bool PrintType,
5121                            ModuleSlotTracker &MST) const {
5122   if (!PrintType)
5123     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
5124       return;
5125 
5126   printAsOperandImpl(*this, O, PrintType, MST);
5127 }
5128 
5129 /// Recursive version of printMetadataImpl.
printMetadataImplRec(raw_ostream & ROS,const Metadata & MD,AsmWriterContext & WriterCtx)5130 static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
5131                                  AsmWriterContext &WriterCtx) {
5132   formatted_raw_ostream OS(ROS);
5133   WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
5134 
5135   auto *N = dyn_cast<MDNode>(&MD);
5136   if (!N || isa<DIExpression>(MD))
5137     return;
5138 
5139   OS << " = ";
5140   WriteMDNodeBodyInternal(OS, N, WriterCtx);
5141 }
5142 
5143 namespace {
5144 struct MDTreeAsmWriterContext : public AsmWriterContext {
5145   unsigned Level;
5146   // {Level, Printed string}
5147   using EntryTy = std::pair<unsigned, std::string>;
5148   SmallVector<EntryTy, 4> Buffer;
5149 
5150   // Used to break the cycle in case there is any.
5151   SmallPtrSet<const Metadata *, 4> Visited;
5152 
5153   raw_ostream &MainOS;
5154 
MDTreeAsmWriterContext__anon33b632581011::MDTreeAsmWriterContext5155   MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
5156                          raw_ostream &OS, const Metadata *InitMD)
5157       : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
5158 
onWriteMetadataAsOperand__anon33b632581011::MDTreeAsmWriterContext5159   void onWriteMetadataAsOperand(const Metadata *MD) override {
5160     if (!Visited.insert(MD).second)
5161       return;
5162 
5163     std::string Str;
5164     raw_string_ostream SS(Str);
5165     ++Level;
5166     // A placeholder entry to memorize the correct
5167     // position in buffer.
5168     Buffer.emplace_back(std::make_pair(Level, ""));
5169     unsigned InsertIdx = Buffer.size() - 1;
5170 
5171     printMetadataImplRec(SS, *MD, *this);
5172     Buffer[InsertIdx].second = std::move(SS.str());
5173     --Level;
5174   }
5175 
~MDTreeAsmWriterContext__anon33b632581011::MDTreeAsmWriterContext5176   ~MDTreeAsmWriterContext() {
5177     for (const auto &Entry : Buffer) {
5178       MainOS << "\n";
5179       unsigned NumIndent = Entry.first * 2U;
5180       MainOS.indent(NumIndent) << Entry.second;
5181     }
5182   }
5183 };
5184 } // end anonymous namespace
5185 
printMetadataImpl(raw_ostream & ROS,const Metadata & MD,ModuleSlotTracker & MST,const Module * M,bool OnlyAsOperand,bool PrintAsTree=false)5186 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
5187                               ModuleSlotTracker &MST, const Module *M,
5188                               bool OnlyAsOperand, bool PrintAsTree = false) {
5189   formatted_raw_ostream OS(ROS);
5190 
5191   TypePrinting TypePrinter(M);
5192 
5193   std::unique_ptr<AsmWriterContext> WriterCtx;
5194   if (PrintAsTree && !OnlyAsOperand)
5195     WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
5196         &TypePrinter, MST.getMachine(), M, OS, &MD);
5197   else
5198     WriterCtx =
5199         std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
5200 
5201   WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
5202 
5203   auto *N = dyn_cast<MDNode>(&MD);
5204   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
5205     return;
5206 
5207   OS << " = ";
5208   WriteMDNodeBodyInternal(OS, N, *WriterCtx);
5209 }
5210 
printAsOperand(raw_ostream & OS,const Module * M) const5211 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
5212   ModuleSlotTracker MST(M, isa<MDNode>(this));
5213   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
5214 }
5215 
printAsOperand(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M) const5216 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
5217                               const Module *M) const {
5218   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
5219 }
5220 
print(raw_ostream & OS,const Module * M,bool) const5221 void Metadata::print(raw_ostream &OS, const Module *M,
5222                      bool /*IsForDebug*/) const {
5223   ModuleSlotTracker MST(M, isa<MDNode>(this));
5224   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
5225 }
5226 
print(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M,bool) const5227 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
5228                      const Module *M, bool /*IsForDebug*/) const {
5229   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
5230 }
5231 
printTree(raw_ostream & OS,const Module * M) const5232 void MDNode::printTree(raw_ostream &OS, const Module *M) const {
5233   ModuleSlotTracker MST(M, true);
5234   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5235                     /*PrintAsTree=*/true);
5236 }
5237 
printTree(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M) const5238 void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,
5239                        const Module *M) const {
5240   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5241                     /*PrintAsTree=*/true);
5242 }
5243 
print(raw_ostream & ROS,bool IsForDebug) const5244 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
5245   SlotTracker SlotTable(this);
5246   formatted_raw_ostream OS(ROS);
5247   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
5248   W.printModuleSummaryIndex();
5249 }
5250 
collectMDNodes(MachineMDNodeListType & L,unsigned LB,unsigned UB) const5251 void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB,
5252                                        unsigned UB) const {
5253   SlotTracker *ST = MachineStorage.get();
5254   if (!ST)
5255     return;
5256 
5257   for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
5258     if (I.second >= LB && I.second < UB)
5259       L.push_back(std::make_pair(I.second, I.first));
5260 }
5261 
5262 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5263 // Value::dump - allow easy printing of Values from the debugger.
5264 LLVM_DUMP_METHOD
dump() const5265 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5266 
5267 // Value::dump - allow easy printing of Values from the debugger.
5268 LLVM_DUMP_METHOD
dump() const5269 void DbgMarker::dump() const {
5270   print(dbgs(), /*IsForDebug=*/true);
5271   dbgs() << '\n';
5272 }
5273 
5274 // Value::dump - allow easy printing of Values from the debugger.
5275 LLVM_DUMP_METHOD
dump() const5276 void DbgRecord::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5277 
5278 // Type::dump - allow easy printing of Types from the debugger.
5279 LLVM_DUMP_METHOD
dump() const5280 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5281 
5282 // Module::dump() - Allow printing of Modules from the debugger.
5283 LLVM_DUMP_METHOD
dump() const5284 void Module::dump() const {
5285   print(dbgs(), nullptr,
5286         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
5287 }
5288 
5289 // Allow printing of Comdats from the debugger.
5290 LLVM_DUMP_METHOD
dump() const5291 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5292 
5293 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
5294 LLVM_DUMP_METHOD
dump() const5295 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5296 
5297 LLVM_DUMP_METHOD
dump() const5298 void Metadata::dump() const { dump(nullptr); }
5299 
5300 LLVM_DUMP_METHOD
dump(const Module * M) const5301 void Metadata::dump(const Module *M) const {
5302   print(dbgs(), M, /*IsForDebug=*/true);
5303   dbgs() << '\n';
5304 }
5305 
5306 LLVM_DUMP_METHOD
dumpTree() const5307 void MDNode::dumpTree() const { dumpTree(nullptr); }
5308 
5309 LLVM_DUMP_METHOD
dumpTree(const Module * M) const5310 void MDNode::dumpTree(const Module *M) const {
5311   printTree(dbgs(), M);
5312   dbgs() << '\n';
5313 }
5314 
5315 // Allow printing of ModuleSummaryIndex from the debugger.
5316 LLVM_DUMP_METHOD
dump() const5317 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5318 #endif
5319