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