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