[AMDGPU] Test codegen'ing True16 additions.
[llvm-project.git] / llvm / lib / IR / AsmWriter.cpp
blobe190d82127908db93048f4285ae12d7ecd9eca37
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.
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.
16 //===----------------------------------------------------------------------===//
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/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalAlias.h"
45 #include "llvm/IR/GlobalIFunc.h"
46 #include "llvm/IR/GlobalObject.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/IRPrintingPasses.h"
50 #include "llvm/IR/InlineAsm.h"
51 #include "llvm/IR/InstrTypes.h"
52 #include "llvm/IR/Instruction.h"
53 #include "llvm/IR/Instructions.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/LLVMContext.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/ModuleSlotTracker.h"
59 #include "llvm/IR/ModuleSummaryIndex.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/TypeFinder.h"
63 #include "llvm/IR/TypedPointerType.h"
64 #include "llvm/IR/Use.h"
65 #include "llvm/IR/User.h"
66 #include "llvm/IR/Value.h"
67 #include "llvm/Support/AtomicOrdering.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/Format.h"
73 #include "llvm/Support/FormattedStream.h"
74 #include "llvm/Support/SaveAndRestore.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <algorithm>
77 #include <cassert>
78 #include <cctype>
79 #include <cstddef>
80 #include <cstdint>
81 #include <iterator>
82 #include <memory>
83 #include <optional>
84 #include <string>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
89 using namespace llvm;
91 // Make virtual table appear in this compilation unit.
92 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
94 //===----------------------------------------------------------------------===//
95 // Helper Functions
96 //===----------------------------------------------------------------------===//
98 using OrderMap = MapVector<const Value *, unsigned>;
100 using UseListOrderMap =
101 DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>;
103 /// Look for a value that might be wrapped as metadata, e.g. a value in a
104 /// metadata operand. Returns the input value as-is if it is not wrapped.
105 static const Value *skipMetadataWrapper(const Value *V) {
106 if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
107 if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
108 return VAM->getValue();
109 return V;
112 static void orderValue(const Value *V, OrderMap &OM) {
113 if (OM.lookup(V))
114 return;
116 if (const Constant *C = dyn_cast<Constant>(V))
117 if (C->getNumOperands() && !isa<GlobalValue>(C))
118 for (const Value *Op : C->operands())
119 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
120 orderValue(Op, OM);
122 // Note: we cannot cache this lookup above, since inserting into the map
123 // changes the map's size, and thus affects the other IDs.
124 unsigned ID = OM.size() + 1;
125 OM[V] = ID;
128 static OrderMap orderModule(const Module *M) {
129 OrderMap OM;
131 for (const GlobalVariable &G : M->globals()) {
132 if (G.hasInitializer())
133 if (!isa<GlobalValue>(G.getInitializer()))
134 orderValue(G.getInitializer(), OM);
135 orderValue(&G, OM);
137 for (const GlobalAlias &A : M->aliases()) {
138 if (!isa<GlobalValue>(A.getAliasee()))
139 orderValue(A.getAliasee(), OM);
140 orderValue(&A, OM);
142 for (const GlobalIFunc &I : M->ifuncs()) {
143 if (!isa<GlobalValue>(I.getResolver()))
144 orderValue(I.getResolver(), OM);
145 orderValue(&I, OM);
147 for (const Function &F : *M) {
148 for (const Use &U : F.operands())
149 if (!isa<GlobalValue>(U.get()))
150 orderValue(U.get(), OM);
152 orderValue(&F, OM);
154 if (F.isDeclaration())
155 continue;
157 for (const Argument &A : F.args())
158 orderValue(&A, OM);
159 for (const BasicBlock &BB : F) {
160 orderValue(&BB, OM);
161 for (const Instruction &I : BB) {
162 for (const Value *Op : I.operands()) {
163 Op = skipMetadataWrapper(Op);
164 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
165 isa<InlineAsm>(*Op))
166 orderValue(Op, OM);
168 orderValue(&I, OM);
172 return OM;
175 static std::vector<unsigned>
176 predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
177 // Predict use-list order for this one.
178 using Entry = std::pair<const Use *, unsigned>;
179 SmallVector<Entry, 64> List;
180 for (const Use &U : V->uses())
181 // Check if this user will be serialized.
182 if (OM.lookup(U.getUser()))
183 List.push_back(std::make_pair(&U, List.size()));
185 if (List.size() < 2)
186 // We may have lost some users.
187 return {};
189 // When referencing a value before its declaration, a temporary value is
190 // created, which will later be RAUWed with the actual value. This reverses
191 // the use list. This happens for all values apart from basic blocks.
192 bool GetsReversed = !isa<BasicBlock>(V);
193 if (auto *BA = dyn_cast<BlockAddress>(V))
194 ID = OM.lookup(BA->getBasicBlock());
195 llvm::sort(List, [&](const Entry &L, const Entry &R) {
196 const Use *LU = L.first;
197 const Use *RU = R.first;
198 if (LU == RU)
199 return false;
201 auto LID = OM.lookup(LU->getUser());
202 auto RID = OM.lookup(RU->getUser());
204 // If ID is 4, then expect: 7 6 5 1 2 3.
205 if (LID < RID) {
206 if (GetsReversed)
207 if (RID <= ID)
208 return true;
209 return false;
211 if (RID < LID) {
212 if (GetsReversed)
213 if (LID <= ID)
214 return false;
215 return true;
218 // LID and RID are equal, so we have different operands of the same user.
219 // Assume operands are added in order for all instructions.
220 if (GetsReversed)
221 if (LID <= ID)
222 return LU->getOperandNo() < RU->getOperandNo();
223 return LU->getOperandNo() > RU->getOperandNo();
226 if (llvm::is_sorted(List, llvm::less_second()))
227 // Order is already correct.
228 return {};
230 // Store the shuffle.
231 std::vector<unsigned> Shuffle(List.size());
232 for (size_t I = 0, E = List.size(); I != E; ++I)
233 Shuffle[I] = List[I].second;
234 return Shuffle;
237 static UseListOrderMap predictUseListOrder(const Module *M) {
238 OrderMap OM = orderModule(M);
239 UseListOrderMap ULOM;
240 for (const auto &Pair : OM) {
241 const Value *V = Pair.first;
242 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
243 continue;
245 std::vector<unsigned> Shuffle =
246 predictValueUseListOrder(V, Pair.second, OM);
247 if (Shuffle.empty())
248 continue;
250 const Function *F = nullptr;
251 if (auto *I = dyn_cast<Instruction>(V))
252 F = I->getFunction();
253 if (auto *A = dyn_cast<Argument>(V))
254 F = A->getParent();
255 if (auto *BB = dyn_cast<BasicBlock>(V))
256 F = BB->getParent();
257 ULOM[F][V] = std::move(Shuffle);
259 return ULOM;
262 static const Module *getModuleFromVal(const Value *V) {
263 if (const Argument *MA = dyn_cast<Argument>(V))
264 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
266 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
267 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
269 if (const Instruction *I = dyn_cast<Instruction>(V)) {
270 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
271 return M ? M->getParent() : nullptr;
274 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
275 return GV->getParent();
277 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
278 for (const User *U : MAV->users())
279 if (isa<Instruction>(U))
280 if (const Module *M = getModuleFromVal(U))
281 return M;
282 return nullptr;
285 return nullptr;
288 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
289 switch (cc) {
290 default: Out << "cc" << cc; break;
291 case CallingConv::Fast: Out << "fastcc"; break;
292 case CallingConv::Cold: Out << "coldcc"; break;
293 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
294 case CallingConv::AnyReg: Out << "anyregcc"; break;
295 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
296 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
297 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
298 case CallingConv::GHC: Out << "ghccc"; break;
299 case CallingConv::Tail: Out << "tailcc"; break;
300 case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
301 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
302 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
303 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
304 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
305 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
306 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
307 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
308 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
309 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
310 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
311 case CallingConv::AArch64_SVE_VectorCall:
312 Out << "aarch64_sve_vector_pcs";
313 break;
314 case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
315 Out << "aarch64_sme_preservemost_from_x0";
316 break;
317 case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
318 Out << "aarch64_sme_preservemost_from_x2";
319 break;
320 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
321 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
322 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
323 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
324 case CallingConv::PTX_Device: Out << "ptx_device"; break;
325 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
326 case CallingConv::Win64: Out << "win64cc"; break;
327 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
328 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
329 case CallingConv::Swift: Out << "swiftcc"; break;
330 case CallingConv::SwiftTail: Out << "swifttailcc"; break;
331 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
332 case CallingConv::DUMMY_HHVM:
333 Out << "hhvmcc";
334 break;
335 case CallingConv::DUMMY_HHVM_C:
336 Out << "hhvm_ccc";
337 break;
338 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
339 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
340 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
341 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
342 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
343 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
344 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
345 case CallingConv::AMDGPU_CS_Chain:
346 Out << "amdgpu_cs_chain";
347 break;
348 case CallingConv::AMDGPU_CS_ChainPreserve:
349 Out << "amdgpu_cs_chain_preserve";
350 break;
351 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
352 case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break;
356 enum PrefixType {
357 GlobalPrefix,
358 ComdatPrefix,
359 LabelPrefix,
360 LocalPrefix,
361 NoPrefix
364 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
365 assert(!Name.empty() && "Cannot get empty name!");
367 // Scan the name to see if it needs quotes first.
368 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
369 if (!NeedsQuotes) {
370 for (unsigned char C : Name) {
371 // By making this unsigned, the value passed in to isalnum will always be
372 // in the range 0-255. This is important when building with MSVC because
373 // its implementation will assert. This situation can arise when dealing
374 // with UTF-8 multibyte characters.
375 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
376 C != '_') {
377 NeedsQuotes = true;
378 break;
383 // If we didn't need any quotes, just write out the name in one blast.
384 if (!NeedsQuotes) {
385 OS << Name;
386 return;
389 // Okay, we need quotes. Output the quotes and escape any scary characters as
390 // needed.
391 OS << '"';
392 printEscapedString(Name, OS);
393 OS << '"';
396 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
397 /// (if the string only contains simple characters) or is surrounded with ""'s
398 /// (if it has special chars in it). Print it out.
399 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
400 switch (Prefix) {
401 case NoPrefix:
402 break;
403 case GlobalPrefix:
404 OS << '@';
405 break;
406 case ComdatPrefix:
407 OS << '$';
408 break;
409 case LabelPrefix:
410 break;
411 case LocalPrefix:
412 OS << '%';
413 break;
415 printLLVMNameWithoutPrefix(OS, Name);
418 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
419 /// (if the string only contains simple characters) or is surrounded with ""'s
420 /// (if it has special chars in it). Print it out.
421 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
422 PrintLLVMName(OS, V->getName(),
423 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
426 static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
427 Out << ", <";
428 if (isa<ScalableVectorType>(Ty))
429 Out << "vscale x ";
430 Out << Mask.size() << " x i32> ";
431 bool FirstElt = true;
432 if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
433 Out << "zeroinitializer";
434 } else if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
435 Out << "poison";
436 } else {
437 Out << "<";
438 for (int Elt : Mask) {
439 if (FirstElt)
440 FirstElt = false;
441 else
442 Out << ", ";
443 Out << "i32 ";
444 if (Elt == PoisonMaskElem)
445 Out << "poison";
446 else
447 Out << Elt;
449 Out << ">";
453 namespace {
455 class TypePrinting {
456 public:
457 TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
459 TypePrinting(const TypePrinting &) = delete;
460 TypePrinting &operator=(const TypePrinting &) = delete;
462 /// The named types that are used by the current module.
463 TypeFinder &getNamedTypes();
465 /// The numbered types, number to type mapping.
466 std::vector<StructType *> &getNumberedTypes();
468 bool empty();
470 void print(Type *Ty, raw_ostream &OS);
472 void printStructBody(StructType *Ty, raw_ostream &OS);
474 private:
475 void incorporateTypes();
477 /// A module to process lazily when needed. Set to nullptr as soon as used.
478 const Module *DeferredM;
480 TypeFinder NamedTypes;
482 // The numbered types, along with their value.
483 DenseMap<StructType *, unsigned> Type2Number;
485 std::vector<StructType *> NumberedTypes;
488 } // end anonymous namespace
490 TypeFinder &TypePrinting::getNamedTypes() {
491 incorporateTypes();
492 return NamedTypes;
495 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
496 incorporateTypes();
498 // We know all the numbers that each type is used and we know that it is a
499 // dense assignment. Convert the map to an index table, if it's not done
500 // already (judging from the sizes):
501 if (NumberedTypes.size() == Type2Number.size())
502 return NumberedTypes;
504 NumberedTypes.resize(Type2Number.size());
505 for (const auto &P : Type2Number) {
506 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
507 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
508 NumberedTypes[P.second] = P.first;
510 return NumberedTypes;
513 bool TypePrinting::empty() {
514 incorporateTypes();
515 return NamedTypes.empty() && Type2Number.empty();
518 void TypePrinting::incorporateTypes() {
519 if (!DeferredM)
520 return;
522 NamedTypes.run(*DeferredM, false);
523 DeferredM = nullptr;
525 // The list of struct types we got back includes all the struct types, split
526 // the unnamed ones out to a numbering and remove the anonymous structs.
527 unsigned NextNumber = 0;
529 std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
530 for (StructType *STy : NamedTypes) {
531 // Ignore anonymous types.
532 if (STy->isLiteral())
533 continue;
535 if (STy->getName().empty())
536 Type2Number[STy] = NextNumber++;
537 else
538 *NextToUse++ = STy;
541 NamedTypes.erase(NextToUse, NamedTypes.end());
544 /// Write the specified type to the specified raw_ostream, making use of type
545 /// names or up references to shorten the type name where possible.
546 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
547 switch (Ty->getTypeID()) {
548 case Type::VoidTyID: OS << "void"; return;
549 case Type::HalfTyID: OS << "half"; return;
550 case Type::BFloatTyID: OS << "bfloat"; return;
551 case Type::FloatTyID: OS << "float"; return;
552 case Type::DoubleTyID: OS << "double"; return;
553 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
554 case Type::FP128TyID: OS << "fp128"; return;
555 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
556 case Type::LabelTyID: OS << "label"; return;
557 case Type::MetadataTyID: OS << "metadata"; return;
558 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
559 case Type::X86_AMXTyID: OS << "x86_amx"; return;
560 case Type::TokenTyID: OS << "token"; return;
561 case Type::IntegerTyID:
562 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
563 return;
565 case Type::FunctionTyID: {
566 FunctionType *FTy = cast<FunctionType>(Ty);
567 print(FTy->getReturnType(), OS);
568 OS << " (";
569 ListSeparator LS;
570 for (Type *Ty : FTy->params()) {
571 OS << LS;
572 print(Ty, OS);
574 if (FTy->isVarArg())
575 OS << LS << "...";
576 OS << ')';
577 return;
579 case Type::StructTyID: {
580 StructType *STy = cast<StructType>(Ty);
582 if (STy->isLiteral())
583 return printStructBody(STy, OS);
585 if (!STy->getName().empty())
586 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
588 incorporateTypes();
589 const auto I = Type2Number.find(STy);
590 if (I != Type2Number.end())
591 OS << '%' << I->second;
592 else // Not enumerated, print the hex address.
593 OS << "%\"type " << STy << '\"';
594 return;
596 case Type::PointerTyID: {
597 PointerType *PTy = cast<PointerType>(Ty);
598 OS << "ptr";
599 if (unsigned AddressSpace = PTy->getAddressSpace())
600 OS << " addrspace(" << AddressSpace << ')';
601 return;
603 case Type::ArrayTyID: {
604 ArrayType *ATy = cast<ArrayType>(Ty);
605 OS << '[' << ATy->getNumElements() << " x ";
606 print(ATy->getElementType(), OS);
607 OS << ']';
608 return;
610 case Type::FixedVectorTyID:
611 case Type::ScalableVectorTyID: {
612 VectorType *PTy = cast<VectorType>(Ty);
613 ElementCount EC = PTy->getElementCount();
614 OS << "<";
615 if (EC.isScalable())
616 OS << "vscale x ";
617 OS << EC.getKnownMinValue() << " x ";
618 print(PTy->getElementType(), OS);
619 OS << '>';
620 return;
622 case Type::TypedPointerTyID: {
623 TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
624 OS << "typedptr(" << *TPTy->getElementType() << ", "
625 << TPTy->getAddressSpace() << ")";
626 return;
628 case Type::TargetExtTyID:
629 TargetExtType *TETy = cast<TargetExtType>(Ty);
630 OS << "target(\"";
631 printEscapedString(Ty->getTargetExtName(), OS);
632 OS << "\"";
633 for (Type *Inner : TETy->type_params())
634 OS << ", " << *Inner;
635 for (unsigned IntParam : TETy->int_params())
636 OS << ", " << IntParam;
637 OS << ")";
638 return;
640 llvm_unreachable("Invalid TypeID");
643 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
644 if (STy->isOpaque()) {
645 OS << "opaque";
646 return;
649 if (STy->isPacked())
650 OS << '<';
652 if (STy->getNumElements() == 0) {
653 OS << "{}";
654 } else {
655 OS << "{ ";
656 ListSeparator LS;
657 for (Type *Ty : STy->elements()) {
658 OS << LS;
659 print(Ty, OS);
662 OS << " }";
664 if (STy->isPacked())
665 OS << '>';
668 AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
670 namespace llvm {
672 //===----------------------------------------------------------------------===//
673 // SlotTracker Class: Enumerate slot numbers for unnamed values
674 //===----------------------------------------------------------------------===//
675 /// This class provides computation of slot numbers for LLVM Assembly writing.
677 class SlotTracker : public AbstractSlotTrackerStorage {
678 public:
679 /// ValueMap - A mapping of Values to slot numbers.
680 using ValueMap = DenseMap<const Value *, unsigned>;
682 private:
683 /// TheModule - The module for which we are holding slot numbers.
684 const Module* TheModule;
686 /// TheFunction - The function for which we are holding slot numbers.
687 const Function* TheFunction = nullptr;
688 bool FunctionProcessed = false;
689 bool ShouldInitializeAllMetadata;
691 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
692 ProcessModuleHookFn;
693 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
694 ProcessFunctionHookFn;
696 /// The summary index for which we are holding slot numbers.
697 const ModuleSummaryIndex *TheIndex = nullptr;
699 /// mMap - The slot map for the module level data.
700 ValueMap mMap;
701 unsigned mNext = 0;
703 /// fMap - The slot map for the function level data.
704 ValueMap fMap;
705 unsigned fNext = 0;
707 /// mdnMap - Map for MDNodes.
708 DenseMap<const MDNode*, unsigned> mdnMap;
709 unsigned mdnNext = 0;
711 /// asMap - The slot map for attribute sets.
712 DenseMap<AttributeSet, unsigned> asMap;
713 unsigned asNext = 0;
715 /// ModulePathMap - The slot map for Module paths used in the summary index.
716 StringMap<unsigned> ModulePathMap;
717 unsigned ModulePathNext = 0;
719 /// GUIDMap - The slot map for GUIDs used in the summary index.
720 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
721 unsigned GUIDNext = 0;
723 /// TypeIdMap - The slot map for type ids used in the summary index.
724 StringMap<unsigned> TypeIdMap;
725 unsigned TypeIdNext = 0;
727 public:
728 /// Construct from a module.
730 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
731 /// functions, giving correct numbering for metadata referenced only from
732 /// within a function (even if no functions have been initialized).
733 explicit SlotTracker(const Module *M,
734 bool ShouldInitializeAllMetadata = false);
736 /// Construct from a function, starting out in incorp state.
738 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
739 /// functions, giving correct numbering for metadata referenced only from
740 /// within a function (even if no functions have been initialized).
741 explicit SlotTracker(const Function *F,
742 bool ShouldInitializeAllMetadata = false);
744 /// Construct from a module summary index.
745 explicit SlotTracker(const ModuleSummaryIndex *Index);
747 SlotTracker(const SlotTracker &) = delete;
748 SlotTracker &operator=(const SlotTracker &) = delete;
750 ~SlotTracker() = default;
752 void setProcessHook(
753 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
754 void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
755 const Function *, bool)>);
757 unsigned getNextMetadataSlot() override { return mdnNext; }
759 void createMetadataSlot(const MDNode *N) override;
761 /// Return the slot number of the specified value in it's type
762 /// plane. If something is not in the SlotTracker, return -1.
763 int getLocalSlot(const Value *V);
764 int getGlobalSlot(const GlobalValue *V);
765 int getMetadataSlot(const MDNode *N) override;
766 int getAttributeGroupSlot(AttributeSet AS);
767 int getModulePathSlot(StringRef Path);
768 int getGUIDSlot(GlobalValue::GUID GUID);
769 int getTypeIdSlot(StringRef Id);
771 /// If you'd like to deal with a function instead of just a module, use
772 /// this method to get its data into the SlotTracker.
773 void incorporateFunction(const Function *F) {
774 TheFunction = F;
775 FunctionProcessed = false;
778 const Function *getFunction() const { return TheFunction; }
780 /// After calling incorporateFunction, use this method to remove the
781 /// most recently incorporated function from the SlotTracker. This
782 /// will reset the state of the machine back to just the module contents.
783 void purgeFunction();
785 /// MDNode map iterators.
786 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
788 mdn_iterator mdn_begin() { return mdnMap.begin(); }
789 mdn_iterator mdn_end() { return mdnMap.end(); }
790 unsigned mdn_size() const { return mdnMap.size(); }
791 bool mdn_empty() const { return mdnMap.empty(); }
793 /// AttributeSet map iterators.
794 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
796 as_iterator as_begin() { return asMap.begin(); }
797 as_iterator as_end() { return asMap.end(); }
798 unsigned as_size() const { return asMap.size(); }
799 bool as_empty() const { return asMap.empty(); }
801 /// GUID map iterators.
802 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
804 /// These functions do the actual initialization.
805 inline void initializeIfNeeded();
806 int initializeIndexIfNeeded();
808 // Implementation Details
809 private:
810 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
811 void CreateModuleSlot(const GlobalValue *V);
813 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
814 void CreateMetadataSlot(const MDNode *N);
816 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
817 void CreateFunctionSlot(const Value *V);
819 /// Insert the specified AttributeSet into the slot table.
820 void CreateAttributeSetSlot(AttributeSet AS);
822 inline void CreateModulePathSlot(StringRef Path);
823 void CreateGUIDSlot(GlobalValue::GUID GUID);
824 void CreateTypeIdSlot(StringRef Id);
826 /// Add all of the module level global variables (and their initializers)
827 /// and function declarations, but not the contents of those functions.
828 void processModule();
829 // Returns number of allocated slots
830 int processIndex();
832 /// Add all of the functions arguments, basic blocks, and instructions.
833 void processFunction();
835 /// Add the metadata directly attached to a GlobalObject.
836 void processGlobalObjectMetadata(const GlobalObject &GO);
838 /// Add all of the metadata from a function.
839 void processFunctionMetadata(const Function &F);
841 /// Add all of the metadata from an instruction.
842 void processInstructionMetadata(const Instruction &I);
845 } // end namespace llvm
847 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
848 const Function *F)
849 : M(M), F(F), Machine(&Machine) {}
851 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
852 bool ShouldInitializeAllMetadata)
853 : ShouldCreateStorage(M),
854 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
856 ModuleSlotTracker::~ModuleSlotTracker() = default;
858 SlotTracker *ModuleSlotTracker::getMachine() {
859 if (!ShouldCreateStorage)
860 return Machine;
862 ShouldCreateStorage = false;
863 MachineStorage =
864 std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
865 Machine = MachineStorage.get();
866 if (ProcessModuleHookFn)
867 Machine->setProcessHook(ProcessModuleHookFn);
868 if (ProcessFunctionHookFn)
869 Machine->setProcessHook(ProcessFunctionHookFn);
870 return Machine;
873 void ModuleSlotTracker::incorporateFunction(const Function &F) {
874 // Using getMachine() may lazily create the slot tracker.
875 if (!getMachine())
876 return;
878 // Nothing to do if this is the right function already.
879 if (this->F == &F)
880 return;
881 if (this->F)
882 Machine->purgeFunction();
883 Machine->incorporateFunction(&F);
884 this->F = &F;
887 int ModuleSlotTracker::getLocalSlot(const Value *V) {
888 assert(F && "No function incorporated");
889 return Machine->getLocalSlot(V);
892 void ModuleSlotTracker::setProcessHook(
893 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
894 Fn) {
895 ProcessModuleHookFn = Fn;
898 void ModuleSlotTracker::setProcessHook(
899 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
900 Fn) {
901 ProcessFunctionHookFn = Fn;
904 static SlotTracker *createSlotTracker(const Value *V) {
905 if (const Argument *FA = dyn_cast<Argument>(V))
906 return new SlotTracker(FA->getParent());
908 if (const Instruction *I = dyn_cast<Instruction>(V))
909 if (I->getParent())
910 return new SlotTracker(I->getParent()->getParent());
912 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
913 return new SlotTracker(BB->getParent());
915 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
916 return new SlotTracker(GV->getParent());
918 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
919 return new SlotTracker(GA->getParent());
921 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
922 return new SlotTracker(GIF->getParent());
924 if (const Function *Func = dyn_cast<Function>(V))
925 return new SlotTracker(Func);
927 return nullptr;
930 #if 0
931 #define ST_DEBUG(X) dbgs() << X
932 #else
933 #define ST_DEBUG(X)
934 #endif
936 // Module level constructor. Causes the contents of the Module (sans functions)
937 // to be added to the slot table.
938 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
939 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
941 // Function level constructor. Causes the contents of the Module and the one
942 // function provided to be added to the slot table.
943 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
944 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
945 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
947 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
948 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
950 inline void SlotTracker::initializeIfNeeded() {
951 if (TheModule) {
952 processModule();
953 TheModule = nullptr; ///< Prevent re-processing next time we're called.
956 if (TheFunction && !FunctionProcessed)
957 processFunction();
960 int SlotTracker::initializeIndexIfNeeded() {
961 if (!TheIndex)
962 return 0;
963 int NumSlots = processIndex();
964 TheIndex = nullptr; ///< Prevent re-processing next time we're called.
965 return NumSlots;
968 // Iterate through all the global variables, functions, and global
969 // variable initializers and create slots for them.
970 void SlotTracker::processModule() {
971 ST_DEBUG("begin processModule!\n");
973 // Add all of the unnamed global variables to the value table.
974 for (const GlobalVariable &Var : TheModule->globals()) {
975 if (!Var.hasName())
976 CreateModuleSlot(&Var);
977 processGlobalObjectMetadata(Var);
978 auto Attrs = Var.getAttributes();
979 if (Attrs.hasAttributes())
980 CreateAttributeSetSlot(Attrs);
983 for (const GlobalAlias &A : TheModule->aliases()) {
984 if (!A.hasName())
985 CreateModuleSlot(&A);
988 for (const GlobalIFunc &I : TheModule->ifuncs()) {
989 if (!I.hasName())
990 CreateModuleSlot(&I);
993 // Add metadata used by named metadata.
994 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
995 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
996 CreateMetadataSlot(NMD.getOperand(i));
999 for (const Function &F : *TheModule) {
1000 if (!F.hasName())
1001 // Add all the unnamed functions to the table.
1002 CreateModuleSlot(&F);
1004 if (ShouldInitializeAllMetadata)
1005 processFunctionMetadata(F);
1007 // Add all the function attributes to the table.
1008 // FIXME: Add attributes of other objects?
1009 AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
1010 if (FnAttrs.hasAttributes())
1011 CreateAttributeSetSlot(FnAttrs);
1014 if (ProcessModuleHookFn)
1015 ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
1017 ST_DEBUG("end processModule!\n");
1020 // Process the arguments, basic blocks, and instructions of a function.
1021 void SlotTracker::processFunction() {
1022 ST_DEBUG("begin processFunction!\n");
1023 fNext = 0;
1025 // Process function metadata if it wasn't hit at the module-level.
1026 if (!ShouldInitializeAllMetadata)
1027 processFunctionMetadata(*TheFunction);
1029 // Add all the function arguments with no names.
1030 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1031 AE = TheFunction->arg_end(); AI != AE; ++AI)
1032 if (!AI->hasName())
1033 CreateFunctionSlot(&*AI);
1035 ST_DEBUG("Inserting Instructions:\n");
1037 // Add all of the basic blocks and instructions with no names.
1038 for (auto &BB : *TheFunction) {
1039 if (!BB.hasName())
1040 CreateFunctionSlot(&BB);
1042 for (auto &I : BB) {
1043 if (!I.getType()->isVoidTy() && !I.hasName())
1044 CreateFunctionSlot(&I);
1046 // We allow direct calls to any llvm.foo function here, because the
1047 // target may not be linked into the optimizer.
1048 if (const auto *Call = dyn_cast<CallBase>(&I)) {
1049 // Add all the call attributes to the table.
1050 AttributeSet Attrs = Call->getAttributes().getFnAttrs();
1051 if (Attrs.hasAttributes())
1052 CreateAttributeSetSlot(Attrs);
1057 if (ProcessFunctionHookFn)
1058 ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
1060 FunctionProcessed = true;
1062 ST_DEBUG("end processFunction!\n");
1065 // Iterate through all the GUID in the index and create slots for them.
1066 int SlotTracker::processIndex() {
1067 ST_DEBUG("begin processIndex!\n");
1068 assert(TheIndex);
1070 // The first block of slots are just the module ids, which start at 0 and are
1071 // assigned consecutively. Since the StringMap iteration order isn't
1072 // guaranteed, order by path string before assigning slots.
1073 std::vector<StringRef> ModulePaths;
1074 for (auto &[ModPath, _] : TheIndex->modulePaths())
1075 ModulePaths.push_back(ModPath);
1076 llvm::sort(ModulePaths.begin(), ModulePaths.end());
1077 for (auto &ModPath : ModulePaths)
1078 CreateModulePathSlot(ModPath);
1080 // Start numbering the GUIDs after the module ids.
1081 GUIDNext = ModulePathNext;
1083 for (auto &GlobalList : *TheIndex)
1084 CreateGUIDSlot(GlobalList.first);
1086 for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1087 CreateGUIDSlot(GlobalValue::getGUID(TId.first));
1089 // Start numbering the TypeIds after the GUIDs.
1090 TypeIdNext = GUIDNext;
1091 for (const auto &TID : TheIndex->typeIds())
1092 CreateTypeIdSlot(TID.second.first);
1094 ST_DEBUG("end processIndex!\n");
1095 return TypeIdNext;
1098 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1099 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1100 GO.getAllMetadata(MDs);
1101 for (auto &MD : MDs)
1102 CreateMetadataSlot(MD.second);
1105 void SlotTracker::processFunctionMetadata(const Function &F) {
1106 processGlobalObjectMetadata(F);
1107 for (auto &BB : F) {
1108 for (auto &I : BB)
1109 processInstructionMetadata(I);
1113 void SlotTracker::processInstructionMetadata(const Instruction &I) {
1114 // Process metadata used directly by intrinsics.
1115 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1116 if (Function *F = CI->getCalledFunction())
1117 if (F->isIntrinsic())
1118 for (auto &Op : I.operands())
1119 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1120 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1121 CreateMetadataSlot(N);
1123 // Process metadata attached to this instruction.
1124 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1125 I.getAllMetadata(MDs);
1126 for (auto &MD : MDs)
1127 CreateMetadataSlot(MD.second);
1130 /// Clean up after incorporating a function. This is the only way to get out of
1131 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1132 /// incorporation state is indicated by TheFunction != 0.
1133 void SlotTracker::purgeFunction() {
1134 ST_DEBUG("begin purgeFunction!\n");
1135 fMap.clear(); // Simply discard the function level map
1136 TheFunction = nullptr;
1137 FunctionProcessed = false;
1138 ST_DEBUG("end purgeFunction!\n");
1141 /// getGlobalSlot - Get the slot number of a global value.
1142 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1143 // Check for uninitialized state and do lazy initialization.
1144 initializeIfNeeded();
1146 // Find the value in the module map
1147 ValueMap::iterator MI = mMap.find(V);
1148 return MI == mMap.end() ? -1 : (int)MI->second;
1151 void SlotTracker::setProcessHook(
1152 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
1153 Fn) {
1154 ProcessModuleHookFn = Fn;
1157 void SlotTracker::setProcessHook(
1158 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
1159 Fn) {
1160 ProcessFunctionHookFn = Fn;
1163 /// getMetadataSlot - Get the slot number of a MDNode.
1164 void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
1166 /// getMetadataSlot - Get the slot number of a MDNode.
1167 int SlotTracker::getMetadataSlot(const MDNode *N) {
1168 // Check for uninitialized state and do lazy initialization.
1169 initializeIfNeeded();
1171 // Find the MDNode in the module map
1172 mdn_iterator MI = mdnMap.find(N);
1173 return MI == mdnMap.end() ? -1 : (int)MI->second;
1176 /// getLocalSlot - Get the slot number for a value that is local to a function.
1177 int SlotTracker::getLocalSlot(const Value *V) {
1178 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1180 // Check for uninitialized state and do lazy initialization.
1181 initializeIfNeeded();
1183 ValueMap::iterator FI = fMap.find(V);
1184 return FI == fMap.end() ? -1 : (int)FI->second;
1187 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1188 // Check for uninitialized state and do lazy initialization.
1189 initializeIfNeeded();
1191 // Find the AttributeSet in the module map.
1192 as_iterator AI = asMap.find(AS);
1193 return AI == asMap.end() ? -1 : (int)AI->second;
1196 int SlotTracker::getModulePathSlot(StringRef Path) {
1197 // Check for uninitialized state and do lazy initialization.
1198 initializeIndexIfNeeded();
1200 // Find the Module path in the map
1201 auto I = ModulePathMap.find(Path);
1202 return I == ModulePathMap.end() ? -1 : (int)I->second;
1205 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1206 // Check for uninitialized state and do lazy initialization.
1207 initializeIndexIfNeeded();
1209 // Find the GUID in the map
1210 guid_iterator I = GUIDMap.find(GUID);
1211 return I == GUIDMap.end() ? -1 : (int)I->second;
1214 int SlotTracker::getTypeIdSlot(StringRef Id) {
1215 // Check for uninitialized state and do lazy initialization.
1216 initializeIndexIfNeeded();
1218 // Find the TypeId string in the map
1219 auto I = TypeIdMap.find(Id);
1220 return I == TypeIdMap.end() ? -1 : (int)I->second;
1223 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1224 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1225 assert(V && "Can't insert a null Value into SlotTracker!");
1226 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1227 assert(!V->hasName() && "Doesn't need a slot!");
1229 unsigned DestSlot = mNext++;
1230 mMap[V] = DestSlot;
1232 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1233 DestSlot << " [");
1234 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1235 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1236 (isa<Function>(V) ? 'F' :
1237 (isa<GlobalAlias>(V) ? 'A' :
1238 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1241 /// CreateSlot - Create a new slot for the specified value if it has no name.
1242 void SlotTracker::CreateFunctionSlot(const Value *V) {
1243 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1245 unsigned DestSlot = fNext++;
1246 fMap[V] = DestSlot;
1248 // G = Global, F = Function, o = other
1249 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1250 DestSlot << " [o]\n");
1253 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1254 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1255 assert(N && "Can't insert a null Value into SlotTracker!");
1257 // Don't make slots for DIExpressions or DIArgLists. We just print them inline
1258 // everywhere.
1259 if (isa<DIExpression>(N) || isa<DIArgList>(N))
1260 return;
1262 unsigned DestSlot = mdnNext;
1263 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1264 return;
1265 ++mdnNext;
1267 // Recursively add any MDNodes referenced by operands.
1268 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1269 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1270 CreateMetadataSlot(Op);
1273 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1274 assert(AS.hasAttributes() && "Doesn't need a slot!");
1276 as_iterator I = asMap.find(AS);
1277 if (I != asMap.end())
1278 return;
1280 unsigned DestSlot = asNext++;
1281 asMap[AS] = DestSlot;
1284 /// Create a new slot for the specified Module
1285 void SlotTracker::CreateModulePathSlot(StringRef Path) {
1286 ModulePathMap[Path] = ModulePathNext++;
1289 /// Create a new slot for the specified GUID
1290 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1291 GUIDMap[GUID] = GUIDNext++;
1294 /// Create a new slot for the specified Id
1295 void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1296 TypeIdMap[Id] = TypeIdNext++;
1299 namespace {
1300 /// Common instances used by most of the printer functions.
1301 struct AsmWriterContext {
1302 TypePrinting *TypePrinter = nullptr;
1303 SlotTracker *Machine = nullptr;
1304 const Module *Context = nullptr;
1306 AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
1307 : TypePrinter(TP), Machine(ST), Context(M) {}
1309 static AsmWriterContext &getEmpty() {
1310 static AsmWriterContext EmptyCtx(nullptr, nullptr);
1311 return EmptyCtx;
1314 /// A callback that will be triggered when the underlying printer
1315 /// prints a Metadata as operand.
1316 virtual void onWriteMetadataAsOperand(const Metadata *) {}
1318 virtual ~AsmWriterContext() = default;
1320 } // end anonymous namespace
1322 //===----------------------------------------------------------------------===//
1323 // AsmWriter Implementation
1324 //===----------------------------------------------------------------------===//
1326 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1327 AsmWriterContext &WriterCtx);
1329 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1330 AsmWriterContext &WriterCtx,
1331 bool FromValue = false);
1333 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1334 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
1335 Out << FPO->getFastMathFlags();
1337 if (const OverflowingBinaryOperator *OBO =
1338 dyn_cast<OverflowingBinaryOperator>(U)) {
1339 if (OBO->hasNoUnsignedWrap())
1340 Out << " nuw";
1341 if (OBO->hasNoSignedWrap())
1342 Out << " nsw";
1343 } else if (const PossiblyExactOperator *Div =
1344 dyn_cast<PossiblyExactOperator>(U)) {
1345 if (Div->isExact())
1346 Out << " exact";
1347 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1348 if (GEP->isInBounds())
1349 Out << " inbounds";
1353 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1354 AsmWriterContext &WriterCtx) {
1355 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1356 if (CI->getType()->isIntegerTy(1)) {
1357 Out << (CI->getZExtValue() ? "true" : "false");
1358 return;
1360 Out << CI->getValue();
1361 return;
1364 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1365 const APFloat &APF = CFP->getValueAPF();
1366 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1367 &APF.getSemantics() == &APFloat::IEEEdouble()) {
1368 // We would like to output the FP constant value in exponential notation,
1369 // but we cannot do this if doing so will lose precision. Check here to
1370 // make sure that we only output it in exponential format if we can parse
1371 // the value back and get the same value.
1373 bool ignored;
1374 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1375 bool isInf = APF.isInfinity();
1376 bool isNaN = APF.isNaN();
1377 if (!isInf && !isNaN) {
1378 double Val = APF.convertToDouble();
1379 SmallString<128> StrVal;
1380 APF.toString(StrVal, 6, 0, false);
1381 // Check to make sure that the stringized number is not some string like
1382 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1383 // that the string matches the "[-+]?[0-9]" regex.
1385 assert((isDigit(StrVal[0]) || ((StrVal[0] == '-' || StrVal[0] == '+') &&
1386 isDigit(StrVal[1]))) &&
1387 "[-+]?[0-9] regex does not match!");
1388 // Reparse stringized version!
1389 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1390 Out << StrVal;
1391 return;
1394 // Otherwise we could not reparse it to exactly the same value, so we must
1395 // output the string in hexadecimal format! Note that loading and storing
1396 // floating point types changes the bits of NaNs on some hosts, notably
1397 // x86, so we must not use these types.
1398 static_assert(sizeof(double) == sizeof(uint64_t),
1399 "assuming that double is 64 bits!");
1400 APFloat apf = APF;
1401 // Floats are represented in ASCII IR as double, convert.
1402 // FIXME: We should allow 32-bit hex float and remove this.
1403 if (!isDouble) {
1404 // A signaling NaN is quieted on conversion, so we need to recreate the
1405 // expected value after convert (quiet bit of the payload is clear).
1406 bool IsSNAN = apf.isSignaling();
1407 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1408 &ignored);
1409 if (IsSNAN) {
1410 APInt Payload = apf.bitcastToAPInt();
1411 apf = APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(),
1412 &Payload);
1415 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1416 return;
1419 // Either half, bfloat or some form of long double.
1420 // These appear as a magic letter identifying the type, then a
1421 // fixed number of hex digits.
1422 Out << "0x";
1423 APInt API = APF.bitcastToAPInt();
1424 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1425 Out << 'K';
1426 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1427 /*Upper=*/true);
1428 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1429 /*Upper=*/true);
1430 return;
1431 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1432 Out << 'L';
1433 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1434 /*Upper=*/true);
1435 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1436 /*Upper=*/true);
1437 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1438 Out << 'M';
1439 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1440 /*Upper=*/true);
1441 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1442 /*Upper=*/true);
1443 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1444 Out << 'H';
1445 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1446 /*Upper=*/true);
1447 } else if (&APF.getSemantics() == &APFloat::BFloat()) {
1448 Out << 'R';
1449 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1450 /*Upper=*/true);
1451 } else
1452 llvm_unreachable("Unsupported floating point type");
1453 return;
1456 if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
1457 Out << "zeroinitializer";
1458 return;
1461 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1462 Out << "blockaddress(";
1463 WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
1464 Out << ", ";
1465 WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
1466 Out << ")";
1467 return;
1470 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1471 Out << "dso_local_equivalent ";
1472 WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
1473 return;
1476 if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
1477 Out << "no_cfi ";
1478 WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
1479 return;
1482 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1483 Type *ETy = CA->getType()->getElementType();
1484 Out << '[';
1485 WriterCtx.TypePrinter->print(ETy, Out);
1486 Out << ' ';
1487 WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
1488 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1489 Out << ", ";
1490 WriterCtx.TypePrinter->print(ETy, Out);
1491 Out << ' ';
1492 WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
1494 Out << ']';
1495 return;
1498 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1499 // As a special case, print the array as a string if it is an array of
1500 // i8 with ConstantInt values.
1501 if (CA->isString()) {
1502 Out << "c\"";
1503 printEscapedString(CA->getAsString(), Out);
1504 Out << '"';
1505 return;
1508 Type *ETy = CA->getType()->getElementType();
1509 Out << '[';
1510 WriterCtx.TypePrinter->print(ETy, Out);
1511 Out << ' ';
1512 WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
1513 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1514 Out << ", ";
1515 WriterCtx.TypePrinter->print(ETy, Out);
1516 Out << ' ';
1517 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
1519 Out << ']';
1520 return;
1523 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1524 if (CS->getType()->isPacked())
1525 Out << '<';
1526 Out << '{';
1527 unsigned N = CS->getNumOperands();
1528 if (N) {
1529 Out << ' ';
1530 WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
1531 Out << ' ';
1533 WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
1535 for (unsigned i = 1; i < N; i++) {
1536 Out << ", ";
1537 WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
1538 Out << ' ';
1540 WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
1542 Out << ' ';
1545 Out << '}';
1546 if (CS->getType()->isPacked())
1547 Out << '>';
1548 return;
1551 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1552 auto *CVVTy = cast<FixedVectorType>(CV->getType());
1553 Type *ETy = CVVTy->getElementType();
1554 Out << '<';
1555 WriterCtx.TypePrinter->print(ETy, Out);
1556 Out << ' ';
1557 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
1558 for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1559 Out << ", ";
1560 WriterCtx.TypePrinter->print(ETy, Out);
1561 Out << ' ';
1562 WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
1564 Out << '>';
1565 return;
1568 if (isa<ConstantPointerNull>(CV)) {
1569 Out << "null";
1570 return;
1573 if (isa<ConstantTokenNone>(CV)) {
1574 Out << "none";
1575 return;
1578 if (isa<PoisonValue>(CV)) {
1579 Out << "poison";
1580 return;
1583 if (isa<UndefValue>(CV)) {
1584 Out << "undef";
1585 return;
1588 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1589 Out << CE->getOpcodeName();
1590 WriteOptimizationInfo(Out, CE);
1591 if (CE->isCompare())
1592 Out << ' ' << static_cast<CmpInst::Predicate>(CE->getPredicate());
1593 Out << " (";
1595 std::optional<unsigned> InRangeOp;
1596 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1597 WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
1598 Out << ", ";
1599 InRangeOp = GEP->getInRangeIndex();
1600 if (InRangeOp)
1601 ++*InRangeOp;
1604 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1605 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1606 Out << "inrange ";
1607 WriterCtx.TypePrinter->print((*OI)->getType(), Out);
1608 Out << ' ';
1609 WriteAsOperandInternal(Out, *OI, WriterCtx);
1610 if (OI+1 != CE->op_end())
1611 Out << ", ";
1614 if (CE->isCast()) {
1615 Out << " to ";
1616 WriterCtx.TypePrinter->print(CE->getType(), Out);
1619 if (CE->getOpcode() == Instruction::ShuffleVector)
1620 PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1622 Out << ')';
1623 return;
1626 Out << "<placeholder or erroneous Constant>";
1629 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1630 AsmWriterContext &WriterCtx) {
1631 Out << "!{";
1632 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1633 const Metadata *MD = Node->getOperand(mi);
1634 if (!MD)
1635 Out << "null";
1636 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1637 Value *V = MDV->getValue();
1638 WriterCtx.TypePrinter->print(V->getType(), Out);
1639 Out << ' ';
1640 WriteAsOperandInternal(Out, V, WriterCtx);
1641 } else {
1642 WriteAsOperandInternal(Out, MD, WriterCtx);
1643 WriterCtx.onWriteMetadataAsOperand(MD);
1645 if (mi + 1 != me)
1646 Out << ", ";
1649 Out << "}";
1652 namespace {
1654 struct FieldSeparator {
1655 bool Skip = true;
1656 const char *Sep;
1658 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1661 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1662 if (FS.Skip) {
1663 FS.Skip = false;
1664 return OS;
1666 return OS << FS.Sep;
1669 struct MDFieldPrinter {
1670 raw_ostream &Out;
1671 FieldSeparator FS;
1672 AsmWriterContext &WriterCtx;
1674 explicit MDFieldPrinter(raw_ostream &Out)
1675 : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
1676 MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1677 : Out(Out), WriterCtx(Ctx) {}
1679 void printTag(const DINode *N);
1680 void printMacinfoType(const DIMacroNode *N);
1681 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1682 void printString(StringRef Name, StringRef Value,
1683 bool ShouldSkipEmpty = true);
1684 void printMetadata(StringRef Name, const Metadata *MD,
1685 bool ShouldSkipNull = true);
1686 template <class IntTy>
1687 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1688 void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1689 bool ShouldSkipZero);
1690 void printBool(StringRef Name, bool Value,
1691 std::optional<bool> Default = std::nullopt);
1692 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1693 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1694 template <class IntTy, class Stringifier>
1695 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1696 bool ShouldSkipZero = true);
1697 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1698 void printNameTableKind(StringRef Name,
1699 DICompileUnit::DebugNameTableKind NTK);
1702 } // end anonymous namespace
1704 void MDFieldPrinter::printTag(const DINode *N) {
1705 Out << FS << "tag: ";
1706 auto Tag = dwarf::TagString(N->getTag());
1707 if (!Tag.empty())
1708 Out << Tag;
1709 else
1710 Out << N->getTag();
1713 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1714 Out << FS << "type: ";
1715 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1716 if (!Type.empty())
1717 Out << Type;
1718 else
1719 Out << N->getMacinfoType();
1722 void MDFieldPrinter::printChecksum(
1723 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1724 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1725 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1728 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1729 bool ShouldSkipEmpty) {
1730 if (ShouldSkipEmpty && Value.empty())
1731 return;
1733 Out << FS << Name << ": \"";
1734 printEscapedString(Value, Out);
1735 Out << "\"";
1738 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1739 AsmWriterContext &WriterCtx) {
1740 if (!MD) {
1741 Out << "null";
1742 return;
1744 WriteAsOperandInternal(Out, MD, WriterCtx);
1745 WriterCtx.onWriteMetadataAsOperand(MD);
1748 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1749 bool ShouldSkipNull) {
1750 if (ShouldSkipNull && !MD)
1751 return;
1753 Out << FS << Name << ": ";
1754 writeMetadataAsOperand(Out, MD, WriterCtx);
1757 template <class IntTy>
1758 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1759 if (ShouldSkipZero && !Int)
1760 return;
1762 Out << FS << Name << ": " << Int;
1765 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1766 bool IsUnsigned, bool ShouldSkipZero) {
1767 if (ShouldSkipZero && Int.isZero())
1768 return;
1770 Out << FS << Name << ": ";
1771 Int.print(Out, !IsUnsigned);
1774 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1775 std::optional<bool> Default) {
1776 if (Default && Value == *Default)
1777 return;
1778 Out << FS << Name << ": " << (Value ? "true" : "false");
1781 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1782 if (!Flags)
1783 return;
1785 Out << FS << Name << ": ";
1787 SmallVector<DINode::DIFlags, 8> SplitFlags;
1788 auto Extra = DINode::splitFlags(Flags, SplitFlags);
1790 FieldSeparator FlagsFS(" | ");
1791 for (auto F : SplitFlags) {
1792 auto StringF = DINode::getFlagString(F);
1793 assert(!StringF.empty() && "Expected valid flag");
1794 Out << FlagsFS << StringF;
1796 if (Extra || SplitFlags.empty())
1797 Out << FlagsFS << Extra;
1800 void MDFieldPrinter::printDISPFlags(StringRef Name,
1801 DISubprogram::DISPFlags Flags) {
1802 // Always print this field, because no flags in the IR at all will be
1803 // interpreted as old-style isDefinition: true.
1804 Out << FS << Name << ": ";
1806 if (!Flags) {
1807 Out << 0;
1808 return;
1811 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1812 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1814 FieldSeparator FlagsFS(" | ");
1815 for (auto F : SplitFlags) {
1816 auto StringF = DISubprogram::getFlagString(F);
1817 assert(!StringF.empty() && "Expected valid flag");
1818 Out << FlagsFS << StringF;
1820 if (Extra || SplitFlags.empty())
1821 Out << FlagsFS << Extra;
1824 void MDFieldPrinter::printEmissionKind(StringRef Name,
1825 DICompileUnit::DebugEmissionKind EK) {
1826 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1829 void MDFieldPrinter::printNameTableKind(StringRef Name,
1830 DICompileUnit::DebugNameTableKind NTK) {
1831 if (NTK == DICompileUnit::DebugNameTableKind::Default)
1832 return;
1833 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1836 template <class IntTy, class Stringifier>
1837 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1838 Stringifier toString, bool ShouldSkipZero) {
1839 if (!Value)
1840 return;
1842 Out << FS << Name << ": ";
1843 auto S = toString(Value);
1844 if (!S.empty())
1845 Out << S;
1846 else
1847 Out << Value;
1850 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1851 AsmWriterContext &WriterCtx) {
1852 Out << "!GenericDINode(";
1853 MDFieldPrinter Printer(Out, WriterCtx);
1854 Printer.printTag(N);
1855 Printer.printString("header", N->getHeader());
1856 if (N->getNumDwarfOperands()) {
1857 Out << Printer.FS << "operands: {";
1858 FieldSeparator IFS;
1859 for (auto &I : N->dwarf_operands()) {
1860 Out << IFS;
1861 writeMetadataAsOperand(Out, I, WriterCtx);
1863 Out << "}";
1865 Out << ")";
1868 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1869 AsmWriterContext &WriterCtx) {
1870 Out << "!DILocation(";
1871 MDFieldPrinter Printer(Out, WriterCtx);
1872 // Always output the line, since 0 is a relevant and important value for it.
1873 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1874 Printer.printInt("column", DL->getColumn());
1875 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1876 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1877 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1878 /* Default */ false);
1879 Out << ")";
1882 static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
1883 AsmWriterContext &WriterCtx) {
1884 Out << "!DIAssignID()";
1885 MDFieldPrinter Printer(Out, WriterCtx);
1888 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1889 AsmWriterContext &WriterCtx) {
1890 Out << "!DISubrange(";
1891 MDFieldPrinter Printer(Out, WriterCtx);
1893 auto *Count = N->getRawCountNode();
1894 if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
1895 auto *CV = cast<ConstantInt>(CE->getValue());
1896 Printer.printInt("count", CV->getSExtValue(),
1897 /* ShouldSkipZero */ false);
1898 } else
1899 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1901 // A lowerBound of constant 0 should not be skipped, since it is different
1902 // from an unspecified lower bound (= nullptr).
1903 auto *LBound = N->getRawLowerBound();
1904 if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
1905 auto *LV = cast<ConstantInt>(LE->getValue());
1906 Printer.printInt("lowerBound", LV->getSExtValue(),
1907 /* ShouldSkipZero */ false);
1908 } else
1909 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1911 auto *UBound = N->getRawUpperBound();
1912 if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
1913 auto *UV = cast<ConstantInt>(UE->getValue());
1914 Printer.printInt("upperBound", UV->getSExtValue(),
1915 /* ShouldSkipZero */ false);
1916 } else
1917 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1919 auto *Stride = N->getRawStride();
1920 if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
1921 auto *SV = cast<ConstantInt>(SE->getValue());
1922 Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
1923 } else
1924 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1926 Out << ")";
1929 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1930 AsmWriterContext &WriterCtx) {
1931 Out << "!DIGenericSubrange(";
1932 MDFieldPrinter Printer(Out, WriterCtx);
1934 auto IsConstant = [&](Metadata *Bound) -> bool {
1935 if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1936 return BE->isConstant() &&
1937 DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1938 *BE->isConstant();
1940 return false;
1943 auto GetConstant = [&](Metadata *Bound) -> int64_t {
1944 assert(IsConstant(Bound) && "Expected constant");
1945 auto *BE = dyn_cast_or_null<DIExpression>(Bound);
1946 return static_cast<int64_t>(BE->getElement(1));
1949 auto *Count = N->getRawCountNode();
1950 if (IsConstant(Count))
1951 Printer.printInt("count", GetConstant(Count),
1952 /* ShouldSkipZero */ false);
1953 else
1954 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1956 auto *LBound = N->getRawLowerBound();
1957 if (IsConstant(LBound))
1958 Printer.printInt("lowerBound", GetConstant(LBound),
1959 /* ShouldSkipZero */ false);
1960 else
1961 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1963 auto *UBound = N->getRawUpperBound();
1964 if (IsConstant(UBound))
1965 Printer.printInt("upperBound", GetConstant(UBound),
1966 /* ShouldSkipZero */ false);
1967 else
1968 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1970 auto *Stride = N->getRawStride();
1971 if (IsConstant(Stride))
1972 Printer.printInt("stride", GetConstant(Stride),
1973 /* ShouldSkipZero */ false);
1974 else
1975 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1977 Out << ")";
1980 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1981 AsmWriterContext &) {
1982 Out << "!DIEnumerator(";
1983 MDFieldPrinter Printer(Out);
1984 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1985 Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
1986 /*ShouldSkipZero=*/false);
1987 if (N->isUnsigned())
1988 Printer.printBool("isUnsigned", true);
1989 Out << ")";
1992 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1993 AsmWriterContext &) {
1994 Out << "!DIBasicType(";
1995 MDFieldPrinter Printer(Out);
1996 if (N->getTag() != dwarf::DW_TAG_base_type)
1997 Printer.printTag(N);
1998 Printer.printString("name", N->getName());
1999 Printer.printInt("size", N->getSizeInBits());
2000 Printer.printInt("align", N->getAlignInBits());
2001 Printer.printDwarfEnum("encoding", N->getEncoding(),
2002 dwarf::AttributeEncodingString);
2003 Printer.printDIFlags("flags", N->getFlags());
2004 Out << ")";
2007 static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2008 AsmWriterContext &WriterCtx) {
2009 Out << "!DIStringType(";
2010 MDFieldPrinter Printer(Out, WriterCtx);
2011 if (N->getTag() != dwarf::DW_TAG_string_type)
2012 Printer.printTag(N);
2013 Printer.printString("name", N->getName());
2014 Printer.printMetadata("stringLength", N->getRawStringLength());
2015 Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2016 Printer.printMetadata("stringLocationExpression",
2017 N->getRawStringLocationExp());
2018 Printer.printInt("size", N->getSizeInBits());
2019 Printer.printInt("align", N->getAlignInBits());
2020 Printer.printDwarfEnum("encoding", N->getEncoding(),
2021 dwarf::AttributeEncodingString);
2022 Out << ")";
2025 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2026 AsmWriterContext &WriterCtx) {
2027 Out << "!DIDerivedType(";
2028 MDFieldPrinter Printer(Out, WriterCtx);
2029 Printer.printTag(N);
2030 Printer.printString("name", N->getName());
2031 Printer.printMetadata("scope", N->getRawScope());
2032 Printer.printMetadata("file", N->getRawFile());
2033 Printer.printInt("line", N->getLine());
2034 Printer.printMetadata("baseType", N->getRawBaseType(),
2035 /* ShouldSkipNull */ false);
2036 Printer.printInt("size", N->getSizeInBits());
2037 Printer.printInt("align", N->getAlignInBits());
2038 Printer.printInt("offset", N->getOffsetInBits());
2039 Printer.printDIFlags("flags", N->getFlags());
2040 Printer.printMetadata("extraData", N->getRawExtraData());
2041 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2042 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2043 /* ShouldSkipZero */ false);
2044 Printer.printMetadata("annotations", N->getRawAnnotations());
2045 Out << ")";
2048 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2049 AsmWriterContext &WriterCtx) {
2050 Out << "!DICompositeType(";
2051 MDFieldPrinter Printer(Out, WriterCtx);
2052 Printer.printTag(N);
2053 Printer.printString("name", N->getName());
2054 Printer.printMetadata("scope", N->getRawScope());
2055 Printer.printMetadata("file", N->getRawFile());
2056 Printer.printInt("line", N->getLine());
2057 Printer.printMetadata("baseType", N->getRawBaseType());
2058 Printer.printInt("size", N->getSizeInBits());
2059 Printer.printInt("align", N->getAlignInBits());
2060 Printer.printInt("offset", N->getOffsetInBits());
2061 Printer.printDIFlags("flags", N->getFlags());
2062 Printer.printMetadata("elements", N->getRawElements());
2063 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2064 dwarf::LanguageString);
2065 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2066 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2067 Printer.printString("identifier", N->getIdentifier());
2068 Printer.printMetadata("discriminator", N->getRawDiscriminator());
2069 Printer.printMetadata("dataLocation", N->getRawDataLocation());
2070 Printer.printMetadata("associated", N->getRawAssociated());
2071 Printer.printMetadata("allocated", N->getRawAllocated());
2072 if (auto *RankConst = N->getRankConst())
2073 Printer.printInt("rank", RankConst->getSExtValue(),
2074 /* ShouldSkipZero */ false);
2075 else
2076 Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2077 Printer.printMetadata("annotations", N->getRawAnnotations());
2078 Out << ")";
2081 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2082 AsmWriterContext &WriterCtx) {
2083 Out << "!DISubroutineType(";
2084 MDFieldPrinter Printer(Out, WriterCtx);
2085 Printer.printDIFlags("flags", N->getFlags());
2086 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2087 Printer.printMetadata("types", N->getRawTypeArray(),
2088 /* ShouldSkipNull */ false);
2089 Out << ")";
2092 static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
2093 Out << "!DIFile(";
2094 MDFieldPrinter Printer(Out);
2095 Printer.printString("filename", N->getFilename(),
2096 /* ShouldSkipEmpty */ false);
2097 Printer.printString("directory", N->getDirectory(),
2098 /* ShouldSkipEmpty */ false);
2099 // Print all values for checksum together, or not at all.
2100 if (N->getChecksum())
2101 Printer.printChecksum(*N->getChecksum());
2102 Printer.printString("source", N->getSource().value_or(StringRef()),
2103 /* ShouldSkipEmpty */ true);
2104 Out << ")";
2107 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2108 AsmWriterContext &WriterCtx) {
2109 Out << "!DICompileUnit(";
2110 MDFieldPrinter Printer(Out, WriterCtx);
2111 Printer.printDwarfEnum("language", N->getSourceLanguage(),
2112 dwarf::LanguageString, /* ShouldSkipZero */ false);
2113 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2114 Printer.printString("producer", N->getProducer());
2115 Printer.printBool("isOptimized", N->isOptimized());
2116 Printer.printString("flags", N->getFlags());
2117 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2118 /* ShouldSkipZero */ false);
2119 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2120 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2121 Printer.printMetadata("enums", N->getRawEnumTypes());
2122 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2123 Printer.printMetadata("globals", N->getRawGlobalVariables());
2124 Printer.printMetadata("imports", N->getRawImportedEntities());
2125 Printer.printMetadata("macros", N->getRawMacros());
2126 Printer.printInt("dwoId", N->getDWOId());
2127 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2128 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2129 false);
2130 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2131 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2132 Printer.printString("sysroot", N->getSysRoot());
2133 Printer.printString("sdk", N->getSDK());
2134 Out << ")";
2137 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2138 AsmWriterContext &WriterCtx) {
2139 Out << "!DISubprogram(";
2140 MDFieldPrinter Printer(Out, WriterCtx);
2141 Printer.printString("name", N->getName());
2142 Printer.printString("linkageName", N->getLinkageName());
2143 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2144 Printer.printMetadata("file", N->getRawFile());
2145 Printer.printInt("line", N->getLine());
2146 Printer.printMetadata("type", N->getRawType());
2147 Printer.printInt("scopeLine", N->getScopeLine());
2148 Printer.printMetadata("containingType", N->getRawContainingType());
2149 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2150 N->getVirtualIndex() != 0)
2151 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2152 Printer.printInt("thisAdjustment", N->getThisAdjustment());
2153 Printer.printDIFlags("flags", N->getFlags());
2154 Printer.printDISPFlags("spFlags", N->getSPFlags());
2155 Printer.printMetadata("unit", N->getRawUnit());
2156 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2157 Printer.printMetadata("declaration", N->getRawDeclaration());
2158 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2159 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2160 Printer.printMetadata("annotations", N->getRawAnnotations());
2161 Printer.printString("targetFuncName", N->getTargetFuncName());
2162 Out << ")";
2165 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2166 AsmWriterContext &WriterCtx) {
2167 Out << "!DILexicalBlock(";
2168 MDFieldPrinter Printer(Out, WriterCtx);
2169 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2170 Printer.printMetadata("file", N->getRawFile());
2171 Printer.printInt("line", N->getLine());
2172 Printer.printInt("column", N->getColumn());
2173 Out << ")";
2176 static void writeDILexicalBlockFile(raw_ostream &Out,
2177 const DILexicalBlockFile *N,
2178 AsmWriterContext &WriterCtx) {
2179 Out << "!DILexicalBlockFile(";
2180 MDFieldPrinter Printer(Out, WriterCtx);
2181 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2182 Printer.printMetadata("file", N->getRawFile());
2183 Printer.printInt("discriminator", N->getDiscriminator(),
2184 /* ShouldSkipZero */ false);
2185 Out << ")";
2188 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2189 AsmWriterContext &WriterCtx) {
2190 Out << "!DINamespace(";
2191 MDFieldPrinter Printer(Out, WriterCtx);
2192 Printer.printString("name", N->getName());
2193 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2194 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2195 Out << ")";
2198 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2199 AsmWriterContext &WriterCtx) {
2200 Out << "!DICommonBlock(";
2201 MDFieldPrinter Printer(Out, WriterCtx);
2202 Printer.printMetadata("scope", N->getRawScope(), false);
2203 Printer.printMetadata("declaration", N->getRawDecl(), false);
2204 Printer.printString("name", N->getName());
2205 Printer.printMetadata("file", N->getRawFile());
2206 Printer.printInt("line", N->getLineNo());
2207 Out << ")";
2210 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2211 AsmWriterContext &WriterCtx) {
2212 Out << "!DIMacro(";
2213 MDFieldPrinter Printer(Out, WriterCtx);
2214 Printer.printMacinfoType(N);
2215 Printer.printInt("line", N->getLine());
2216 Printer.printString("name", N->getName());
2217 Printer.printString("value", N->getValue());
2218 Out << ")";
2221 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2222 AsmWriterContext &WriterCtx) {
2223 Out << "!DIMacroFile(";
2224 MDFieldPrinter Printer(Out, WriterCtx);
2225 Printer.printInt("line", N->getLine());
2226 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2227 Printer.printMetadata("nodes", N->getRawElements());
2228 Out << ")";
2231 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2232 AsmWriterContext &WriterCtx) {
2233 Out << "!DIModule(";
2234 MDFieldPrinter Printer(Out, WriterCtx);
2235 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2236 Printer.printString("name", N->getName());
2237 Printer.printString("configMacros", N->getConfigurationMacros());
2238 Printer.printString("includePath", N->getIncludePath());
2239 Printer.printString("apinotes", N->getAPINotesFile());
2240 Printer.printMetadata("file", N->getRawFile());
2241 Printer.printInt("line", N->getLineNo());
2242 Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
2243 Out << ")";
2246 static void writeDITemplateTypeParameter(raw_ostream &Out,
2247 const DITemplateTypeParameter *N,
2248 AsmWriterContext &WriterCtx) {
2249 Out << "!DITemplateTypeParameter(";
2250 MDFieldPrinter Printer(Out, WriterCtx);
2251 Printer.printString("name", N->getName());
2252 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2253 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2254 Out << ")";
2257 static void writeDITemplateValueParameter(raw_ostream &Out,
2258 const DITemplateValueParameter *N,
2259 AsmWriterContext &WriterCtx) {
2260 Out << "!DITemplateValueParameter(";
2261 MDFieldPrinter Printer(Out, WriterCtx);
2262 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2263 Printer.printTag(N);
2264 Printer.printString("name", N->getName());
2265 Printer.printMetadata("type", N->getRawType());
2266 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2267 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2268 Out << ")";
2271 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2272 AsmWriterContext &WriterCtx) {
2273 Out << "!DIGlobalVariable(";
2274 MDFieldPrinter Printer(Out, WriterCtx);
2275 Printer.printString("name", N->getName());
2276 Printer.printString("linkageName", N->getLinkageName());
2277 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2278 Printer.printMetadata("file", N->getRawFile());
2279 Printer.printInt("line", N->getLine());
2280 Printer.printMetadata("type", N->getRawType());
2281 Printer.printBool("isLocal", N->isLocalToUnit());
2282 Printer.printBool("isDefinition", N->isDefinition());
2283 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2284 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2285 Printer.printInt("align", N->getAlignInBits());
2286 Printer.printMetadata("annotations", N->getRawAnnotations());
2287 Out << ")";
2290 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2291 AsmWriterContext &WriterCtx) {
2292 Out << "!DILocalVariable(";
2293 MDFieldPrinter Printer(Out, WriterCtx);
2294 Printer.printString("name", N->getName());
2295 Printer.printInt("arg", N->getArg());
2296 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2297 Printer.printMetadata("file", N->getRawFile());
2298 Printer.printInt("line", N->getLine());
2299 Printer.printMetadata("type", N->getRawType());
2300 Printer.printDIFlags("flags", N->getFlags());
2301 Printer.printInt("align", N->getAlignInBits());
2302 Printer.printMetadata("annotations", N->getRawAnnotations());
2303 Out << ")";
2306 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2307 AsmWriterContext &WriterCtx) {
2308 Out << "!DILabel(";
2309 MDFieldPrinter Printer(Out, WriterCtx);
2310 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2311 Printer.printString("name", N->getName());
2312 Printer.printMetadata("file", N->getRawFile());
2313 Printer.printInt("line", N->getLine());
2314 Out << ")";
2317 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2318 AsmWriterContext &WriterCtx) {
2319 Out << "!DIExpression(";
2320 FieldSeparator FS;
2321 if (N->isValid()) {
2322 for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2323 auto OpStr = dwarf::OperationEncodingString(Op.getOp());
2324 assert(!OpStr.empty() && "Expected valid opcode");
2326 Out << FS << OpStr;
2327 if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2328 Out << FS << Op.getArg(0);
2329 Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
2330 } else {
2331 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2332 Out << FS << Op.getArg(A);
2335 } else {
2336 for (const auto &I : N->getElements())
2337 Out << FS << I;
2339 Out << ")";
2342 static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2343 AsmWriterContext &WriterCtx,
2344 bool FromValue = false) {
2345 assert(FromValue &&
2346 "Unexpected DIArgList metadata outside of value argument");
2347 Out << "!DIArgList(";
2348 FieldSeparator FS;
2349 MDFieldPrinter Printer(Out, WriterCtx);
2350 for (Metadata *Arg : N->getArgs()) {
2351 Out << FS;
2352 WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2354 Out << ")";
2357 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2358 const DIGlobalVariableExpression *N,
2359 AsmWriterContext &WriterCtx) {
2360 Out << "!DIGlobalVariableExpression(";
2361 MDFieldPrinter Printer(Out, WriterCtx);
2362 Printer.printMetadata("var", N->getVariable());
2363 Printer.printMetadata("expr", N->getExpression());
2364 Out << ")";
2367 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2368 AsmWriterContext &WriterCtx) {
2369 Out << "!DIObjCProperty(";
2370 MDFieldPrinter Printer(Out, WriterCtx);
2371 Printer.printString("name", N->getName());
2372 Printer.printMetadata("file", N->getRawFile());
2373 Printer.printInt("line", N->getLine());
2374 Printer.printString("setter", N->getSetterName());
2375 Printer.printString("getter", N->getGetterName());
2376 Printer.printInt("attributes", N->getAttributes());
2377 Printer.printMetadata("type", N->getRawType());
2378 Out << ")";
2381 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2382 AsmWriterContext &WriterCtx) {
2383 Out << "!DIImportedEntity(";
2384 MDFieldPrinter Printer(Out, WriterCtx);
2385 Printer.printTag(N);
2386 Printer.printString("name", N->getName());
2387 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2388 Printer.printMetadata("entity", N->getRawEntity());
2389 Printer.printMetadata("file", N->getRawFile());
2390 Printer.printInt("line", N->getLine());
2391 Printer.printMetadata("elements", N->getRawElements());
2392 Out << ")";
2395 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2396 AsmWriterContext &Ctx) {
2397 if (Node->isDistinct())
2398 Out << "distinct ";
2399 else if (Node->isTemporary())
2400 Out << "<temporary!> "; // Handle broken code.
2402 switch (Node->getMetadataID()) {
2403 default:
2404 llvm_unreachable("Expected uniquable MDNode");
2405 #define HANDLE_MDNODE_LEAF(CLASS) \
2406 case Metadata::CLASS##Kind: \
2407 write##CLASS(Out, cast<CLASS>(Node), Ctx); \
2408 break;
2409 #include "llvm/IR/Metadata.def"
2413 // Full implementation of printing a Value as an operand with support for
2414 // TypePrinting, etc.
2415 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2416 AsmWriterContext &WriterCtx) {
2417 if (V->hasName()) {
2418 PrintLLVMName(Out, V);
2419 return;
2422 const Constant *CV = dyn_cast<Constant>(V);
2423 if (CV && !isa<GlobalValue>(CV)) {
2424 assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2425 WriteConstantInternal(Out, CV, WriterCtx);
2426 return;
2429 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2430 Out << "asm ";
2431 if (IA->hasSideEffects())
2432 Out << "sideeffect ";
2433 if (IA->isAlignStack())
2434 Out << "alignstack ";
2435 // We don't emit the AD_ATT dialect as it's the assumed default.
2436 if (IA->getDialect() == InlineAsm::AD_Intel)
2437 Out << "inteldialect ";
2438 if (IA->canThrow())
2439 Out << "unwind ";
2440 Out << '"';
2441 printEscapedString(IA->getAsmString(), Out);
2442 Out << "\", \"";
2443 printEscapedString(IA->getConstraintString(), Out);
2444 Out << '"';
2445 return;
2448 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2449 WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
2450 /* FromValue */ true);
2451 return;
2454 char Prefix = '%';
2455 int Slot;
2456 auto *Machine = WriterCtx.Machine;
2457 // If we have a SlotTracker, use it.
2458 if (Machine) {
2459 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2460 Slot = Machine->getGlobalSlot(GV);
2461 Prefix = '@';
2462 } else {
2463 Slot = Machine->getLocalSlot(V);
2465 // If the local value didn't succeed, then we may be referring to a value
2466 // from a different function. Translate it, as this can happen when using
2467 // address of blocks.
2468 if (Slot == -1)
2469 if ((Machine = createSlotTracker(V))) {
2470 Slot = Machine->getLocalSlot(V);
2471 delete Machine;
2474 } else if ((Machine = createSlotTracker(V))) {
2475 // Otherwise, create one to get the # and then destroy it.
2476 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2477 Slot = Machine->getGlobalSlot(GV);
2478 Prefix = '@';
2479 } else {
2480 Slot = Machine->getLocalSlot(V);
2482 delete Machine;
2483 Machine = nullptr;
2484 } else {
2485 Slot = -1;
2488 if (Slot != -1)
2489 Out << Prefix << Slot;
2490 else
2491 Out << "<badref>";
2494 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2495 AsmWriterContext &WriterCtx,
2496 bool FromValue) {
2497 // Write DIExpressions and DIArgLists inline when used as a value. Improves
2498 // readability of debug info intrinsics.
2499 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2500 writeDIExpression(Out, Expr, WriterCtx);
2501 return;
2503 if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2504 writeDIArgList(Out, ArgList, WriterCtx, FromValue);
2505 return;
2508 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2509 std::unique_ptr<SlotTracker> MachineStorage;
2510 SaveAndRestore SARMachine(WriterCtx.Machine);
2511 if (!WriterCtx.Machine) {
2512 MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2513 WriterCtx.Machine = MachineStorage.get();
2515 int Slot = WriterCtx.Machine->getMetadataSlot(N);
2516 if (Slot == -1) {
2517 if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2518 writeDILocation(Out, Loc, WriterCtx);
2519 return;
2521 // Give the pointer value instead of "badref", since this comes up all
2522 // the time when debugging.
2523 Out << "<" << N << ">";
2524 } else
2525 Out << '!' << Slot;
2526 return;
2529 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2530 Out << "!\"";
2531 printEscapedString(MDS->getString(), Out);
2532 Out << '"';
2533 return;
2536 auto *V = cast<ValueAsMetadata>(MD);
2537 assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
2538 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2539 "Unexpected function-local metadata outside of value argument");
2541 WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
2542 Out << ' ';
2543 WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
2546 namespace {
2548 class AssemblyWriter {
2549 formatted_raw_ostream &Out;
2550 const Module *TheModule = nullptr;
2551 const ModuleSummaryIndex *TheIndex = nullptr;
2552 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2553 SlotTracker &Machine;
2554 TypePrinting TypePrinter;
2555 AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2556 SetVector<const Comdat *> Comdats;
2557 bool IsForDebug;
2558 bool ShouldPreserveUseListOrder;
2559 UseListOrderMap UseListOrders;
2560 SmallVector<StringRef, 8> MDNames;
2561 /// Synchronization scope names registered with LLVMContext.
2562 SmallVector<StringRef, 8> SSNs;
2563 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2565 public:
2566 /// Construct an AssemblyWriter with an external SlotTracker
2567 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2568 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2569 bool ShouldPreserveUseListOrder = false);
2571 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2572 const ModuleSummaryIndex *Index, bool IsForDebug);
2574 AsmWriterContext getContext() {
2575 return AsmWriterContext(&TypePrinter, &Machine, TheModule);
2578 void printMDNodeBody(const MDNode *MD);
2579 void printNamedMDNode(const NamedMDNode *NMD);
2581 void printModule(const Module *M);
2583 void writeOperand(const Value *Op, bool PrintType);
2584 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2585 void writeOperandBundles(const CallBase *Call);
2586 void writeSyncScope(const LLVMContext &Context,
2587 SyncScope::ID SSID);
2588 void writeAtomic(const LLVMContext &Context,
2589 AtomicOrdering Ordering,
2590 SyncScope::ID SSID);
2591 void writeAtomicCmpXchg(const LLVMContext &Context,
2592 AtomicOrdering SuccessOrdering,
2593 AtomicOrdering FailureOrdering,
2594 SyncScope::ID SSID);
2596 void writeAllMDNodes();
2597 void writeMDNode(unsigned Slot, const MDNode *Node);
2598 void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2599 void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
2600 void writeAllAttributeGroups();
2602 void printTypeIdentities();
2603 void printGlobal(const GlobalVariable *GV);
2604 void printAlias(const GlobalAlias *GA);
2605 void printIFunc(const GlobalIFunc *GI);
2606 void printComdat(const Comdat *C);
2607 void printFunction(const Function *F);
2608 void printArgument(const Argument *FA, AttributeSet Attrs);
2609 void printBasicBlock(const BasicBlock *BB);
2610 void printInstructionLine(const Instruction &I);
2611 void printInstruction(const Instruction &I);
2613 void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
2614 void printUseLists(const Function *F);
2616 void printModuleSummaryIndex();
2617 void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2618 void printSummary(const GlobalValueSummary &Summary);
2619 void printAliasSummary(const AliasSummary *AS);
2620 void printGlobalVarSummary(const GlobalVarSummary *GS);
2621 void printFunctionSummary(const FunctionSummary *FS);
2622 void printTypeIdSummary(const TypeIdSummary &TIS);
2623 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
2624 void printTypeTestResolution(const TypeTestResolution &TTRes);
2625 void printArgs(const std::vector<uint64_t> &Args);
2626 void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2627 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2628 void printVFuncId(const FunctionSummary::VFuncId VFId);
2629 void
2630 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
2631 const char *Tag);
2632 void
2633 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
2634 const char *Tag);
2636 private:
2637 /// Print out metadata attachments.
2638 void printMetadataAttachments(
2639 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2640 StringRef Separator);
2642 // printInfoComment - Print a little comment after the instruction indicating
2643 // which slot it occupies.
2644 void printInfoComment(const Value &V);
2646 // printGCRelocateComment - print comment after call to the gc.relocate
2647 // intrinsic indicating base and derived pointer names.
2648 void printGCRelocateComment(const GCRelocateInst &Relocate);
2651 } // end anonymous namespace
2653 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2654 const Module *M, AssemblyAnnotationWriter *AAW,
2655 bool IsForDebug, bool ShouldPreserveUseListOrder)
2656 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2657 IsForDebug(IsForDebug),
2658 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2659 if (!TheModule)
2660 return;
2661 for (const GlobalObject &GO : TheModule->global_objects())
2662 if (const Comdat *C = GO.getComdat())
2663 Comdats.insert(C);
2666 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2667 const ModuleSummaryIndex *Index, bool IsForDebug)
2668 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2669 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2671 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2672 if (!Operand) {
2673 Out << "<null operand!>";
2674 return;
2676 if (PrintType) {
2677 TypePrinter.print(Operand->getType(), Out);
2678 Out << ' ';
2680 auto WriterCtx = getContext();
2681 WriteAsOperandInternal(Out, Operand, WriterCtx);
2684 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2685 SyncScope::ID SSID) {
2686 switch (SSID) {
2687 case SyncScope::System: {
2688 break;
2690 default: {
2691 if (SSNs.empty())
2692 Context.getSyncScopeNames(SSNs);
2694 Out << " syncscope(\"";
2695 printEscapedString(SSNs[SSID], Out);
2696 Out << "\")";
2697 break;
2702 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2703 AtomicOrdering Ordering,
2704 SyncScope::ID SSID) {
2705 if (Ordering == AtomicOrdering::NotAtomic)
2706 return;
2708 writeSyncScope(Context, SSID);
2709 Out << " " << toIRString(Ordering);
2712 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2713 AtomicOrdering SuccessOrdering,
2714 AtomicOrdering FailureOrdering,
2715 SyncScope::ID SSID) {
2716 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2717 FailureOrdering != AtomicOrdering::NotAtomic);
2719 writeSyncScope(Context, SSID);
2720 Out << " " << toIRString(SuccessOrdering);
2721 Out << " " << toIRString(FailureOrdering);
2724 void AssemblyWriter::writeParamOperand(const Value *Operand,
2725 AttributeSet Attrs) {
2726 if (!Operand) {
2727 Out << "<null operand!>";
2728 return;
2731 // Print the type
2732 TypePrinter.print(Operand->getType(), Out);
2733 // Print parameter attributes list
2734 if (Attrs.hasAttributes()) {
2735 Out << ' ';
2736 writeAttributeSet(Attrs);
2738 Out << ' ';
2739 // Print the operand
2740 auto WriterCtx = getContext();
2741 WriteAsOperandInternal(Out, Operand, WriterCtx);
2744 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2745 if (!Call->hasOperandBundles())
2746 return;
2748 Out << " [ ";
2750 bool FirstBundle = true;
2751 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2752 OperandBundleUse BU = Call->getOperandBundleAt(i);
2754 if (!FirstBundle)
2755 Out << ", ";
2756 FirstBundle = false;
2758 Out << '"';
2759 printEscapedString(BU.getTagName(), Out);
2760 Out << '"';
2762 Out << '(';
2764 bool FirstInput = true;
2765 auto WriterCtx = getContext();
2766 for (const auto &Input : BU.Inputs) {
2767 if (!FirstInput)
2768 Out << ", ";
2769 FirstInput = false;
2771 if (Input == nullptr)
2772 Out << "<null operand bundle!>";
2773 else {
2774 TypePrinter.print(Input->getType(), Out);
2775 Out << " ";
2776 WriteAsOperandInternal(Out, Input, WriterCtx);
2780 Out << ')';
2783 Out << " ]";
2786 void AssemblyWriter::printModule(const Module *M) {
2787 Machine.initializeIfNeeded();
2789 if (ShouldPreserveUseListOrder)
2790 UseListOrders = predictUseListOrder(M);
2792 if (!M->getModuleIdentifier().empty() &&
2793 // Don't print the ID if it will start a new line (which would
2794 // require a comment char before it).
2795 M->getModuleIdentifier().find('\n') == std::string::npos)
2796 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2798 if (!M->getSourceFileName().empty()) {
2799 Out << "source_filename = \"";
2800 printEscapedString(M->getSourceFileName(), Out);
2801 Out << "\"\n";
2804 const std::string &DL = M->getDataLayoutStr();
2805 if (!DL.empty())
2806 Out << "target datalayout = \"" << DL << "\"\n";
2807 if (!M->getTargetTriple().empty())
2808 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2810 if (!M->getModuleInlineAsm().empty()) {
2811 Out << '\n';
2813 // Split the string into lines, to make it easier to read the .ll file.
2814 StringRef Asm = M->getModuleInlineAsm();
2815 do {
2816 StringRef Front;
2817 std::tie(Front, Asm) = Asm.split('\n');
2819 // We found a newline, print the portion of the asm string from the
2820 // last newline up to this newline.
2821 Out << "module asm \"";
2822 printEscapedString(Front, Out);
2823 Out << "\"\n";
2824 } while (!Asm.empty());
2827 printTypeIdentities();
2829 // Output all comdats.
2830 if (!Comdats.empty())
2831 Out << '\n';
2832 for (const Comdat *C : Comdats) {
2833 printComdat(C);
2834 if (C != Comdats.back())
2835 Out << '\n';
2838 // Output all globals.
2839 if (!M->global_empty()) Out << '\n';
2840 for (const GlobalVariable &GV : M->globals()) {
2841 printGlobal(&GV); Out << '\n';
2844 // Output all aliases.
2845 if (!M->alias_empty()) Out << "\n";
2846 for (const GlobalAlias &GA : M->aliases())
2847 printAlias(&GA);
2849 // Output all ifuncs.
2850 if (!M->ifunc_empty()) Out << "\n";
2851 for (const GlobalIFunc &GI : M->ifuncs())
2852 printIFunc(&GI);
2854 // Output all of the functions.
2855 for (const Function &F : *M) {
2856 Out << '\n';
2857 printFunction(&F);
2860 // Output global use-lists.
2861 printUseLists(nullptr);
2863 // Output all attribute groups.
2864 if (!Machine.as_empty()) {
2865 Out << '\n';
2866 writeAllAttributeGroups();
2869 // Output named metadata.
2870 if (!M->named_metadata_empty()) Out << '\n';
2872 for (const NamedMDNode &Node : M->named_metadata())
2873 printNamedMDNode(&Node);
2875 // Output metadata.
2876 if (!Machine.mdn_empty()) {
2877 Out << '\n';
2878 writeAllMDNodes();
2882 void AssemblyWriter::printModuleSummaryIndex() {
2883 assert(TheIndex);
2884 int NumSlots = Machine.initializeIndexIfNeeded();
2886 Out << "\n";
2888 // Print module path entries. To print in order, add paths to a vector
2889 // indexed by module slot.
2890 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2891 std::string RegularLTOModuleName =
2892 ModuleSummaryIndex::getRegularLTOModuleName();
2893 moduleVec.resize(TheIndex->modulePaths().size());
2894 for (auto &[ModPath, ModHash] : TheIndex->modulePaths())
2895 moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(
2896 // An empty module path is a special entry for a regular LTO module
2897 // created during the thin link.
2898 ModPath.empty() ? RegularLTOModuleName : std::string(ModPath), ModHash);
2900 unsigned i = 0;
2901 for (auto &ModPair : moduleVec) {
2902 Out << "^" << i++ << " = module: (";
2903 Out << "path: \"";
2904 printEscapedString(ModPair.first, Out);
2905 Out << "\", hash: (";
2906 FieldSeparator FS;
2907 for (auto Hash : ModPair.second)
2908 Out << FS << Hash;
2909 Out << "))\n";
2912 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2913 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2914 for (auto &GlobalList : *TheIndex) {
2915 auto GUID = GlobalList.first;
2916 for (auto &Summary : GlobalList.second.SummaryList)
2917 SummaryToGUIDMap[Summary.get()] = GUID;
2920 // Print the global value summary entries.
2921 for (auto &GlobalList : *TheIndex) {
2922 auto GUID = GlobalList.first;
2923 auto VI = TheIndex->getValueInfo(GlobalList);
2924 printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2927 // Print the TypeIdMap entries.
2928 for (const auto &TID : TheIndex->typeIds()) {
2929 Out << "^" << Machine.getTypeIdSlot(TID.second.first)
2930 << " = typeid: (name: \"" << TID.second.first << "\"";
2931 printTypeIdSummary(TID.second.second);
2932 Out << ") ; guid = " << TID.first << "\n";
2935 // Print the TypeIdCompatibleVtableMap entries.
2936 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2937 auto GUID = GlobalValue::getGUID(TId.first);
2938 Out << "^" << Machine.getGUIDSlot(GUID)
2939 << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
2940 printTypeIdCompatibleVtableSummary(TId.second);
2941 Out << ") ; guid = " << GUID << "\n";
2944 // Don't emit flags when it's not really needed (value is zero by default).
2945 if (TheIndex->getFlags()) {
2946 Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
2947 ++NumSlots;
2950 Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
2951 << "\n";
2954 static const char *
2955 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2956 switch (K) {
2957 case WholeProgramDevirtResolution::Indir:
2958 return "indir";
2959 case WholeProgramDevirtResolution::SingleImpl:
2960 return "singleImpl";
2961 case WholeProgramDevirtResolution::BranchFunnel:
2962 return "branchFunnel";
2964 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2967 static const char *getWholeProgDevirtResByArgKindName(
2968 WholeProgramDevirtResolution::ByArg::Kind K) {
2969 switch (K) {
2970 case WholeProgramDevirtResolution::ByArg::Indir:
2971 return "indir";
2972 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2973 return "uniformRetVal";
2974 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2975 return "uniqueRetVal";
2976 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2977 return "virtualConstProp";
2979 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2982 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2983 switch (K) {
2984 case TypeTestResolution::Unknown:
2985 return "unknown";
2986 case TypeTestResolution::Unsat:
2987 return "unsat";
2988 case TypeTestResolution::ByteArray:
2989 return "byteArray";
2990 case TypeTestResolution::Inline:
2991 return "inline";
2992 case TypeTestResolution::Single:
2993 return "single";
2994 case TypeTestResolution::AllOnes:
2995 return "allOnes";
2997 llvm_unreachable("invalid TypeTestResolution kind");
3000 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
3001 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
3002 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
3004 // The following fields are only used if the target does not support the use
3005 // of absolute symbols to store constants. Print only if non-zero.
3006 if (TTRes.AlignLog2)
3007 Out << ", alignLog2: " << TTRes.AlignLog2;
3008 if (TTRes.SizeM1)
3009 Out << ", sizeM1: " << TTRes.SizeM1;
3010 if (TTRes.BitMask)
3011 // BitMask is uint8_t which causes it to print the corresponding char.
3012 Out << ", bitMask: " << (unsigned)TTRes.BitMask;
3013 if (TTRes.InlineBits)
3014 Out << ", inlineBits: " << TTRes.InlineBits;
3016 Out << ")";
3019 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
3020 Out << ", summary: (";
3021 printTypeTestResolution(TIS.TTRes);
3022 if (!TIS.WPDRes.empty()) {
3023 Out << ", wpdResolutions: (";
3024 FieldSeparator FS;
3025 for (auto &WPDRes : TIS.WPDRes) {
3026 Out << FS;
3027 Out << "(offset: " << WPDRes.first << ", ";
3028 printWPDRes(WPDRes.second);
3029 Out << ")";
3031 Out << ")";
3033 Out << ")";
3036 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3037 const TypeIdCompatibleVtableInfo &TI) {
3038 Out << ", summary: (";
3039 FieldSeparator FS;
3040 for (auto &P : TI) {
3041 Out << FS;
3042 Out << "(offset: " << P.AddressPointOffset << ", ";
3043 Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
3044 Out << ")";
3046 Out << ")";
3049 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
3050 Out << "args: (";
3051 FieldSeparator FS;
3052 for (auto arg : Args) {
3053 Out << FS;
3054 Out << arg;
3056 Out << ")";
3059 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
3060 Out << "wpdRes: (kind: ";
3061 Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
3063 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
3064 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
3066 if (!WPDRes.ResByArg.empty()) {
3067 Out << ", resByArg: (";
3068 FieldSeparator FS;
3069 for (auto &ResByArg : WPDRes.ResByArg) {
3070 Out << FS;
3071 printArgs(ResByArg.first);
3072 Out << ", byArg: (kind: ";
3073 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
3074 if (ResByArg.second.TheKind ==
3075 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3076 ResByArg.second.TheKind ==
3077 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3078 Out << ", info: " << ResByArg.second.Info;
3080 // The following fields are only used if the target does not support the
3081 // use of absolute symbols to store constants. Print only if non-zero.
3082 if (ResByArg.second.Byte || ResByArg.second.Bit)
3083 Out << ", byte: " << ResByArg.second.Byte
3084 << ", bit: " << ResByArg.second.Bit;
3086 Out << ")";
3088 Out << ")";
3090 Out << ")";
3093 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
3094 switch (SK) {
3095 case GlobalValueSummary::AliasKind:
3096 return "alias";
3097 case GlobalValueSummary::FunctionKind:
3098 return "function";
3099 case GlobalValueSummary::GlobalVarKind:
3100 return "variable";
3102 llvm_unreachable("invalid summary kind");
3105 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
3106 Out << ", aliasee: ";
3107 // The indexes emitted for distributed backends may not include the
3108 // aliasee summary (only if it is being imported directly). Handle
3109 // that case by just emitting "null" as the aliasee.
3110 if (AS->hasAliasee())
3111 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
3112 else
3113 Out << "null";
3116 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
3117 auto VTableFuncs = GS->vTableFuncs();
3118 Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3119 << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3120 << "constant: " << GS->VarFlags.Constant;
3121 if (!VTableFuncs.empty())
3122 Out << ", "
3123 << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3124 Out << ")";
3126 if (!VTableFuncs.empty()) {
3127 Out << ", vTableFuncs: (";
3128 FieldSeparator FS;
3129 for (auto &P : VTableFuncs) {
3130 Out << FS;
3131 Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
3132 << ", offset: " << P.VTableOffset;
3133 Out << ")";
3135 Out << ")";
3139 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
3140 switch (LT) {
3141 case GlobalValue::ExternalLinkage:
3142 return "external";
3143 case GlobalValue::PrivateLinkage:
3144 return "private";
3145 case GlobalValue::InternalLinkage:
3146 return "internal";
3147 case GlobalValue::LinkOnceAnyLinkage:
3148 return "linkonce";
3149 case GlobalValue::LinkOnceODRLinkage:
3150 return "linkonce_odr";
3151 case GlobalValue::WeakAnyLinkage:
3152 return "weak";
3153 case GlobalValue::WeakODRLinkage:
3154 return "weak_odr";
3155 case GlobalValue::CommonLinkage:
3156 return "common";
3157 case GlobalValue::AppendingLinkage:
3158 return "appending";
3159 case GlobalValue::ExternalWeakLinkage:
3160 return "extern_weak";
3161 case GlobalValue::AvailableExternallyLinkage:
3162 return "available_externally";
3164 llvm_unreachable("invalid linkage");
3167 // When printing the linkage types in IR where the ExternalLinkage is
3168 // not printed, and other linkage types are expected to be printed with
3169 // a space after the name.
3170 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
3171 if (LT == GlobalValue::ExternalLinkage)
3172 return "";
3173 return getLinkageName(LT) + " ";
3176 static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {
3177 switch (Vis) {
3178 case GlobalValue::DefaultVisibility:
3179 return "default";
3180 case GlobalValue::HiddenVisibility:
3181 return "hidden";
3182 case GlobalValue::ProtectedVisibility:
3183 return "protected";
3185 llvm_unreachable("invalid visibility");
3188 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
3189 Out << ", insts: " << FS->instCount();
3190 if (FS->fflags().anyFlagSet())
3191 Out << ", " << FS->fflags();
3193 if (!FS->calls().empty()) {
3194 Out << ", calls: (";
3195 FieldSeparator IFS;
3196 for (auto &Call : FS->calls()) {
3197 Out << IFS;
3198 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
3199 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
3200 Out << ", hotness: " << getHotnessName(Call.second.getHotness());
3201 else if (Call.second.RelBlockFreq)
3202 Out << ", relbf: " << Call.second.RelBlockFreq;
3203 Out << ")";
3205 Out << ")";
3208 if (const auto *TIdInfo = FS->getTypeIdInfo())
3209 printTypeIdInfo(*TIdInfo);
3211 // The AllocationType identifiers capture the profiled context behavior
3212 // reaching a specific static allocation site (possibly cloned).
3213 auto AllocTypeName = [](uint8_t Type) -> const char * {
3214 switch (Type) {
3215 case (uint8_t)AllocationType::None:
3216 return "none";
3217 case (uint8_t)AllocationType::NotCold:
3218 return "notcold";
3219 case (uint8_t)AllocationType::Cold:
3220 return "cold";
3221 case (uint8_t)AllocationType::Hot:
3222 return "hot";
3224 llvm_unreachable("Unexpected alloc type");
3227 if (!FS->allocs().empty()) {
3228 Out << ", allocs: (";
3229 FieldSeparator AFS;
3230 for (auto &AI : FS->allocs()) {
3231 Out << AFS;
3232 Out << "(versions: (";
3233 FieldSeparator VFS;
3234 for (auto V : AI.Versions) {
3235 Out << VFS;
3236 Out << AllocTypeName(V);
3238 Out << "), memProf: (";
3239 FieldSeparator MIBFS;
3240 for (auto &MIB : AI.MIBs) {
3241 Out << MIBFS;
3242 Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3243 Out << ", stackIds: (";
3244 FieldSeparator SIDFS;
3245 for (auto Id : MIB.StackIdIndices) {
3246 Out << SIDFS;
3247 Out << TheIndex->getStackIdAtIndex(Id);
3249 Out << "))";
3251 Out << "))";
3253 Out << ")";
3256 if (!FS->callsites().empty()) {
3257 Out << ", callsites: (";
3258 FieldSeparator SNFS;
3259 for (auto &CI : FS->callsites()) {
3260 Out << SNFS;
3261 if (CI.Callee)
3262 Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
3263 else
3264 Out << "(callee: null";
3265 Out << ", clones: (";
3266 FieldSeparator VFS;
3267 for (auto V : CI.Clones) {
3268 Out << VFS;
3269 Out << V;
3271 Out << "), stackIds: (";
3272 FieldSeparator SIDFS;
3273 for (auto Id : CI.StackIdIndices) {
3274 Out << SIDFS;
3275 Out << TheIndex->getStackIdAtIndex(Id);
3277 Out << "))";
3279 Out << ")";
3282 auto PrintRange = [&](const ConstantRange &Range) {
3283 Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3286 if (!FS->paramAccesses().empty()) {
3287 Out << ", params: (";
3288 FieldSeparator IFS;
3289 for (auto &PS : FS->paramAccesses()) {
3290 Out << IFS;
3291 Out << "(param: " << PS.ParamNo;
3292 Out << ", offset: ";
3293 PrintRange(PS.Use);
3294 if (!PS.Calls.empty()) {
3295 Out << ", calls: (";
3296 FieldSeparator IFS;
3297 for (auto &Call : PS.Calls) {
3298 Out << IFS;
3299 Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
3300 Out << ", param: " << Call.ParamNo;
3301 Out << ", offset: ";
3302 PrintRange(Call.Offsets);
3303 Out << ")";
3305 Out << ")";
3307 Out << ")";
3309 Out << ")";
3313 void AssemblyWriter::printTypeIdInfo(
3314 const FunctionSummary::TypeIdInfo &TIDInfo) {
3315 Out << ", typeIdInfo: (";
3316 FieldSeparator TIDFS;
3317 if (!TIDInfo.TypeTests.empty()) {
3318 Out << TIDFS;
3319 Out << "typeTests: (";
3320 FieldSeparator FS;
3321 for (auto &GUID : TIDInfo.TypeTests) {
3322 auto TidIter = TheIndex->typeIds().equal_range(GUID);
3323 if (TidIter.first == TidIter.second) {
3324 Out << FS;
3325 Out << GUID;
3326 continue;
3328 // Print all type id that correspond to this GUID.
3329 for (auto It = TidIter.first; It != TidIter.second; ++It) {
3330 Out << FS;
3331 auto Slot = Machine.getTypeIdSlot(It->second.first);
3332 assert(Slot != -1);
3333 Out << "^" << Slot;
3336 Out << ")";
3338 if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3339 Out << TIDFS;
3340 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3342 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3343 Out << TIDFS;
3344 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3346 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3347 Out << TIDFS;
3348 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3349 "typeTestAssumeConstVCalls");
3351 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3352 Out << TIDFS;
3353 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3354 "typeCheckedLoadConstVCalls");
3356 Out << ")";
3359 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3360 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3361 if (TidIter.first == TidIter.second) {
3362 Out << "vFuncId: (";
3363 Out << "guid: " << VFId.GUID;
3364 Out << ", offset: " << VFId.Offset;
3365 Out << ")";
3366 return;
3368 // Print all type id that correspond to this GUID.
3369 FieldSeparator FS;
3370 for (auto It = TidIter.first; It != TidIter.second; ++It) {
3371 Out << FS;
3372 Out << "vFuncId: (";
3373 auto Slot = Machine.getTypeIdSlot(It->second.first);
3374 assert(Slot != -1);
3375 Out << "^" << Slot;
3376 Out << ", offset: " << VFId.Offset;
3377 Out << ")";
3381 void AssemblyWriter::printNonConstVCalls(
3382 const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
3383 Out << Tag << ": (";
3384 FieldSeparator FS;
3385 for (auto &VFuncId : VCallList) {
3386 Out << FS;
3387 printVFuncId(VFuncId);
3389 Out << ")";
3392 void AssemblyWriter::printConstVCalls(
3393 const std::vector<FunctionSummary::ConstVCall> &VCallList,
3394 const char *Tag) {
3395 Out << Tag << ": (";
3396 FieldSeparator FS;
3397 for (auto &ConstVCall : VCallList) {
3398 Out << FS;
3399 Out << "(";
3400 printVFuncId(ConstVCall.VFunc);
3401 if (!ConstVCall.Args.empty()) {
3402 Out << ", ";
3403 printArgs(ConstVCall.Args);
3405 Out << ")";
3407 Out << ")";
3410 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3411 GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3412 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3413 Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3414 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3415 << ", flags: (";
3416 Out << "linkage: " << getLinkageName(LT);
3417 Out << ", visibility: "
3418 << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility);
3419 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3420 Out << ", live: " << GVFlags.Live;
3421 Out << ", dsoLocal: " << GVFlags.DSOLocal;
3422 Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3423 Out << ")";
3425 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3426 printAliasSummary(cast<AliasSummary>(&Summary));
3427 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3428 printFunctionSummary(cast<FunctionSummary>(&Summary));
3429 else
3430 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3432 auto RefList = Summary.refs();
3433 if (!RefList.empty()) {
3434 Out << ", refs: (";
3435 FieldSeparator FS;
3436 for (auto &Ref : RefList) {
3437 Out << FS;
3438 if (Ref.isReadOnly())
3439 Out << "readonly ";
3440 else if (Ref.isWriteOnly())
3441 Out << "writeonly ";
3442 Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3444 Out << ")";
3447 Out << ")";
3450 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3451 Out << "^" << Slot << " = gv: (";
3452 if (!VI.name().empty())
3453 Out << "name: \"" << VI.name() << "\"";
3454 else
3455 Out << "guid: " << VI.getGUID();
3456 if (!VI.getSummaryList().empty()) {
3457 Out << ", summaries: (";
3458 FieldSeparator FS;
3459 for (auto &Summary : VI.getSummaryList()) {
3460 Out << FS;
3461 printSummary(*Summary);
3463 Out << ")";
3465 Out << ")";
3466 if (!VI.name().empty())
3467 Out << " ; guid = " << VI.getGUID();
3468 Out << "\n";
3471 static void printMetadataIdentifier(StringRef Name,
3472 formatted_raw_ostream &Out) {
3473 if (Name.empty()) {
3474 Out << "<empty name> ";
3475 } else {
3476 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3477 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3478 Out << Name[0];
3479 else
3480 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3481 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3482 unsigned char C = Name[i];
3483 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3484 C == '.' || C == '_')
3485 Out << C;
3486 else
3487 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3492 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3493 Out << '!';
3494 printMetadataIdentifier(NMD->getName(), Out);
3495 Out << " = !{";
3496 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3497 if (i)
3498 Out << ", ";
3500 // Write DIExpressions inline.
3501 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3502 MDNode *Op = NMD->getOperand(i);
3503 assert(!isa<DIArgList>(Op) &&
3504 "DIArgLists should not appear in NamedMDNodes");
3505 if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3506 writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
3507 continue;
3510 int Slot = Machine.getMetadataSlot(Op);
3511 if (Slot == -1)
3512 Out << "<badref>";
3513 else
3514 Out << '!' << Slot;
3516 Out << "}\n";
3519 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3520 formatted_raw_ostream &Out) {
3521 switch (Vis) {
3522 case GlobalValue::DefaultVisibility: break;
3523 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3524 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3528 static void PrintDSOLocation(const GlobalValue &GV,
3529 formatted_raw_ostream &Out) {
3530 if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
3531 Out << "dso_local ";
3534 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3535 formatted_raw_ostream &Out) {
3536 switch (SCT) {
3537 case GlobalValue::DefaultStorageClass: break;
3538 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3539 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3543 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3544 formatted_raw_ostream &Out) {
3545 switch (TLM) {
3546 case GlobalVariable::NotThreadLocal:
3547 break;
3548 case GlobalVariable::GeneralDynamicTLSModel:
3549 Out << "thread_local ";
3550 break;
3551 case GlobalVariable::LocalDynamicTLSModel:
3552 Out << "thread_local(localdynamic) ";
3553 break;
3554 case GlobalVariable::InitialExecTLSModel:
3555 Out << "thread_local(initialexec) ";
3556 break;
3557 case GlobalVariable::LocalExecTLSModel:
3558 Out << "thread_local(localexec) ";
3559 break;
3563 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3564 switch (UA) {
3565 case GlobalVariable::UnnamedAddr::None:
3566 return "";
3567 case GlobalVariable::UnnamedAddr::Local:
3568 return "local_unnamed_addr";
3569 case GlobalVariable::UnnamedAddr::Global:
3570 return "unnamed_addr";
3572 llvm_unreachable("Unknown UnnamedAddr");
3575 static void maybePrintComdat(formatted_raw_ostream &Out,
3576 const GlobalObject &GO) {
3577 const Comdat *C = GO.getComdat();
3578 if (!C)
3579 return;
3581 if (isa<GlobalVariable>(GO))
3582 Out << ',';
3583 Out << " comdat";
3585 if (GO.getName() == C->getName())
3586 return;
3588 Out << '(';
3589 PrintLLVMName(Out, C->getName(), ComdatPrefix);
3590 Out << ')';
3593 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3594 if (GV->isMaterializable())
3595 Out << "; Materializable\n";
3597 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
3598 WriteAsOperandInternal(Out, GV, WriterCtx);
3599 Out << " = ";
3601 if (!GV->hasInitializer() && GV->hasExternalLinkage())
3602 Out << "external ";
3604 Out << getLinkageNameWithSpace(GV->getLinkage());
3605 PrintDSOLocation(*GV, Out);
3606 PrintVisibility(GV->getVisibility(), Out);
3607 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3608 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3609 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3610 if (!UA.empty())
3611 Out << UA << ' ';
3613 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3614 Out << "addrspace(" << AddressSpace << ") ";
3615 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3616 Out << (GV->isConstant() ? "constant " : "global ");
3617 TypePrinter.print(GV->getValueType(), Out);
3619 if (GV->hasInitializer()) {
3620 Out << ' ';
3621 writeOperand(GV->getInitializer(), false);
3624 if (GV->hasSection()) {
3625 Out << ", section \"";
3626 printEscapedString(GV->getSection(), Out);
3627 Out << '"';
3629 if (GV->hasPartition()) {
3630 Out << ", partition \"";
3631 printEscapedString(GV->getPartition(), Out);
3632 Out << '"';
3635 using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;
3636 if (GV->hasSanitizerMetadata()) {
3637 SanitizerMetadata MD = GV->getSanitizerMetadata();
3638 if (MD.NoAddress)
3639 Out << ", no_sanitize_address";
3640 if (MD.NoHWAddress)
3641 Out << ", no_sanitize_hwaddress";
3642 if (MD.Memtag)
3643 Out << ", sanitize_memtag";
3644 if (MD.IsDynInit)
3645 Out << ", sanitize_address_dyninit";
3648 maybePrintComdat(Out, *GV);
3649 if (MaybeAlign A = GV->getAlign())
3650 Out << ", align " << A->value();
3652 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3653 GV->getAllMetadata(MDs);
3654 printMetadataAttachments(MDs, ", ");
3656 auto Attrs = GV->getAttributes();
3657 if (Attrs.hasAttributes())
3658 Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3660 printInfoComment(*GV);
3663 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
3664 if (GA->isMaterializable())
3665 Out << "; Materializable\n";
3667 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
3668 WriteAsOperandInternal(Out, GA, WriterCtx);
3669 Out << " = ";
3671 Out << getLinkageNameWithSpace(GA->getLinkage());
3672 PrintDSOLocation(*GA, Out);
3673 PrintVisibility(GA->getVisibility(), Out);
3674 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
3675 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
3676 StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr());
3677 if (!UA.empty())
3678 Out << UA << ' ';
3680 Out << "alias ";
3682 TypePrinter.print(GA->getValueType(), Out);
3683 Out << ", ";
3685 if (const Constant *Aliasee = GA->getAliasee()) {
3686 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
3687 } else {
3688 TypePrinter.print(GA->getType(), Out);
3689 Out << " <<NULL ALIASEE>>";
3692 if (GA->hasPartition()) {
3693 Out << ", partition \"";
3694 printEscapedString(GA->getPartition(), Out);
3695 Out << '"';
3698 printInfoComment(*GA);
3699 Out << '\n';
3702 void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
3703 if (GI->isMaterializable())
3704 Out << "; Materializable\n";
3706 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
3707 WriteAsOperandInternal(Out, GI, WriterCtx);
3708 Out << " = ";
3710 Out << getLinkageNameWithSpace(GI->getLinkage());
3711 PrintDSOLocation(*GI, Out);
3712 PrintVisibility(GI->getVisibility(), Out);
3714 Out << "ifunc ";
3716 TypePrinter.print(GI->getValueType(), Out);
3717 Out << ", ";
3719 if (const Constant *Resolver = GI->getResolver()) {
3720 writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
3721 } else {
3722 TypePrinter.print(GI->getType(), Out);
3723 Out << " <<NULL RESOLVER>>";
3726 if (GI->hasPartition()) {
3727 Out << ", partition \"";
3728 printEscapedString(GI->getPartition(), Out);
3729 Out << '"';
3732 printInfoComment(*GI);
3733 Out << '\n';
3736 void AssemblyWriter::printComdat(const Comdat *C) {
3737 C->print(Out);
3740 void AssemblyWriter::printTypeIdentities() {
3741 if (TypePrinter.empty())
3742 return;
3744 Out << '\n';
3746 // Emit all numbered types.
3747 auto &NumberedTypes = TypePrinter.getNumberedTypes();
3748 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3749 Out << '%' << I << " = type ";
3751 // Make sure we print out at least one level of the type structure, so
3752 // that we do not get %2 = type %2
3753 TypePrinter.printStructBody(NumberedTypes[I], Out);
3754 Out << '\n';
3757 auto &NamedTypes = TypePrinter.getNamedTypes();
3758 for (StructType *NamedType : NamedTypes) {
3759 PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
3760 Out << " = type ";
3762 // Make sure we print out at least one level of the type structure, so
3763 // that we do not get %FILE = type %FILE
3764 TypePrinter.printStructBody(NamedType, Out);
3765 Out << '\n';
3769 /// printFunction - Print all aspects of a function.
3770 void AssemblyWriter::printFunction(const Function *F) {
3771 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3773 if (F->isMaterializable())
3774 Out << "; Materializable\n";
3776 const AttributeList &Attrs = F->getAttributes();
3777 if (Attrs.hasFnAttrs()) {
3778 AttributeSet AS = Attrs.getFnAttrs();
3779 std::string AttrStr;
3781 for (const Attribute &Attr : AS) {
3782 if (!Attr.isStringAttribute()) {
3783 if (!AttrStr.empty()) AttrStr += ' ';
3784 AttrStr += Attr.getAsString();
3788 if (!AttrStr.empty())
3789 Out << "; Function Attrs: " << AttrStr << '\n';
3792 Machine.incorporateFunction(F);
3794 if (F->isDeclaration()) {
3795 Out << "declare";
3796 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3797 F->getAllMetadata(MDs);
3798 printMetadataAttachments(MDs, " ");
3799 Out << ' ';
3800 } else
3801 Out << "define ";
3803 Out << getLinkageNameWithSpace(F->getLinkage());
3804 PrintDSOLocation(*F, Out);
3805 PrintVisibility(F->getVisibility(), Out);
3806 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3808 // Print the calling convention.
3809 if (F->getCallingConv() != CallingConv::C) {
3810 PrintCallingConv(F->getCallingConv(), Out);
3811 Out << " ";
3814 FunctionType *FT = F->getFunctionType();
3815 if (Attrs.hasRetAttrs())
3816 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3817 TypePrinter.print(F->getReturnType(), Out);
3818 AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
3819 Out << ' ';
3820 WriteAsOperandInternal(Out, F, WriterCtx);
3821 Out << '(';
3823 // Loop over the arguments, printing them...
3824 if (F->isDeclaration() && !IsForDebug) {
3825 // We're only interested in the type here - don't print argument names.
3826 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3827 // Insert commas as we go... the first arg doesn't get a comma
3828 if (I)
3829 Out << ", ";
3830 // Output type...
3831 TypePrinter.print(FT->getParamType(I), Out);
3833 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
3834 if (ArgAttrs.hasAttributes()) {
3835 Out << ' ';
3836 writeAttributeSet(ArgAttrs);
3839 } else {
3840 // The arguments are meaningful here, print them in detail.
3841 for (const Argument &Arg : F->args()) {
3842 // Insert commas as we go... the first arg doesn't get a comma
3843 if (Arg.getArgNo() != 0)
3844 Out << ", ";
3845 printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
3849 // Finish printing arguments...
3850 if (FT->isVarArg()) {
3851 if (FT->getNumParams()) Out << ", ";
3852 Out << "..."; // Output varargs portion of signature!
3854 Out << ')';
3855 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3856 if (!UA.empty())
3857 Out << ' ' << UA;
3858 // We print the function address space if it is non-zero or if we are writing
3859 // a module with a non-zero program address space or if there is no valid
3860 // Module* so that the file can be parsed without the datalayout string.
3861 const Module *Mod = F->getParent();
3862 if (F->getAddressSpace() != 0 || !Mod ||
3863 Mod->getDataLayout().getProgramAddressSpace() != 0)
3864 Out << " addrspace(" << F->getAddressSpace() << ")";
3865 if (Attrs.hasFnAttrs())
3866 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
3867 if (F->hasSection()) {
3868 Out << " section \"";
3869 printEscapedString(F->getSection(), Out);
3870 Out << '"';
3872 if (F->hasPartition()) {
3873 Out << " partition \"";
3874 printEscapedString(F->getPartition(), Out);
3875 Out << '"';
3877 maybePrintComdat(Out, *F);
3878 if (MaybeAlign A = F->getAlign())
3879 Out << " align " << A->value();
3880 if (F->hasGC())
3881 Out << " gc \"" << F->getGC() << '"';
3882 if (F->hasPrefixData()) {
3883 Out << " prefix ";
3884 writeOperand(F->getPrefixData(), true);
3886 if (F->hasPrologueData()) {
3887 Out << " prologue ";
3888 writeOperand(F->getPrologueData(), true);
3890 if (F->hasPersonalityFn()) {
3891 Out << " personality ";
3892 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3895 if (F->isDeclaration()) {
3896 Out << '\n';
3897 } else {
3898 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3899 F->getAllMetadata(MDs);
3900 printMetadataAttachments(MDs, " ");
3902 Out << " {";
3903 // Output all of the function's basic blocks.
3904 for (const BasicBlock &BB : *F)
3905 printBasicBlock(&BB);
3907 // Output the function's use-lists.
3908 printUseLists(F);
3910 Out << "}\n";
3913 Machine.purgeFunction();
3916 /// printArgument - This member is called for every argument that is passed into
3917 /// the function. Simply print it out
3918 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3919 // Output type...
3920 TypePrinter.print(Arg->getType(), Out);
3922 // Output parameter attributes list
3923 if (Attrs.hasAttributes()) {
3924 Out << ' ';
3925 writeAttributeSet(Attrs);
3928 // Output name, if available...
3929 if (Arg->hasName()) {
3930 Out << ' ';
3931 PrintLLVMName(Out, Arg);
3932 } else {
3933 int Slot = Machine.getLocalSlot(Arg);
3934 assert(Slot != -1 && "expect argument in function here");
3935 Out << " %" << Slot;
3939 /// printBasicBlock - This member is called for each basic block in a method.
3940 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3941 bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
3942 if (BB->hasName()) { // Print out the label if it exists...
3943 Out << "\n";
3944 PrintLLVMName(Out, BB->getName(), LabelPrefix);
3945 Out << ':';
3946 } else if (!IsEntryBlock) {
3947 Out << "\n";
3948 int Slot = Machine.getLocalSlot(BB);
3949 if (Slot != -1)
3950 Out << Slot << ":";
3951 else
3952 Out << "<badref>:";
3955 if (!IsEntryBlock) {
3956 // Output predecessors for the block.
3957 Out.PadToColumn(50);
3958 Out << ";";
3959 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3961 if (PI == PE) {
3962 Out << " No predecessors!";
3963 } else {
3964 Out << " preds = ";
3965 writeOperand(*PI, false);
3966 for (++PI; PI != PE; ++PI) {
3967 Out << ", ";
3968 writeOperand(*PI, false);
3973 Out << "\n";
3975 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3977 // Output all of the instructions in the basic block...
3978 for (const Instruction &I : *BB) {
3979 printInstructionLine(I);
3982 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3985 /// printInstructionLine - Print an instruction and a newline character.
3986 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3987 printInstruction(I);
3988 Out << '\n';
3991 /// printGCRelocateComment - print comment after call to the gc.relocate
3992 /// intrinsic indicating base and derived pointer names.
3993 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3994 Out << " ; (";
3995 writeOperand(Relocate.getBasePtr(), false);
3996 Out << ", ";
3997 writeOperand(Relocate.getDerivedPtr(), false);
3998 Out << ")";
4001 /// printInfoComment - Print a little comment after the instruction indicating
4002 /// which slot it occupies.
4003 void AssemblyWriter::printInfoComment(const Value &V) {
4004 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
4005 printGCRelocateComment(*Relocate);
4007 if (AnnotationWriter)
4008 AnnotationWriter->printInfoComment(V, Out);
4011 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
4012 raw_ostream &Out) {
4013 // We print the address space of the call if it is non-zero.
4014 if (Operand == nullptr) {
4015 Out << " <cannot get addrspace!>";
4016 return;
4018 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
4019 bool PrintAddrSpace = CallAddrSpace != 0;
4020 if (!PrintAddrSpace) {
4021 const Module *Mod = getModuleFromVal(I);
4022 // We also print it if it is zero but not equal to the program address space
4023 // or if we can't find a valid Module* to make it possible to parse
4024 // the resulting file even without a datalayout string.
4025 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
4026 PrintAddrSpace = true;
4028 if (PrintAddrSpace)
4029 Out << " addrspace(" << CallAddrSpace << ")";
4032 // This member is called for each Instruction in a function..
4033 void AssemblyWriter::printInstruction(const Instruction &I) {
4034 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
4036 // Print out indentation for an instruction.
4037 Out << " ";
4039 // Print out name if it exists...
4040 if (I.hasName()) {
4041 PrintLLVMName(Out, &I);
4042 Out << " = ";
4043 } else if (!I.getType()->isVoidTy()) {
4044 // Print out the def slot taken.
4045 int SlotNum = Machine.getLocalSlot(&I);
4046 if (SlotNum == -1)
4047 Out << "<badref> = ";
4048 else
4049 Out << '%' << SlotNum << " = ";
4052 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4053 if (CI->isMustTailCall())
4054 Out << "musttail ";
4055 else if (CI->isTailCall())
4056 Out << "tail ";
4057 else if (CI->isNoTailCall())
4058 Out << "notail ";
4061 // Print out the opcode...
4062 Out << I.getOpcodeName();
4064 // If this is an atomic load or store, print out the atomic marker.
4065 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
4066 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
4067 Out << " atomic";
4069 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
4070 Out << " weak";
4072 // If this is a volatile operation, print out the volatile marker.
4073 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
4074 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
4075 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
4076 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
4077 Out << " volatile";
4079 // Print out optimization information.
4080 WriteOptimizationInfo(Out, &I);
4082 // Print out the compare instruction predicates
4083 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
4084 Out << ' ' << CI->getPredicate();
4086 // Print out the atomicrmw operation
4087 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
4088 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
4090 // Print out the type of the operands...
4091 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
4093 // Special case conditional branches to swizzle the condition out to the front
4094 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
4095 const BranchInst &BI(cast<BranchInst>(I));
4096 Out << ' ';
4097 writeOperand(BI.getCondition(), true);
4098 Out << ", ";
4099 writeOperand(BI.getSuccessor(0), true);
4100 Out << ", ";
4101 writeOperand(BI.getSuccessor(1), true);
4103 } else if (isa<SwitchInst>(I)) {
4104 const SwitchInst& SI(cast<SwitchInst>(I));
4105 // Special case switch instruction to get formatting nice and correct.
4106 Out << ' ';
4107 writeOperand(SI.getCondition(), true);
4108 Out << ", ";
4109 writeOperand(SI.getDefaultDest(), true);
4110 Out << " [";
4111 for (auto Case : SI.cases()) {
4112 Out << "\n ";
4113 writeOperand(Case.getCaseValue(), true);
4114 Out << ", ";
4115 writeOperand(Case.getCaseSuccessor(), true);
4117 Out << "\n ]";
4118 } else if (isa<IndirectBrInst>(I)) {
4119 // Special case indirectbr instruction to get formatting nice and correct.
4120 Out << ' ';
4121 writeOperand(Operand, true);
4122 Out << ", [";
4124 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
4125 if (i != 1)
4126 Out << ", ";
4127 writeOperand(I.getOperand(i), true);
4129 Out << ']';
4130 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
4131 Out << ' ';
4132 TypePrinter.print(I.getType(), Out);
4133 Out << ' ';
4135 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
4136 if (op) Out << ", ";
4137 Out << "[ ";
4138 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
4139 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
4141 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
4142 Out << ' ';
4143 writeOperand(I.getOperand(0), true);
4144 for (unsigned i : EVI->indices())
4145 Out << ", " << i;
4146 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
4147 Out << ' ';
4148 writeOperand(I.getOperand(0), true); Out << ", ";
4149 writeOperand(I.getOperand(1), true);
4150 for (unsigned i : IVI->indices())
4151 Out << ", " << i;
4152 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
4153 Out << ' ';
4154 TypePrinter.print(I.getType(), Out);
4155 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4156 Out << '\n';
4158 if (LPI->isCleanup())
4159 Out << " cleanup";
4161 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
4162 if (i != 0 || LPI->isCleanup()) Out << "\n";
4163 if (LPI->isCatch(i))
4164 Out << " catch ";
4165 else
4166 Out << " filter ";
4168 writeOperand(LPI->getClause(i), true);
4170 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
4171 Out << " within ";
4172 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
4173 Out << " [";
4174 unsigned Op = 0;
4175 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
4176 if (Op > 0)
4177 Out << ", ";
4178 writeOperand(PadBB, /*PrintType=*/true);
4179 ++Op;
4181 Out << "] unwind ";
4182 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4183 writeOperand(UnwindDest, /*PrintType=*/true);
4184 else
4185 Out << "to caller";
4186 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
4187 Out << " within ";
4188 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
4189 Out << " [";
4190 for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
4191 if (Op > 0)
4192 Out << ", ";
4193 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
4195 Out << ']';
4196 } else if (isa<ReturnInst>(I) && !Operand) {
4197 Out << " void";
4198 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
4199 Out << " from ";
4200 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4202 Out << " to ";
4203 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4204 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
4205 Out << " from ";
4206 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4208 Out << " unwind ";
4209 if (CRI->hasUnwindDest())
4210 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4211 else
4212 Out << "to caller";
4213 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4214 // Print the calling convention being used.
4215 if (CI->getCallingConv() != CallingConv::C) {
4216 Out << " ";
4217 PrintCallingConv(CI->getCallingConv(), Out);
4220 Operand = CI->getCalledOperand();
4221 FunctionType *FTy = CI->getFunctionType();
4222 Type *RetTy = FTy->getReturnType();
4223 const AttributeList &PAL = CI->getAttributes();
4225 if (PAL.hasRetAttrs())
4226 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4228 // Only print addrspace(N) if necessary:
4229 maybePrintCallAddrSpace(Operand, &I, Out);
4231 // If possible, print out the short form of the call instruction. We can
4232 // only do this if the first argument is a pointer to a nonvararg function,
4233 // and if the return type is not a pointer to a function.
4234 Out << ' ';
4235 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4236 Out << ' ';
4237 writeOperand(Operand, false);
4238 Out << '(';
4239 for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
4240 if (op > 0)
4241 Out << ", ";
4242 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
4245 // Emit an ellipsis if this is a musttail call in a vararg function. This
4246 // is only to aid readability, musttail calls forward varargs by default.
4247 if (CI->isMustTailCall() && CI->getParent() &&
4248 CI->getParent()->getParent() &&
4249 CI->getParent()->getParent()->isVarArg()) {
4250 if (CI->arg_size() > 0)
4251 Out << ", ";
4252 Out << "...";
4255 Out << ')';
4256 if (PAL.hasFnAttrs())
4257 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4259 writeOperandBundles(CI);
4260 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
4261 Operand = II->getCalledOperand();
4262 FunctionType *FTy = II->getFunctionType();
4263 Type *RetTy = FTy->getReturnType();
4264 const AttributeList &PAL = II->getAttributes();
4266 // Print the calling convention being used.
4267 if (II->getCallingConv() != CallingConv::C) {
4268 Out << " ";
4269 PrintCallingConv(II->getCallingConv(), Out);
4272 if (PAL.hasRetAttrs())
4273 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4275 // Only print addrspace(N) if necessary:
4276 maybePrintCallAddrSpace(Operand, &I, Out);
4278 // If possible, print out the short form of the invoke instruction. We can
4279 // only do this if the first argument is a pointer to a nonvararg function,
4280 // and if the return type is not a pointer to a function.
4282 Out << ' ';
4283 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4284 Out << ' ';
4285 writeOperand(Operand, false);
4286 Out << '(';
4287 for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
4288 if (op)
4289 Out << ", ";
4290 writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
4293 Out << ')';
4294 if (PAL.hasFnAttrs())
4295 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4297 writeOperandBundles(II);
4299 Out << "\n to ";
4300 writeOperand(II->getNormalDest(), true);
4301 Out << " unwind ";
4302 writeOperand(II->getUnwindDest(), true);
4303 } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
4304 Operand = CBI->getCalledOperand();
4305 FunctionType *FTy = CBI->getFunctionType();
4306 Type *RetTy = FTy->getReturnType();
4307 const AttributeList &PAL = CBI->getAttributes();
4309 // Print the calling convention being used.
4310 if (CBI->getCallingConv() != CallingConv::C) {
4311 Out << " ";
4312 PrintCallingConv(CBI->getCallingConv(), Out);
4315 if (PAL.hasRetAttrs())
4316 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4318 // If possible, print out the short form of the callbr instruction. We can
4319 // only do this if the first argument is a pointer to a nonvararg function,
4320 // and if the return type is not a pointer to a function.
4322 Out << ' ';
4323 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4324 Out << ' ';
4325 writeOperand(Operand, false);
4326 Out << '(';
4327 for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
4328 if (op)
4329 Out << ", ";
4330 writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
4333 Out << ')';
4334 if (PAL.hasFnAttrs())
4335 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4337 writeOperandBundles(CBI);
4339 Out << "\n to ";
4340 writeOperand(CBI->getDefaultDest(), true);
4341 Out << " [";
4342 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
4343 if (i != 0)
4344 Out << ", ";
4345 writeOperand(CBI->getIndirectDest(i), true);
4347 Out << ']';
4348 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4349 Out << ' ';
4350 if (AI->isUsedWithInAlloca())
4351 Out << "inalloca ";
4352 if (AI->isSwiftError())
4353 Out << "swifterror ";
4354 TypePrinter.print(AI->getAllocatedType(), Out);
4356 // Explicitly write the array size if the code is broken, if it's an array
4357 // allocation, or if the type is not canonical for scalar allocations. The
4358 // latter case prevents the type from mutating when round-tripping through
4359 // assembly.
4360 if (!AI->getArraySize() || AI->isArrayAllocation() ||
4361 !AI->getArraySize()->getType()->isIntegerTy(32)) {
4362 Out << ", ";
4363 writeOperand(AI->getArraySize(), true);
4365 if (MaybeAlign A = AI->getAlign()) {
4366 Out << ", align " << A->value();
4369 unsigned AddrSpace = AI->getAddressSpace();
4370 if (AddrSpace != 0) {
4371 Out << ", addrspace(" << AddrSpace << ')';
4373 } else if (isa<CastInst>(I)) {
4374 if (Operand) {
4375 Out << ' ';
4376 writeOperand(Operand, true); // Work with broken code
4378 Out << " to ";
4379 TypePrinter.print(I.getType(), Out);
4380 } else if (isa<VAArgInst>(I)) {
4381 if (Operand) {
4382 Out << ' ';
4383 writeOperand(Operand, true); // Work with broken code
4385 Out << ", ";
4386 TypePrinter.print(I.getType(), Out);
4387 } else if (Operand) { // Print the normal way.
4388 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4389 Out << ' ';
4390 TypePrinter.print(GEP->getSourceElementType(), Out);
4391 Out << ',';
4392 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4393 Out << ' ';
4394 TypePrinter.print(LI->getType(), Out);
4395 Out << ',';
4398 // PrintAllTypes - Instructions who have operands of all the same type
4399 // omit the type from all but the first operand. If the instruction has
4400 // different type operands (for example br), then they are all printed.
4401 bool PrintAllTypes = false;
4402 Type *TheType = Operand->getType();
4404 // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
4405 // types.
4406 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
4407 isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||
4408 isa<AtomicRMWInst>(I)) {
4409 PrintAllTypes = true;
4410 } else {
4411 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4412 Operand = I.getOperand(i);
4413 // note that Operand shouldn't be null, but the test helps make dump()
4414 // more tolerant of malformed IR
4415 if (Operand && Operand->getType() != TheType) {
4416 PrintAllTypes = true; // We have differing types! Print them all!
4417 break;
4422 if (!PrintAllTypes) {
4423 Out << ' ';
4424 TypePrinter.print(TheType, Out);
4427 Out << ' ';
4428 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4429 if (i) Out << ", ";
4430 writeOperand(I.getOperand(i), PrintAllTypes);
4434 // Print atomic ordering/alignment for memory operations
4435 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4436 if (LI->isAtomic())
4437 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4438 if (MaybeAlign A = LI->getAlign())
4439 Out << ", align " << A->value();
4440 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4441 if (SI->isAtomic())
4442 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4443 if (MaybeAlign A = SI->getAlign())
4444 Out << ", align " << A->value();
4445 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4446 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4447 CXI->getFailureOrdering(), CXI->getSyncScopeID());
4448 Out << ", align " << CXI->getAlign().value();
4449 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4450 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4451 RMWI->getSyncScopeID());
4452 Out << ", align " << RMWI->getAlign().value();
4453 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4454 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4455 } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
4456 PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
4459 // Print Metadata info.
4460 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4461 I.getAllMetadata(InstMD);
4462 printMetadataAttachments(InstMD, ", ");
4464 // Print a nice comment.
4465 printInfoComment(I);
4468 void AssemblyWriter::printMetadataAttachments(
4469 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4470 StringRef Separator) {
4471 if (MDs.empty())
4472 return;
4474 if (MDNames.empty())
4475 MDs[0].second->getContext().getMDKindNames(MDNames);
4477 auto WriterCtx = getContext();
4478 for (const auto &I : MDs) {
4479 unsigned Kind = I.first;
4480 Out << Separator;
4481 if (Kind < MDNames.size()) {
4482 Out << "!";
4483 printMetadataIdentifier(MDNames[Kind], Out);
4484 } else
4485 Out << "!<unknown kind #" << Kind << ">";
4486 Out << ' ';
4487 WriteAsOperandInternal(Out, I.second, WriterCtx);
4491 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4492 Out << '!' << Slot << " = ";
4493 printMDNodeBody(Node);
4494 Out << "\n";
4497 void AssemblyWriter::writeAllMDNodes() {
4498 SmallVector<const MDNode *, 16> Nodes;
4499 Nodes.resize(Machine.mdn_size());
4500 for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
4501 Nodes[I.second] = cast<MDNode>(I.first);
4503 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4504 writeMDNode(i, Nodes[i]);
4508 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4509 auto WriterCtx = getContext();
4510 WriteMDNodeBodyInternal(Out, Node, WriterCtx);
4513 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4514 if (!Attr.isTypeAttribute()) {
4515 Out << Attr.getAsString(InAttrGroup);
4516 return;
4519 Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());
4520 if (Type *Ty = Attr.getValueAsType()) {
4521 Out << '(';
4522 TypePrinter.print(Ty, Out);
4523 Out << ')';
4527 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4528 bool InAttrGroup) {
4529 bool FirstAttr = true;
4530 for (const auto &Attr : AttrSet) {
4531 if (!FirstAttr)
4532 Out << ' ';
4533 writeAttribute(Attr, InAttrGroup);
4534 FirstAttr = false;
4538 void AssemblyWriter::writeAllAttributeGroups() {
4539 std::vector<std::pair<AttributeSet, unsigned>> asVec;
4540 asVec.resize(Machine.as_size());
4542 for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
4543 asVec[I.second] = I;
4545 for (const auto &I : asVec)
4546 Out << "attributes #" << I.second << " = { "
4547 << I.first.getAsString(true) << " }\n";
4550 void AssemblyWriter::printUseListOrder(const Value *V,
4551 const std::vector<unsigned> &Shuffle) {
4552 bool IsInFunction = Machine.getFunction();
4553 if (IsInFunction)
4554 Out << " ";
4556 Out << "uselistorder";
4557 if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
4558 Out << "_bb ";
4559 writeOperand(BB->getParent(), false);
4560 Out << ", ";
4561 writeOperand(BB, false);
4562 } else {
4563 Out << " ";
4564 writeOperand(V, true);
4566 Out << ", { ";
4568 assert(Shuffle.size() >= 2 && "Shuffle too small");
4569 Out << Shuffle[0];
4570 for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)
4571 Out << ", " << Shuffle[I];
4572 Out << " }\n";
4575 void AssemblyWriter::printUseLists(const Function *F) {
4576 auto It = UseListOrders.find(F);
4577 if (It == UseListOrders.end())
4578 return;
4580 Out << "\n; uselistorder directives\n";
4581 for (const auto &Pair : It->second)
4582 printUseListOrder(Pair.first, Pair.second);
4585 //===----------------------------------------------------------------------===//
4586 // External Interface declarations
4587 //===----------------------------------------------------------------------===//
4589 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4590 bool ShouldPreserveUseListOrder,
4591 bool IsForDebug) const {
4592 SlotTracker SlotTable(this->getParent());
4593 formatted_raw_ostream OS(ROS);
4594 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4595 IsForDebug,
4596 ShouldPreserveUseListOrder);
4597 W.printFunction(this);
4600 void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4601 bool ShouldPreserveUseListOrder,
4602 bool IsForDebug) const {
4603 SlotTracker SlotTable(this->getParent());
4604 formatted_raw_ostream OS(ROS);
4605 AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
4606 IsForDebug,
4607 ShouldPreserveUseListOrder);
4608 W.printBasicBlock(this);
4611 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4612 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4613 SlotTracker SlotTable(this);
4614 formatted_raw_ostream OS(ROS);
4615 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4616 ShouldPreserveUseListOrder);
4617 W.printModule(this);
4620 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4621 SlotTracker SlotTable(getParent());
4622 formatted_raw_ostream OS(ROS);
4623 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4624 W.printNamedMDNode(this);
4627 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4628 bool IsForDebug) const {
4629 std::optional<SlotTracker> LocalST;
4630 SlotTracker *SlotTable;
4631 if (auto *ST = MST.getMachine())
4632 SlotTable = ST;
4633 else {
4634 LocalST.emplace(getParent());
4635 SlotTable = &*LocalST;
4638 formatted_raw_ostream OS(ROS);
4639 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4640 W.printNamedMDNode(this);
4643 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4644 PrintLLVMName(ROS, getName(), ComdatPrefix);
4645 ROS << " = comdat ";
4647 switch (getSelectionKind()) {
4648 case Comdat::Any:
4649 ROS << "any";
4650 break;
4651 case Comdat::ExactMatch:
4652 ROS << "exactmatch";
4653 break;
4654 case Comdat::Largest:
4655 ROS << "largest";
4656 break;
4657 case Comdat::NoDeduplicate:
4658 ROS << "nodeduplicate";
4659 break;
4660 case Comdat::SameSize:
4661 ROS << "samesize";
4662 break;
4665 ROS << '\n';
4668 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4669 TypePrinting TP;
4670 TP.print(const_cast<Type*>(this), OS);
4672 if (NoDetails)
4673 return;
4675 // If the type is a named struct type, print the body as well.
4676 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4677 if (!STy->isLiteral()) {
4678 OS << " = type ";
4679 TP.printStructBody(STy, OS);
4683 static bool isReferencingMDNode(const Instruction &I) {
4684 if (const auto *CI = dyn_cast<CallInst>(&I))
4685 if (Function *F = CI->getCalledFunction())
4686 if (F->isIntrinsic())
4687 for (auto &Op : I.operands())
4688 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4689 if (isa<MDNode>(V->getMetadata()))
4690 return true;
4691 return false;
4694 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4695 bool ShouldInitializeAllMetadata = false;
4696 if (auto *I = dyn_cast<Instruction>(this))
4697 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4698 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4699 ShouldInitializeAllMetadata = true;
4701 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4702 print(ROS, MST, IsForDebug);
4705 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4706 bool IsForDebug) const {
4707 formatted_raw_ostream OS(ROS);
4708 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4709 SlotTracker &SlotTable =
4710 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4711 auto incorporateFunction = [&](const Function *F) {
4712 if (F)
4713 MST.incorporateFunction(*F);
4716 if (const Instruction *I = dyn_cast<Instruction>(this)) {
4717 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4718 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4719 W.printInstruction(*I);
4720 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4721 incorporateFunction(BB->getParent());
4722 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4723 W.printBasicBlock(BB);
4724 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4725 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4726 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4727 W.printGlobal(V);
4728 else if (const Function *F = dyn_cast<Function>(GV))
4729 W.printFunction(F);
4730 else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
4731 W.printAlias(A);
4732 else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
4733 W.printIFunc(I);
4734 else
4735 llvm_unreachable("Unknown GlobalValue to print out!");
4736 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4737 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4738 } else if (const Constant *C = dyn_cast<Constant>(this)) {
4739 TypePrinting TypePrinter;
4740 TypePrinter.print(C->getType(), OS);
4741 OS << ' ';
4742 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
4743 WriteConstantInternal(OS, C, WriterCtx);
4744 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4745 this->printAsOperand(OS, /* PrintType */ true, MST);
4746 } else {
4747 llvm_unreachable("Unknown value to print out!");
4751 /// Print without a type, skipping the TypePrinting object.
4753 /// \return \c true iff printing was successful.
4754 static bool printWithoutType(const Value &V, raw_ostream &O,
4755 SlotTracker *Machine, const Module *M) {
4756 if (V.hasName() || isa<GlobalValue>(V) ||
4757 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4758 AsmWriterContext WriterCtx(nullptr, Machine, M);
4759 WriteAsOperandInternal(O, &V, WriterCtx);
4760 return true;
4762 return false;
4765 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4766 ModuleSlotTracker &MST) {
4767 TypePrinting TypePrinter(MST.getModule());
4768 if (PrintType) {
4769 TypePrinter.print(V.getType(), O);
4770 O << ' ';
4773 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
4774 WriteAsOperandInternal(O, &V, WriterCtx);
4777 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4778 const Module *M) const {
4779 if (!M)
4780 M = getModuleFromVal(this);
4782 if (!PrintType)
4783 if (printWithoutType(*this, O, nullptr, M))
4784 return;
4786 SlotTracker Machine(
4787 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4788 ModuleSlotTracker MST(Machine, M);
4789 printAsOperandImpl(*this, O, PrintType, MST);
4792 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4793 ModuleSlotTracker &MST) const {
4794 if (!PrintType)
4795 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4796 return;
4798 printAsOperandImpl(*this, O, PrintType, MST);
4801 /// Recursive version of printMetadataImpl.
4802 static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
4803 AsmWriterContext &WriterCtx) {
4804 formatted_raw_ostream OS(ROS);
4805 WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
4807 auto *N = dyn_cast<MDNode>(&MD);
4808 if (!N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4809 return;
4811 OS << " = ";
4812 WriteMDNodeBodyInternal(OS, N, WriterCtx);
4815 namespace {
4816 struct MDTreeAsmWriterContext : public AsmWriterContext {
4817 unsigned Level;
4818 // {Level, Printed string}
4819 using EntryTy = std::pair<unsigned, std::string>;
4820 SmallVector<EntryTy, 4> Buffer;
4822 // Used to break the cycle in case there is any.
4823 SmallPtrSet<const Metadata *, 4> Visited;
4825 raw_ostream &MainOS;
4827 MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
4828 raw_ostream &OS, const Metadata *InitMD)
4829 : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
4831 void onWriteMetadataAsOperand(const Metadata *MD) override {
4832 if (!Visited.insert(MD).second)
4833 return;
4835 std::string Str;
4836 raw_string_ostream SS(Str);
4837 ++Level;
4838 // A placeholder entry to memorize the correct
4839 // position in buffer.
4840 Buffer.emplace_back(std::make_pair(Level, ""));
4841 unsigned InsertIdx = Buffer.size() - 1;
4843 printMetadataImplRec(SS, *MD, *this);
4844 Buffer[InsertIdx].second = std::move(SS.str());
4845 --Level;
4848 ~MDTreeAsmWriterContext() {
4849 for (const auto &Entry : Buffer) {
4850 MainOS << "\n";
4851 unsigned NumIndent = Entry.first * 2U;
4852 MainOS.indent(NumIndent) << Entry.second;
4856 } // end anonymous namespace
4858 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4859 ModuleSlotTracker &MST, const Module *M,
4860 bool OnlyAsOperand, bool PrintAsTree = false) {
4861 formatted_raw_ostream OS(ROS);
4863 TypePrinting TypePrinter(M);
4865 std::unique_ptr<AsmWriterContext> WriterCtx;
4866 if (PrintAsTree && !OnlyAsOperand)
4867 WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
4868 &TypePrinter, MST.getMachine(), M, OS, &MD);
4869 else
4870 WriterCtx =
4871 std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
4873 WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
4875 auto *N = dyn_cast<MDNode>(&MD);
4876 if (OnlyAsOperand || !N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4877 return;
4879 OS << " = ";
4880 WriteMDNodeBodyInternal(OS, N, *WriterCtx);
4883 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4884 ModuleSlotTracker MST(M, isa<MDNode>(this));
4885 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4888 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4889 const Module *M) const {
4890 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4893 void Metadata::print(raw_ostream &OS, const Module *M,
4894 bool /*IsForDebug*/) const {
4895 ModuleSlotTracker MST(M, isa<MDNode>(this));
4896 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4899 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4900 const Module *M, bool /*IsForDebug*/) const {
4901 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4904 void MDNode::printTree(raw_ostream &OS, const Module *M) const {
4905 ModuleSlotTracker MST(M, true);
4906 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
4907 /*PrintAsTree=*/true);
4910 void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,
4911 const Module *M) const {
4912 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
4913 /*PrintAsTree=*/true);
4916 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4917 SlotTracker SlotTable(this);
4918 formatted_raw_ostream OS(ROS);
4919 AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4920 W.printModuleSummaryIndex();
4923 void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB,
4924 unsigned UB) const {
4925 SlotTracker *ST = MachineStorage.get();
4926 if (!ST)
4927 return;
4929 for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
4930 if (I.second >= LB && I.second < UB)
4931 L.push_back(std::make_pair(I.second, I.first));
4934 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4935 // Value::dump - allow easy printing of Values from the debugger.
4936 LLVM_DUMP_METHOD
4937 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4939 // Type::dump - allow easy printing of Types from the debugger.
4940 LLVM_DUMP_METHOD
4941 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4943 // Module::dump() - Allow printing of Modules from the debugger.
4944 LLVM_DUMP_METHOD
4945 void Module::dump() const {
4946 print(dbgs(), nullptr,
4947 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4950 // Allow printing of Comdats from the debugger.
4951 LLVM_DUMP_METHOD
4952 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4954 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4955 LLVM_DUMP_METHOD
4956 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4958 LLVM_DUMP_METHOD
4959 void Metadata::dump() const { dump(nullptr); }
4961 LLVM_DUMP_METHOD
4962 void Metadata::dump(const Module *M) const {
4963 print(dbgs(), M, /*IsForDebug=*/true);
4964 dbgs() << '\n';
4967 LLVM_DUMP_METHOD
4968 void MDNode::dumpTree() const { dumpTree(nullptr); }
4970 LLVM_DUMP_METHOD
4971 void MDNode::dumpTree(const Module *M) const {
4972 printTree(dbgs(), M);
4973 dbgs() << '\n';
4976 // Allow printing of ModuleSummaryIndex from the debugger.
4977 LLVM_DUMP_METHOD
4978 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4979 #endif