1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements `print` family of functions in classes like
11 // Module, Function, Value, etc. In-memory representation of those classes is
12 // converted to IR strings.
14 // Note that these routines must be extremely tolerant of various errors in the
15 // LLVM code, because it can be used for debugging transformations.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/iterator_range.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/Config/llvm-config.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/AssemblyAnnotationWriter.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/CallSite.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/Comdat.h"
42 #include "llvm/IR/Constant.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DebugInfoMetadata.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GlobalAlias.h"
48 #include "llvm/IR/GlobalIFunc.h"
49 #include "llvm/IR/GlobalIndirectSymbol.h"
50 #include "llvm/IR/GlobalObject.h"
51 #include "llvm/IR/GlobalValue.h"
52 #include "llvm/IR/GlobalVariable.h"
53 #include "llvm/IR/IRPrintingPasses.h"
54 #include "llvm/IR/InlineAsm.h"
55 #include "llvm/IR/InstrTypes.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Metadata.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/ModuleSlotTracker.h"
62 #include "llvm/IR/ModuleSummaryIndex.h"
63 #include "llvm/IR/Operator.h"
64 #include "llvm/IR/Statepoint.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/TypeFinder.h"
67 #include "llvm/IR/Use.h"
68 #include "llvm/IR/UseListOrder.h"
69 #include "llvm/IR/User.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/Support/AtomicOrdering.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/Format.h"
77 #include "llvm/Support/FormattedStream.h"
78 #include "llvm/Support/raw_ostream.h"
93 // Make virtual table appear in this compilation unit.
94 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
96 //===----------------------------------------------------------------------===//
98 //===----------------------------------------------------------------------===//
103 DenseMap
<const Value
*, std::pair
<unsigned, bool>> IDs
;
105 unsigned size() const { return IDs
.size(); }
106 std::pair
<unsigned, bool> &operator[](const Value
*V
) { return IDs
[V
]; }
108 std::pair
<unsigned, bool> lookup(const Value
*V
) const {
109 return IDs
.lookup(V
);
112 void index(const Value
*V
) {
113 // Explicitly sequence get-size and insert-value operations to avoid UB.
114 unsigned ID
= IDs
.size() + 1;
119 } // end anonymous namespace
121 static void orderValue(const Value
*V
, OrderMap
&OM
) {
122 if (OM
.lookup(V
).first
)
125 if (const Constant
*C
= dyn_cast
<Constant
>(V
))
126 if (C
->getNumOperands() && !isa
<GlobalValue
>(C
))
127 for (const Value
*Op
: C
->operands())
128 if (!isa
<BasicBlock
>(Op
) && !isa
<GlobalValue
>(Op
))
131 // Note: we cannot cache this lookup above, since inserting into the map
132 // changes the map's size, and thus affects the other IDs.
136 static OrderMap
orderModule(const Module
*M
) {
137 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
138 // and ValueEnumerator::incorporateFunction().
141 for (const GlobalVariable
&G
: M
->globals()) {
142 if (G
.hasInitializer())
143 if (!isa
<GlobalValue
>(G
.getInitializer()))
144 orderValue(G
.getInitializer(), OM
);
147 for (const GlobalAlias
&A
: M
->aliases()) {
148 if (!isa
<GlobalValue
>(A
.getAliasee()))
149 orderValue(A
.getAliasee(), OM
);
152 for (const GlobalIFunc
&I
: M
->ifuncs()) {
153 if (!isa
<GlobalValue
>(I
.getResolver()))
154 orderValue(I
.getResolver(), OM
);
157 for (const Function
&F
: *M
) {
158 for (const Use
&U
: F
.operands())
159 if (!isa
<GlobalValue
>(U
.get()))
160 orderValue(U
.get(), OM
);
164 if (F
.isDeclaration())
167 for (const Argument
&A
: F
.args())
169 for (const BasicBlock
&BB
: F
) {
171 for (const Instruction
&I
: BB
) {
172 for (const Value
*Op
: I
.operands())
173 if ((isa
<Constant
>(*Op
) && !isa
<GlobalValue
>(*Op
)) ||
183 static void predictValueUseListOrderImpl(const Value
*V
, const Function
*F
,
184 unsigned ID
, const OrderMap
&OM
,
185 UseListOrderStack
&Stack
) {
186 // Predict use-list order for this one.
187 using Entry
= std::pair
<const Use
*, unsigned>;
188 SmallVector
<Entry
, 64> List
;
189 for (const Use
&U
: V
->uses())
190 // Check if this user will be serialized.
191 if (OM
.lookup(U
.getUser()).first
)
192 List
.push_back(std::make_pair(&U
, List
.size()));
195 // We may have lost some users.
199 !isa
<GlobalVariable
>(V
) && !isa
<Function
>(V
) && !isa
<BasicBlock
>(V
);
200 if (auto *BA
= dyn_cast
<BlockAddress
>(V
))
201 ID
= OM
.lookup(BA
->getBasicBlock()).first
;
202 llvm::sort(List
, [&](const Entry
&L
, const Entry
&R
) {
203 const Use
*LU
= L
.first
;
204 const Use
*RU
= R
.first
;
208 auto LID
= OM
.lookup(LU
->getUser()).first
;
209 auto RID
= OM
.lookup(RU
->getUser()).first
;
211 // If ID is 4, then expect: 7 6 5 1 2 3.
225 // LID and RID are equal, so we have different operands of the same user.
226 // Assume operands are added in order for all instructions.
229 return LU
->getOperandNo() < RU
->getOperandNo();
230 return LU
->getOperandNo() > RU
->getOperandNo();
234 List
.begin(), List
.end(),
235 [](const Entry
&L
, const Entry
&R
) { return L
.second
< R
.second
; }))
236 // Order is already correct.
239 // Store the shuffle.
240 Stack
.emplace_back(V
, F
, List
.size());
241 assert(List
.size() == Stack
.back().Shuffle
.size() && "Wrong size");
242 for (size_t I
= 0, E
= List
.size(); I
!= E
; ++I
)
243 Stack
.back().Shuffle
[I
] = List
[I
].second
;
246 static void predictValueUseListOrder(const Value
*V
, const Function
*F
,
247 OrderMap
&OM
, UseListOrderStack
&Stack
) {
248 auto &IDPair
= OM
[V
];
249 assert(IDPair
.first
&& "Unmapped value");
251 // Already predicted.
254 // Do the actual prediction.
255 IDPair
.second
= true;
256 if (!V
->use_empty() && std::next(V
->use_begin()) != V
->use_end())
257 predictValueUseListOrderImpl(V
, F
, IDPair
.first
, OM
, Stack
);
259 // Recursive descent into constants.
260 if (const Constant
*C
= dyn_cast
<Constant
>(V
))
261 if (C
->getNumOperands()) // Visit GlobalValues.
262 for (const Value
*Op
: C
->operands())
263 if (isa
<Constant
>(Op
)) // Visit GlobalValues.
264 predictValueUseListOrder(Op
, F
, OM
, Stack
);
267 static UseListOrderStack
predictUseListOrder(const Module
*M
) {
268 OrderMap OM
= orderModule(M
);
270 // Use-list orders need to be serialized after all the users have been added
271 // to a value, or else the shuffles will be incomplete. Store them per
272 // function in a stack.
274 // Aside from function order, the order of values doesn't matter much here.
275 UseListOrderStack Stack
;
277 // We want to visit the functions backward now so we can list function-local
278 // constants in the last Function they're used in. Module-level constants
279 // have already been visited above.
280 for (const Function
&F
: make_range(M
->rbegin(), M
->rend())) {
281 if (F
.isDeclaration())
283 for (const BasicBlock
&BB
: F
)
284 predictValueUseListOrder(&BB
, &F
, OM
, Stack
);
285 for (const Argument
&A
: F
.args())
286 predictValueUseListOrder(&A
, &F
, OM
, Stack
);
287 for (const BasicBlock
&BB
: F
)
288 for (const Instruction
&I
: BB
)
289 for (const Value
*Op
: I
.operands())
290 if (isa
<Constant
>(*Op
) || isa
<InlineAsm
>(*Op
)) // Visit GlobalValues.
291 predictValueUseListOrder(Op
, &F
, OM
, Stack
);
292 for (const BasicBlock
&BB
: F
)
293 for (const Instruction
&I
: BB
)
294 predictValueUseListOrder(&I
, &F
, OM
, Stack
);
297 // Visit globals last.
298 for (const GlobalVariable
&G
: M
->globals())
299 predictValueUseListOrder(&G
, nullptr, OM
, Stack
);
300 for (const Function
&F
: *M
)
301 predictValueUseListOrder(&F
, nullptr, OM
, Stack
);
302 for (const GlobalAlias
&A
: M
->aliases())
303 predictValueUseListOrder(&A
, nullptr, OM
, Stack
);
304 for (const GlobalIFunc
&I
: M
->ifuncs())
305 predictValueUseListOrder(&I
, nullptr, OM
, Stack
);
306 for (const GlobalVariable
&G
: M
->globals())
307 if (G
.hasInitializer())
308 predictValueUseListOrder(G
.getInitializer(), nullptr, OM
, Stack
);
309 for (const GlobalAlias
&A
: M
->aliases())
310 predictValueUseListOrder(A
.getAliasee(), nullptr, OM
, Stack
);
311 for (const GlobalIFunc
&I
: M
->ifuncs())
312 predictValueUseListOrder(I
.getResolver(), nullptr, OM
, Stack
);
313 for (const Function
&F
: *M
)
314 for (const Use
&U
: F
.operands())
315 predictValueUseListOrder(U
.get(), nullptr, OM
, Stack
);
320 static const Module
*getModuleFromVal(const Value
*V
) {
321 if (const Argument
*MA
= dyn_cast
<Argument
>(V
))
322 return MA
->getParent() ? MA
->getParent()->getParent() : nullptr;
324 if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
))
325 return BB
->getParent() ? BB
->getParent()->getParent() : nullptr;
327 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
328 const Function
*M
= I
->getParent() ? I
->getParent()->getParent() : nullptr;
329 return M
? M
->getParent() : nullptr;
332 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
))
333 return GV
->getParent();
335 if (const auto *MAV
= dyn_cast
<MetadataAsValue
>(V
)) {
336 for (const User
*U
: MAV
->users())
337 if (isa
<Instruction
>(U
))
338 if (const Module
*M
= getModuleFromVal(U
))
346 static void PrintCallingConv(unsigned cc
, raw_ostream
&Out
) {
348 default: Out
<< "cc" << cc
; break;
349 case CallingConv::Fast
: Out
<< "fastcc"; break;
350 case CallingConv::Cold
: Out
<< "coldcc"; break;
351 case CallingConv::WebKit_JS
: Out
<< "webkit_jscc"; break;
352 case CallingConv::AnyReg
: Out
<< "anyregcc"; break;
353 case CallingConv::PreserveMost
: Out
<< "preserve_mostcc"; break;
354 case CallingConv::PreserveAll
: Out
<< "preserve_allcc"; break;
355 case CallingConv::CXX_FAST_TLS
: Out
<< "cxx_fast_tlscc"; break;
356 case CallingConv::GHC
: Out
<< "ghccc"; break;
357 case CallingConv::X86_StdCall
: Out
<< "x86_stdcallcc"; break;
358 case CallingConv::X86_FastCall
: Out
<< "x86_fastcallcc"; break;
359 case CallingConv::X86_ThisCall
: Out
<< "x86_thiscallcc"; break;
360 case CallingConv::X86_RegCall
: Out
<< "x86_regcallcc"; break;
361 case CallingConv::X86_VectorCall
:Out
<< "x86_vectorcallcc"; break;
362 case CallingConv::Intel_OCL_BI
: Out
<< "intel_ocl_bicc"; break;
363 case CallingConv::ARM_APCS
: Out
<< "arm_apcscc"; break;
364 case CallingConv::ARM_AAPCS
: Out
<< "arm_aapcscc"; break;
365 case CallingConv::ARM_AAPCS_VFP
: Out
<< "arm_aapcs_vfpcc"; break;
366 case CallingConv::AArch64_VectorCall
: Out
<< "aarch64_vector_pcs"; break;
367 case CallingConv::MSP430_INTR
: Out
<< "msp430_intrcc"; break;
368 case CallingConv::AVR_INTR
: Out
<< "avr_intrcc "; break;
369 case CallingConv::AVR_SIGNAL
: Out
<< "avr_signalcc "; break;
370 case CallingConv::PTX_Kernel
: Out
<< "ptx_kernel"; break;
371 case CallingConv::PTX_Device
: Out
<< "ptx_device"; break;
372 case CallingConv::X86_64_SysV
: Out
<< "x86_64_sysvcc"; break;
373 case CallingConv::Win64
: Out
<< "win64cc"; break;
374 case CallingConv::SPIR_FUNC
: Out
<< "spir_func"; break;
375 case CallingConv::SPIR_KERNEL
: Out
<< "spir_kernel"; break;
376 case CallingConv::Swift
: Out
<< "swiftcc"; break;
377 case CallingConv::X86_INTR
: Out
<< "x86_intrcc"; break;
378 case CallingConv::HHVM
: Out
<< "hhvmcc"; break;
379 case CallingConv::HHVM_C
: Out
<< "hhvm_ccc"; break;
380 case CallingConv::AMDGPU_VS
: Out
<< "amdgpu_vs"; break;
381 case CallingConv::AMDGPU_LS
: Out
<< "amdgpu_ls"; break;
382 case CallingConv::AMDGPU_HS
: Out
<< "amdgpu_hs"; break;
383 case CallingConv::AMDGPU_ES
: Out
<< "amdgpu_es"; break;
384 case CallingConv::AMDGPU_GS
: Out
<< "amdgpu_gs"; break;
385 case CallingConv::AMDGPU_PS
: Out
<< "amdgpu_ps"; break;
386 case CallingConv::AMDGPU_CS
: Out
<< "amdgpu_cs"; break;
387 case CallingConv::AMDGPU_KERNEL
: Out
<< "amdgpu_kernel"; break;
399 void llvm::printLLVMNameWithoutPrefix(raw_ostream
&OS
, StringRef Name
) {
400 assert(!Name
.empty() && "Cannot get empty name!");
402 // Scan the name to see if it needs quotes first.
403 bool NeedsQuotes
= isdigit(static_cast<unsigned char>(Name
[0]));
405 for (unsigned i
= 0, e
= Name
.size(); i
!= e
; ++i
) {
406 // By making this unsigned, the value passed in to isalnum will always be
407 // in the range 0-255. This is important when building with MSVC because
408 // its implementation will assert. This situation can arise when dealing
409 // with UTF-8 multibyte characters.
410 unsigned char C
= Name
[i
];
411 if (!isalnum(static_cast<unsigned char>(C
)) && C
!= '-' && C
!= '.' &&
419 // If we didn't need any quotes, just write out the name in one blast.
425 // Okay, we need quotes. Output the quotes and escape any scary characters as
428 printEscapedString(Name
, OS
);
432 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
433 /// (if the string only contains simple characters) or is surrounded with ""'s
434 /// (if it has special chars in it). Print it out.
435 static void PrintLLVMName(raw_ostream
&OS
, StringRef Name
, PrefixType Prefix
) {
451 printLLVMNameWithoutPrefix(OS
, Name
);
454 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
455 /// (if the string only contains simple characters) or is surrounded with ""'s
456 /// (if it has special chars in it). Print it out.
457 static void PrintLLVMName(raw_ostream
&OS
, const Value
*V
) {
458 PrintLLVMName(OS
, V
->getName(),
459 isa
<GlobalValue
>(V
) ? GlobalPrefix
: LocalPrefix
);
466 TypePrinting(const Module
*M
= nullptr) : DeferredM(M
) {}
468 TypePrinting(const TypePrinting
&) = delete;
469 TypePrinting
&operator=(const TypePrinting
&) = delete;
471 /// The named types that are used by the current module.
472 TypeFinder
&getNamedTypes();
474 /// The numbered types, number to type mapping.
475 std::vector
<StructType
*> &getNumberedTypes();
479 void print(Type
*Ty
, raw_ostream
&OS
);
481 void printStructBody(StructType
*Ty
, raw_ostream
&OS
);
484 void incorporateTypes();
486 /// A module to process lazily when needed. Set to nullptr as soon as used.
487 const Module
*DeferredM
;
489 TypeFinder NamedTypes
;
491 // The numbered types, along with their value.
492 DenseMap
<StructType
*, unsigned> Type2Number
;
494 std::vector
<StructType
*> NumberedTypes
;
497 } // end anonymous namespace
499 TypeFinder
&TypePrinting::getNamedTypes() {
504 std::vector
<StructType
*> &TypePrinting::getNumberedTypes() {
507 // We know all the numbers that each type is used and we know that it is a
508 // dense assignment. Convert the map to an index table, if it's not done
509 // already (judging from the sizes):
510 if (NumberedTypes
.size() == Type2Number
.size())
511 return NumberedTypes
;
513 NumberedTypes
.resize(Type2Number
.size());
514 for (const auto &P
: Type2Number
) {
515 assert(P
.second
< NumberedTypes
.size() && "Didn't get a dense numbering?");
516 assert(!NumberedTypes
[P
.second
] && "Didn't get a unique numbering?");
517 NumberedTypes
[P
.second
] = P
.first
;
519 return NumberedTypes
;
522 bool TypePrinting::empty() {
524 return NamedTypes
.empty() && Type2Number
.empty();
527 void TypePrinting::incorporateTypes() {
531 NamedTypes
.run(*DeferredM
, false);
534 // The list of struct types we got back includes all the struct types, split
535 // the unnamed ones out to a numbering and remove the anonymous structs.
536 unsigned NextNumber
= 0;
538 std::vector
<StructType
*>::iterator NextToUse
= NamedTypes
.begin(), I
, E
;
539 for (I
= NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
) {
540 StructType
*STy
= *I
;
542 // Ignore anonymous types.
543 if (STy
->isLiteral())
546 if (STy
->getName().empty())
547 Type2Number
[STy
] = NextNumber
++;
552 NamedTypes
.erase(NextToUse
, NamedTypes
.end());
555 /// Write the specified type to the specified raw_ostream, making use of type
556 /// names or up references to shorten the type name where possible.
557 void TypePrinting::print(Type
*Ty
, raw_ostream
&OS
) {
558 switch (Ty
->getTypeID()) {
559 case Type::VoidTyID
: OS
<< "void"; return;
560 case Type::HalfTyID
: OS
<< "half"; return;
561 case Type::FloatTyID
: OS
<< "float"; return;
562 case Type::DoubleTyID
: OS
<< "double"; return;
563 case Type::X86_FP80TyID
: OS
<< "x86_fp80"; return;
564 case Type::FP128TyID
: OS
<< "fp128"; return;
565 case Type::PPC_FP128TyID
: OS
<< "ppc_fp128"; return;
566 case Type::LabelTyID
: OS
<< "label"; return;
567 case Type::MetadataTyID
: OS
<< "metadata"; return;
568 case Type::X86_MMXTyID
: OS
<< "x86_mmx"; return;
569 case Type::TokenTyID
: OS
<< "token"; return;
570 case Type::IntegerTyID
:
571 OS
<< 'i' << cast
<IntegerType
>(Ty
)->getBitWidth();
574 case Type::FunctionTyID
: {
575 FunctionType
*FTy
= cast
<FunctionType
>(Ty
);
576 print(FTy
->getReturnType(), OS
);
578 for (FunctionType::param_iterator I
= FTy
->param_begin(),
579 E
= FTy
->param_end(); I
!= E
; ++I
) {
580 if (I
!= FTy
->param_begin())
584 if (FTy
->isVarArg()) {
585 if (FTy
->getNumParams()) OS
<< ", ";
591 case Type::StructTyID
: {
592 StructType
*STy
= cast
<StructType
>(Ty
);
594 if (STy
->isLiteral())
595 return printStructBody(STy
, OS
);
597 if (!STy
->getName().empty())
598 return PrintLLVMName(OS
, STy
->getName(), LocalPrefix
);
601 const auto I
= Type2Number
.find(STy
);
602 if (I
!= Type2Number
.end())
603 OS
<< '%' << I
->second
;
604 else // Not enumerated, print the hex address.
605 OS
<< "%\"type " << STy
<< '\"';
608 case Type::PointerTyID
: {
609 PointerType
*PTy
= cast
<PointerType
>(Ty
);
610 print(PTy
->getElementType(), OS
);
611 if (unsigned AddressSpace
= PTy
->getAddressSpace())
612 OS
<< " addrspace(" << AddressSpace
<< ')';
616 case Type::ArrayTyID
: {
617 ArrayType
*ATy
= cast
<ArrayType
>(Ty
);
618 OS
<< '[' << ATy
->getNumElements() << " x ";
619 print(ATy
->getElementType(), OS
);
623 case Type::VectorTyID
: {
624 VectorType
*PTy
= cast
<VectorType
>(Ty
);
625 OS
<< "<" << PTy
->getNumElements() << " x ";
626 print(PTy
->getElementType(), OS
);
631 llvm_unreachable("Invalid TypeID");
634 void TypePrinting::printStructBody(StructType
*STy
, raw_ostream
&OS
) {
635 if (STy
->isOpaque()) {
643 if (STy
->getNumElements() == 0) {
646 StructType::element_iterator I
= STy
->element_begin();
649 for (StructType::element_iterator E
= STy
->element_end(); I
!= E
; ++I
) {
662 //===----------------------------------------------------------------------===//
663 // SlotTracker Class: Enumerate slot numbers for unnamed values
664 //===----------------------------------------------------------------------===//
665 /// This class provides computation of slot numbers for LLVM Assembly writing.
669 /// ValueMap - A mapping of Values to slot numbers.
670 using ValueMap
= DenseMap
<const Value
*, unsigned>;
673 /// TheModule - The module for which we are holding slot numbers.
674 const Module
* TheModule
;
676 /// TheFunction - The function for which we are holding slot numbers.
677 const Function
* TheFunction
= nullptr;
678 bool FunctionProcessed
= false;
679 bool ShouldInitializeAllMetadata
;
681 /// The summary index for which we are holding slot numbers.
682 const ModuleSummaryIndex
*TheIndex
= nullptr;
684 /// mMap - The slot map for the module level data.
688 /// fMap - The slot map for the function level data.
692 /// mdnMap - Map for MDNodes.
693 DenseMap
<const MDNode
*, unsigned> mdnMap
;
694 unsigned mdnNext
= 0;
696 /// asMap - The slot map for attribute sets.
697 DenseMap
<AttributeSet
, unsigned> asMap
;
700 /// ModulePathMap - The slot map for Module paths used in the summary index.
701 StringMap
<unsigned> ModulePathMap
;
702 unsigned ModulePathNext
= 0;
704 /// GUIDMap - The slot map for GUIDs used in the summary index.
705 DenseMap
<GlobalValue::GUID
, unsigned> GUIDMap
;
706 unsigned GUIDNext
= 0;
708 /// TypeIdMap - The slot map for type ids used in the summary index.
709 StringMap
<unsigned> TypeIdMap
;
710 unsigned TypeIdNext
= 0;
713 /// Construct from a module.
715 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
716 /// functions, giving correct numbering for metadata referenced only from
717 /// within a function (even if no functions have been initialized).
718 explicit SlotTracker(const Module
*M
,
719 bool ShouldInitializeAllMetadata
= false);
721 /// Construct from a function, starting out in incorp state.
723 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
724 /// functions, giving correct numbering for metadata referenced only from
725 /// within a function (even if no functions have been initialized).
726 explicit SlotTracker(const Function
*F
,
727 bool ShouldInitializeAllMetadata
= false);
729 /// Construct from a module summary index.
730 explicit SlotTracker(const ModuleSummaryIndex
*Index
);
732 SlotTracker(const SlotTracker
&) = delete;
733 SlotTracker
&operator=(const SlotTracker
&) = delete;
735 /// Return the slot number of the specified value in it's type
736 /// plane. If something is not in the SlotTracker, return -1.
737 int getLocalSlot(const Value
*V
);
738 int getGlobalSlot(const GlobalValue
*V
);
739 int getMetadataSlot(const MDNode
*N
);
740 int getAttributeGroupSlot(AttributeSet AS
);
741 int getModulePathSlot(StringRef Path
);
742 int getGUIDSlot(GlobalValue::GUID GUID
);
743 int getTypeIdSlot(StringRef Id
);
745 /// If you'd like to deal with a function instead of just a module, use
746 /// this method to get its data into the SlotTracker.
747 void incorporateFunction(const Function
*F
) {
749 FunctionProcessed
= false;
752 const Function
*getFunction() const { return TheFunction
; }
754 /// After calling incorporateFunction, use this method to remove the
755 /// most recently incorporated function from the SlotTracker. This
756 /// will reset the state of the machine back to just the module contents.
757 void purgeFunction();
759 /// MDNode map iterators.
760 using mdn_iterator
= DenseMap
<const MDNode
*, unsigned>::iterator
;
762 mdn_iterator
mdn_begin() { return mdnMap
.begin(); }
763 mdn_iterator
mdn_end() { return mdnMap
.end(); }
764 unsigned mdn_size() const { return mdnMap
.size(); }
765 bool mdn_empty() const { return mdnMap
.empty(); }
767 /// AttributeSet map iterators.
768 using as_iterator
= DenseMap
<AttributeSet
, unsigned>::iterator
;
770 as_iterator
as_begin() { return asMap
.begin(); }
771 as_iterator
as_end() { return asMap
.end(); }
772 unsigned as_size() const { return asMap
.size(); }
773 bool as_empty() const { return asMap
.empty(); }
775 /// GUID map iterators.
776 using guid_iterator
= DenseMap
<GlobalValue::GUID
, unsigned>::iterator
;
778 /// These functions do the actual initialization.
779 inline void initializeIfNeeded();
780 void initializeIndexIfNeeded();
782 // Implementation Details
784 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
785 void CreateModuleSlot(const GlobalValue
*V
);
787 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
788 void CreateMetadataSlot(const MDNode
*N
);
790 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
791 void CreateFunctionSlot(const Value
*V
);
793 /// Insert the specified AttributeSet into the slot table.
794 void CreateAttributeSetSlot(AttributeSet AS
);
796 inline void CreateModulePathSlot(StringRef Path
);
797 void CreateGUIDSlot(GlobalValue::GUID GUID
);
798 void CreateTypeIdSlot(StringRef Id
);
800 /// Add all of the module level global variables (and their initializers)
801 /// and function declarations, but not the contents of those functions.
802 void processModule();
805 /// Add all of the functions arguments, basic blocks, and instructions.
806 void processFunction();
808 /// Add the metadata directly attached to a GlobalObject.
809 void processGlobalObjectMetadata(const GlobalObject
&GO
);
811 /// Add all of the metadata from a function.
812 void processFunctionMetadata(const Function
&F
);
814 /// Add all of the metadata from an instruction.
815 void processInstructionMetadata(const Instruction
&I
);
818 } // end namespace llvm
820 ModuleSlotTracker::ModuleSlotTracker(SlotTracker
&Machine
, const Module
*M
,
822 : M(M
), F(F
), Machine(&Machine
) {}
824 ModuleSlotTracker::ModuleSlotTracker(const Module
*M
,
825 bool ShouldInitializeAllMetadata
)
826 : ShouldCreateStorage(M
),
827 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata
), M(M
) {}
829 ModuleSlotTracker::~ModuleSlotTracker() = default;
831 SlotTracker
*ModuleSlotTracker::getMachine() {
832 if (!ShouldCreateStorage
)
835 ShouldCreateStorage
= false;
837 llvm::make_unique
<SlotTracker
>(M
, ShouldInitializeAllMetadata
);
838 Machine
= MachineStorage
.get();
842 void ModuleSlotTracker::incorporateFunction(const Function
&F
) {
843 // Using getMachine() may lazily create the slot tracker.
847 // Nothing to do if this is the right function already.
851 Machine
->purgeFunction();
852 Machine
->incorporateFunction(&F
);
856 int ModuleSlotTracker::getLocalSlot(const Value
*V
) {
857 assert(F
&& "No function incorporated");
858 return Machine
->getLocalSlot(V
);
861 static SlotTracker
*createSlotTracker(const Value
*V
) {
862 if (const Argument
*FA
= dyn_cast
<Argument
>(V
))
863 return new SlotTracker(FA
->getParent());
865 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
))
867 return new SlotTracker(I
->getParent()->getParent());
869 if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
))
870 return new SlotTracker(BB
->getParent());
872 if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(V
))
873 return new SlotTracker(GV
->getParent());
875 if (const GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(V
))
876 return new SlotTracker(GA
->getParent());
878 if (const GlobalIFunc
*GIF
= dyn_cast
<GlobalIFunc
>(V
))
879 return new SlotTracker(GIF
->getParent());
881 if (const Function
*Func
= dyn_cast
<Function
>(V
))
882 return new SlotTracker(Func
);
888 #define ST_DEBUG(X) dbgs() << X
893 // Module level constructor. Causes the contents of the Module (sans functions)
894 // to be added to the slot table.
895 SlotTracker::SlotTracker(const Module
*M
, bool ShouldInitializeAllMetadata
)
896 : TheModule(M
), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata
) {}
898 // Function level constructor. Causes the contents of the Module and the one
899 // function provided to be added to the slot table.
900 SlotTracker::SlotTracker(const Function
*F
, bool ShouldInitializeAllMetadata
)
901 : TheModule(F
? F
->getParent() : nullptr), TheFunction(F
),
902 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata
) {}
904 SlotTracker::SlotTracker(const ModuleSummaryIndex
*Index
)
905 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index
) {}
907 inline void SlotTracker::initializeIfNeeded() {
910 TheModule
= nullptr; ///< Prevent re-processing next time we're called.
913 if (TheFunction
&& !FunctionProcessed
)
917 void SlotTracker::initializeIndexIfNeeded() {
921 TheIndex
= nullptr; ///< Prevent re-processing next time we're called.
924 // Iterate through all the global variables, functions, and global
925 // variable initializers and create slots for them.
926 void SlotTracker::processModule() {
927 ST_DEBUG("begin processModule!\n");
929 // Add all of the unnamed global variables to the value table.
930 for (const GlobalVariable
&Var
: TheModule
->globals()) {
932 CreateModuleSlot(&Var
);
933 processGlobalObjectMetadata(Var
);
934 auto Attrs
= Var
.getAttributes();
935 if (Attrs
.hasAttributes())
936 CreateAttributeSetSlot(Attrs
);
939 for (const GlobalAlias
&A
: TheModule
->aliases()) {
941 CreateModuleSlot(&A
);
944 for (const GlobalIFunc
&I
: TheModule
->ifuncs()) {
946 CreateModuleSlot(&I
);
949 // Add metadata used by named metadata.
950 for (const NamedMDNode
&NMD
: TheModule
->named_metadata()) {
951 for (unsigned i
= 0, e
= NMD
.getNumOperands(); i
!= e
; ++i
)
952 CreateMetadataSlot(NMD
.getOperand(i
));
955 for (const Function
&F
: *TheModule
) {
957 // Add all the unnamed functions to the table.
958 CreateModuleSlot(&F
);
960 if (ShouldInitializeAllMetadata
)
961 processFunctionMetadata(F
);
963 // Add all the function attributes to the table.
964 // FIXME: Add attributes of other objects?
965 AttributeSet FnAttrs
= F
.getAttributes().getFnAttributes();
966 if (FnAttrs
.hasAttributes())
967 CreateAttributeSetSlot(FnAttrs
);
970 ST_DEBUG("end processModule!\n");
973 // Process the arguments, basic blocks, and instructions of a function.
974 void SlotTracker::processFunction() {
975 ST_DEBUG("begin processFunction!\n");
978 // Process function metadata if it wasn't hit at the module-level.
979 if (!ShouldInitializeAllMetadata
)
980 processFunctionMetadata(*TheFunction
);
982 // Add all the function arguments with no names.
983 for(Function::const_arg_iterator AI
= TheFunction
->arg_begin(),
984 AE
= TheFunction
->arg_end(); AI
!= AE
; ++AI
)
986 CreateFunctionSlot(&*AI
);
988 ST_DEBUG("Inserting Instructions:\n");
990 // Add all of the basic blocks and instructions with no names.
991 for (auto &BB
: *TheFunction
) {
993 CreateFunctionSlot(&BB
);
996 if (!I
.getType()->isVoidTy() && !I
.hasName())
997 CreateFunctionSlot(&I
);
999 // We allow direct calls to any llvm.foo function here, because the
1000 // target may not be linked into the optimizer.
1001 if (auto CS
= ImmutableCallSite(&I
)) {
1002 // Add all the call attributes to the table.
1003 AttributeSet Attrs
= CS
.getAttributes().getFnAttributes();
1004 if (Attrs
.hasAttributes())
1005 CreateAttributeSetSlot(Attrs
);
1010 FunctionProcessed
= true;
1012 ST_DEBUG("end processFunction!\n");
1015 // Iterate through all the GUID in the index and create slots for them.
1016 void SlotTracker::processIndex() {
1017 ST_DEBUG("begin processIndex!\n");
1020 // The first block of slots are just the module ids, which start at 0 and are
1021 // assigned consecutively. Since the StringMap iteration order isn't
1022 // guaranteed, use a std::map to order by module ID before assigning slots.
1023 std::map
<uint64_t, StringRef
> ModuleIdToPathMap
;
1024 for (auto &ModPath
: TheIndex
->modulePaths())
1025 ModuleIdToPathMap
[ModPath
.second
.first
] = ModPath
.first();
1026 for (auto &ModPair
: ModuleIdToPathMap
)
1027 CreateModulePathSlot(ModPair
.second
);
1029 // Start numbering the GUIDs after the module ids.
1030 GUIDNext
= ModulePathNext
;
1032 for (auto &GlobalList
: *TheIndex
)
1033 CreateGUIDSlot(GlobalList
.first
);
1035 // Start numbering the TypeIds after the GUIDs.
1036 TypeIdNext
= GUIDNext
;
1038 for (auto TidIter
= TheIndex
->typeIds().begin();
1039 TidIter
!= TheIndex
->typeIds().end(); TidIter
++)
1040 CreateTypeIdSlot(TidIter
->second
.first
);
1042 ST_DEBUG("end processIndex!\n");
1045 void SlotTracker::processGlobalObjectMetadata(const GlobalObject
&GO
) {
1046 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
1047 GO
.getAllMetadata(MDs
);
1048 for (auto &MD
: MDs
)
1049 CreateMetadataSlot(MD
.second
);
1052 void SlotTracker::processFunctionMetadata(const Function
&F
) {
1053 processGlobalObjectMetadata(F
);
1054 for (auto &BB
: F
) {
1056 processInstructionMetadata(I
);
1060 void SlotTracker::processInstructionMetadata(const Instruction
&I
) {
1061 // Process metadata used directly by intrinsics.
1062 if (const CallInst
*CI
= dyn_cast
<CallInst
>(&I
))
1063 if (Function
*F
= CI
->getCalledFunction())
1064 if (F
->isIntrinsic())
1065 for (auto &Op
: I
.operands())
1066 if (auto *V
= dyn_cast_or_null
<MetadataAsValue
>(Op
))
1067 if (MDNode
*N
= dyn_cast
<MDNode
>(V
->getMetadata()))
1068 CreateMetadataSlot(N
);
1070 // Process metadata attached to this instruction.
1071 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
1072 I
.getAllMetadata(MDs
);
1073 for (auto &MD
: MDs
)
1074 CreateMetadataSlot(MD
.second
);
1077 /// Clean up after incorporating a function. This is the only way to get out of
1078 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1079 /// incorporation state is indicated by TheFunction != 0.
1080 void SlotTracker::purgeFunction() {
1081 ST_DEBUG("begin purgeFunction!\n");
1082 fMap
.clear(); // Simply discard the function level map
1083 TheFunction
= nullptr;
1084 FunctionProcessed
= false;
1085 ST_DEBUG("end purgeFunction!\n");
1088 /// getGlobalSlot - Get the slot number of a global value.
1089 int SlotTracker::getGlobalSlot(const GlobalValue
*V
) {
1090 // Check for uninitialized state and do lazy initialization.
1091 initializeIfNeeded();
1093 // Find the value in the module map
1094 ValueMap::iterator MI
= mMap
.find(V
);
1095 return MI
== mMap
.end() ? -1 : (int)MI
->second
;
1098 /// getMetadataSlot - Get the slot number of a MDNode.
1099 int SlotTracker::getMetadataSlot(const MDNode
*N
) {
1100 // Check for uninitialized state and do lazy initialization.
1101 initializeIfNeeded();
1103 // Find the MDNode in the module map
1104 mdn_iterator MI
= mdnMap
.find(N
);
1105 return MI
== mdnMap
.end() ? -1 : (int)MI
->second
;
1108 /// getLocalSlot - Get the slot number for a value that is local to a function.
1109 int SlotTracker::getLocalSlot(const Value
*V
) {
1110 assert(!isa
<Constant
>(V
) && "Can't get a constant or global slot with this!");
1112 // Check for uninitialized state and do lazy initialization.
1113 initializeIfNeeded();
1115 ValueMap::iterator FI
= fMap
.find(V
);
1116 return FI
== fMap
.end() ? -1 : (int)FI
->second
;
1119 int SlotTracker::getAttributeGroupSlot(AttributeSet AS
) {
1120 // Check for uninitialized state and do lazy initialization.
1121 initializeIfNeeded();
1123 // Find the AttributeSet in the module map.
1124 as_iterator AI
= asMap
.find(AS
);
1125 return AI
== asMap
.end() ? -1 : (int)AI
->second
;
1128 int SlotTracker::getModulePathSlot(StringRef Path
) {
1129 // Check for uninitialized state and do lazy initialization.
1130 initializeIndexIfNeeded();
1132 // Find the Module path in the map
1133 auto I
= ModulePathMap
.find(Path
);
1134 return I
== ModulePathMap
.end() ? -1 : (int)I
->second
;
1137 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID
) {
1138 // Check for uninitialized state and do lazy initialization.
1139 initializeIndexIfNeeded();
1141 // Find the GUID in the map
1142 guid_iterator I
= GUIDMap
.find(GUID
);
1143 return I
== GUIDMap
.end() ? -1 : (int)I
->second
;
1146 int SlotTracker::getTypeIdSlot(StringRef Id
) {
1147 // Check for uninitialized state and do lazy initialization.
1148 initializeIndexIfNeeded();
1150 // Find the TypeId string in the map
1151 auto I
= TypeIdMap
.find(Id
);
1152 return I
== TypeIdMap
.end() ? -1 : (int)I
->second
;
1155 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1156 void SlotTracker::CreateModuleSlot(const GlobalValue
*V
) {
1157 assert(V
&& "Can't insert a null Value into SlotTracker!");
1158 assert(!V
->getType()->isVoidTy() && "Doesn't need a slot!");
1159 assert(!V
->hasName() && "Doesn't need a slot!");
1161 unsigned DestSlot
= mNext
++;
1164 ST_DEBUG(" Inserting value [" << V
->getType() << "] = " << V
<< " slot=" <<
1166 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1167 ST_DEBUG((isa
<GlobalVariable
>(V
) ? 'G' :
1168 (isa
<Function
>(V
) ? 'F' :
1169 (isa
<GlobalAlias
>(V
) ? 'A' :
1170 (isa
<GlobalIFunc
>(V
) ? 'I' : 'o')))) << "]\n");
1173 /// CreateSlot - Create a new slot for the specified value if it has no name.
1174 void SlotTracker::CreateFunctionSlot(const Value
*V
) {
1175 assert(!V
->getType()->isVoidTy() && !V
->hasName() && "Doesn't need a slot!");
1177 unsigned DestSlot
= fNext
++;
1180 // G = Global, F = Function, o = other
1181 ST_DEBUG(" Inserting value [" << V
->getType() << "] = " << V
<< " slot=" <<
1182 DestSlot
<< " [o]\n");
1185 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1186 void SlotTracker::CreateMetadataSlot(const MDNode
*N
) {
1187 assert(N
&& "Can't insert a null Value into SlotTracker!");
1189 // Don't make slots for DIExpressions. We just print them inline everywhere.
1190 if (isa
<DIExpression
>(N
))
1193 unsigned DestSlot
= mdnNext
;
1194 if (!mdnMap
.insert(std::make_pair(N
, DestSlot
)).second
)
1198 // Recursively add any MDNodes referenced by operands.
1199 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
)
1200 if (const MDNode
*Op
= dyn_cast_or_null
<MDNode
>(N
->getOperand(i
)))
1201 CreateMetadataSlot(Op
);
1204 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS
) {
1205 assert(AS
.hasAttributes() && "Doesn't need a slot!");
1207 as_iterator I
= asMap
.find(AS
);
1208 if (I
!= asMap
.end())
1211 unsigned DestSlot
= asNext
++;
1212 asMap
[AS
] = DestSlot
;
1215 /// Create a new slot for the specified Module
1216 void SlotTracker::CreateModulePathSlot(StringRef Path
) {
1217 ModulePathMap
[Path
] = ModulePathNext
++;
1220 /// Create a new slot for the specified GUID
1221 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID
) {
1222 GUIDMap
[GUID
] = GUIDNext
++;
1225 /// Create a new slot for the specified Id
1226 void SlotTracker::CreateTypeIdSlot(StringRef Id
) {
1227 TypeIdMap
[Id
] = TypeIdNext
++;
1230 //===----------------------------------------------------------------------===//
1231 // AsmWriter Implementation
1232 //===----------------------------------------------------------------------===//
1234 static void WriteAsOperandInternal(raw_ostream
&Out
, const Value
*V
,
1235 TypePrinting
*TypePrinter
,
1236 SlotTracker
*Machine
,
1237 const Module
*Context
);
1239 static void WriteAsOperandInternal(raw_ostream
&Out
, const Metadata
*MD
,
1240 TypePrinting
*TypePrinter
,
1241 SlotTracker
*Machine
, const Module
*Context
,
1242 bool FromValue
= false);
1244 static void WriteOptimizationInfo(raw_ostream
&Out
, const User
*U
) {
1245 if (const FPMathOperator
*FPO
= dyn_cast
<const FPMathOperator
>(U
)) {
1246 // 'Fast' is an abbreviation for all fast-math-flags.
1250 if (FPO
->hasAllowReassoc())
1252 if (FPO
->hasNoNaNs())
1254 if (FPO
->hasNoInfs())
1256 if (FPO
->hasNoSignedZeros())
1258 if (FPO
->hasAllowReciprocal())
1260 if (FPO
->hasAllowContract())
1262 if (FPO
->hasApproxFunc())
1267 if (const OverflowingBinaryOperator
*OBO
=
1268 dyn_cast
<OverflowingBinaryOperator
>(U
)) {
1269 if (OBO
->hasNoUnsignedWrap())
1271 if (OBO
->hasNoSignedWrap())
1273 } else if (const PossiblyExactOperator
*Div
=
1274 dyn_cast
<PossiblyExactOperator
>(U
)) {
1277 } else if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(U
)) {
1278 if (GEP
->isInBounds())
1283 static void WriteConstantInternal(raw_ostream
&Out
, const Constant
*CV
,
1284 TypePrinting
&TypePrinter
,
1285 SlotTracker
*Machine
,
1286 const Module
*Context
) {
1287 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
1288 if (CI
->getType()->isIntegerTy(1)) {
1289 Out
<< (CI
->getZExtValue() ? "true" : "false");
1292 Out
<< CI
->getValue();
1296 if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
1297 const APFloat
&APF
= CFP
->getValueAPF();
1298 if (&APF
.getSemantics() == &APFloat::IEEEsingle() ||
1299 &APF
.getSemantics() == &APFloat::IEEEdouble()) {
1300 // We would like to output the FP constant value in exponential notation,
1301 // but we cannot do this if doing so will lose precision. Check here to
1302 // make sure that we only output it in exponential format if we can parse
1303 // the value back and get the same value.
1306 bool isDouble
= &APF
.getSemantics() == &APFloat::IEEEdouble();
1307 bool isInf
= APF
.isInfinity();
1308 bool isNaN
= APF
.isNaN();
1309 if (!isInf
&& !isNaN
) {
1310 double Val
= isDouble
? APF
.convertToDouble() : APF
.convertToFloat();
1311 SmallString
<128> StrVal
;
1312 APF
.toString(StrVal
, 6, 0, false);
1313 // Check to make sure that the stringized number is not some string like
1314 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1315 // that the string matches the "[-+]?[0-9]" regex.
1317 assert(((StrVal
[0] >= '0' && StrVal
[0] <= '9') ||
1318 ((StrVal
[0] == '-' || StrVal
[0] == '+') &&
1319 (StrVal
[1] >= '0' && StrVal
[1] <= '9'))) &&
1320 "[-+]?[0-9] regex does not match!");
1321 // Reparse stringized version!
1322 if (APFloat(APFloat::IEEEdouble(), StrVal
).convertToDouble() == Val
) {
1327 // Otherwise we could not reparse it to exactly the same value, so we must
1328 // output the string in hexadecimal format! Note that loading and storing
1329 // floating point types changes the bits of NaNs on some hosts, notably
1330 // x86, so we must not use these types.
1331 static_assert(sizeof(double) == sizeof(uint64_t),
1332 "assuming that double is 64 bits!");
1334 // Floats are represented in ASCII IR as double, convert.
1336 apf
.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven
,
1338 Out
<< format_hex(apf
.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1342 // Either half, or some form of long double.
1343 // These appear as a magic letter identifying the type, then a
1344 // fixed number of hex digits.
1346 APInt API
= APF
.bitcastToAPInt();
1347 if (&APF
.getSemantics() == &APFloat::x87DoubleExtended()) {
1349 Out
<< format_hex_no_prefix(API
.getHiBits(16).getZExtValue(), 4,
1351 Out
<< format_hex_no_prefix(API
.getLoBits(64).getZExtValue(), 16,
1354 } else if (&APF
.getSemantics() == &APFloat::IEEEquad()) {
1356 Out
<< format_hex_no_prefix(API
.getLoBits(64).getZExtValue(), 16,
1358 Out
<< format_hex_no_prefix(API
.getHiBits(64).getZExtValue(), 16,
1360 } else if (&APF
.getSemantics() == &APFloat::PPCDoubleDouble()) {
1362 Out
<< format_hex_no_prefix(API
.getLoBits(64).getZExtValue(), 16,
1364 Out
<< format_hex_no_prefix(API
.getHiBits(64).getZExtValue(), 16,
1366 } else if (&APF
.getSemantics() == &APFloat::IEEEhalf()) {
1368 Out
<< format_hex_no_prefix(API
.getZExtValue(), 4,
1371 llvm_unreachable("Unsupported floating point type");
1375 if (isa
<ConstantAggregateZero
>(CV
)) {
1376 Out
<< "zeroinitializer";
1380 if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(CV
)) {
1381 Out
<< "blockaddress(";
1382 WriteAsOperandInternal(Out
, BA
->getFunction(), &TypePrinter
, Machine
,
1385 WriteAsOperandInternal(Out
, BA
->getBasicBlock(), &TypePrinter
, Machine
,
1391 if (const ConstantArray
*CA
= dyn_cast
<ConstantArray
>(CV
)) {
1392 Type
*ETy
= CA
->getType()->getElementType();
1394 TypePrinter
.print(ETy
, Out
);
1396 WriteAsOperandInternal(Out
, CA
->getOperand(0),
1397 &TypePrinter
, Machine
,
1399 for (unsigned i
= 1, e
= CA
->getNumOperands(); i
!= e
; ++i
) {
1401 TypePrinter
.print(ETy
, Out
);
1403 WriteAsOperandInternal(Out
, CA
->getOperand(i
), &TypePrinter
, Machine
,
1410 if (const ConstantDataArray
*CA
= dyn_cast
<ConstantDataArray
>(CV
)) {
1411 // As a special case, print the array as a string if it is an array of
1412 // i8 with ConstantInt values.
1413 if (CA
->isString()) {
1415 printEscapedString(CA
->getAsString(), Out
);
1420 Type
*ETy
= CA
->getType()->getElementType();
1422 TypePrinter
.print(ETy
, Out
);
1424 WriteAsOperandInternal(Out
, CA
->getElementAsConstant(0),
1425 &TypePrinter
, Machine
,
1427 for (unsigned i
= 1, e
= CA
->getNumElements(); i
!= e
; ++i
) {
1429 TypePrinter
.print(ETy
, Out
);
1431 WriteAsOperandInternal(Out
, CA
->getElementAsConstant(i
), &TypePrinter
,
1438 if (const ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(CV
)) {
1439 if (CS
->getType()->isPacked())
1442 unsigned N
= CS
->getNumOperands();
1445 TypePrinter
.print(CS
->getOperand(0)->getType(), Out
);
1448 WriteAsOperandInternal(Out
, CS
->getOperand(0), &TypePrinter
, Machine
,
1451 for (unsigned i
= 1; i
< N
; i
++) {
1453 TypePrinter
.print(CS
->getOperand(i
)->getType(), Out
);
1456 WriteAsOperandInternal(Out
, CS
->getOperand(i
), &TypePrinter
, Machine
,
1463 if (CS
->getType()->isPacked())
1468 if (isa
<ConstantVector
>(CV
) || isa
<ConstantDataVector
>(CV
)) {
1469 Type
*ETy
= CV
->getType()->getVectorElementType();
1471 TypePrinter
.print(ETy
, Out
);
1473 WriteAsOperandInternal(Out
, CV
->getAggregateElement(0U), &TypePrinter
,
1475 for (unsigned i
= 1, e
= CV
->getType()->getVectorNumElements(); i
!= e
;++i
){
1477 TypePrinter
.print(ETy
, Out
);
1479 WriteAsOperandInternal(Out
, CV
->getAggregateElement(i
), &TypePrinter
,
1486 if (isa
<ConstantPointerNull
>(CV
)) {
1491 if (isa
<ConstantTokenNone
>(CV
)) {
1496 if (isa
<UndefValue
>(CV
)) {
1501 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
1502 Out
<< CE
->getOpcodeName();
1503 WriteOptimizationInfo(Out
, CE
);
1504 if (CE
->isCompare())
1505 Out
<< ' ' << CmpInst::getPredicateName(
1506 static_cast<CmpInst::Predicate
>(CE
->getPredicate()));
1509 Optional
<unsigned> InRangeOp
;
1510 if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(CE
)) {
1511 TypePrinter
.print(GEP
->getSourceElementType(), Out
);
1513 InRangeOp
= GEP
->getInRangeIndex();
1518 for (User::const_op_iterator OI
=CE
->op_begin(); OI
!= CE
->op_end(); ++OI
) {
1519 if (InRangeOp
&& unsigned(OI
- CE
->op_begin()) == *InRangeOp
)
1521 TypePrinter
.print((*OI
)->getType(), Out
);
1523 WriteAsOperandInternal(Out
, *OI
, &TypePrinter
, Machine
, Context
);
1524 if (OI
+1 != CE
->op_end())
1528 if (CE
->hasIndices()) {
1529 ArrayRef
<unsigned> Indices
= CE
->getIndices();
1530 for (unsigned i
= 0, e
= Indices
.size(); i
!= e
; ++i
)
1531 Out
<< ", " << Indices
[i
];
1536 TypePrinter
.print(CE
->getType(), Out
);
1543 Out
<< "<placeholder or erroneous Constant>";
1546 static void writeMDTuple(raw_ostream
&Out
, const MDTuple
*Node
,
1547 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1548 const Module
*Context
) {
1550 for (unsigned mi
= 0, me
= Node
->getNumOperands(); mi
!= me
; ++mi
) {
1551 const Metadata
*MD
= Node
->getOperand(mi
);
1554 else if (auto *MDV
= dyn_cast
<ValueAsMetadata
>(MD
)) {
1555 Value
*V
= MDV
->getValue();
1556 TypePrinter
->print(V
->getType(), Out
);
1558 WriteAsOperandInternal(Out
, V
, TypePrinter
, Machine
, Context
);
1560 WriteAsOperandInternal(Out
, MD
, TypePrinter
, Machine
, Context
);
1571 struct FieldSeparator
{
1575 FieldSeparator(const char *Sep
= ", ") : Sep(Sep
) {}
1578 raw_ostream
&operator<<(raw_ostream
&OS
, FieldSeparator
&FS
) {
1583 return OS
<< FS
.Sep
;
1586 struct MDFieldPrinter
{
1589 TypePrinting
*TypePrinter
= nullptr;
1590 SlotTracker
*Machine
= nullptr;
1591 const Module
*Context
= nullptr;
1593 explicit MDFieldPrinter(raw_ostream
&Out
) : Out(Out
) {}
1594 MDFieldPrinter(raw_ostream
&Out
, TypePrinting
*TypePrinter
,
1595 SlotTracker
*Machine
, const Module
*Context
)
1596 : Out(Out
), TypePrinter(TypePrinter
), Machine(Machine
), Context(Context
) {
1599 void printTag(const DINode
*N
);
1600 void printMacinfoType(const DIMacroNode
*N
);
1601 void printChecksum(const DIFile::ChecksumInfo
<StringRef
> &N
);
1602 void printString(StringRef Name
, StringRef Value
,
1603 bool ShouldSkipEmpty
= true);
1604 void printMetadata(StringRef Name
, const Metadata
*MD
,
1605 bool ShouldSkipNull
= true);
1606 template <class IntTy
>
1607 void printInt(StringRef Name
, IntTy Int
, bool ShouldSkipZero
= true);
1608 void printBool(StringRef Name
, bool Value
, Optional
<bool> Default
= None
);
1609 void printDIFlags(StringRef Name
, DINode::DIFlags Flags
);
1610 template <class IntTy
, class Stringifier
>
1611 void printDwarfEnum(StringRef Name
, IntTy Value
, Stringifier toString
,
1612 bool ShouldSkipZero
= true);
1613 void printEmissionKind(StringRef Name
, DICompileUnit::DebugEmissionKind EK
);
1614 void printNameTableKind(StringRef Name
,
1615 DICompileUnit::DebugNameTableKind NTK
);
1618 } // end anonymous namespace
1620 void MDFieldPrinter::printTag(const DINode
*N
) {
1621 Out
<< FS
<< "tag: ";
1622 auto Tag
= dwarf::TagString(N
->getTag());
1629 void MDFieldPrinter::printMacinfoType(const DIMacroNode
*N
) {
1630 Out
<< FS
<< "type: ";
1631 auto Type
= dwarf::MacinfoString(N
->getMacinfoType());
1635 Out
<< N
->getMacinfoType();
1638 void MDFieldPrinter::printChecksum(
1639 const DIFile::ChecksumInfo
<StringRef
> &Checksum
) {
1640 Out
<< FS
<< "checksumkind: " << Checksum
.getKindAsString();
1641 printString("checksum", Checksum
.Value
, /* ShouldSkipEmpty */ false);
1644 void MDFieldPrinter::printString(StringRef Name
, StringRef Value
,
1645 bool ShouldSkipEmpty
) {
1646 if (ShouldSkipEmpty
&& Value
.empty())
1649 Out
<< FS
<< Name
<< ": \"";
1650 printEscapedString(Value
, Out
);
1654 static void writeMetadataAsOperand(raw_ostream
&Out
, const Metadata
*MD
,
1655 TypePrinting
*TypePrinter
,
1656 SlotTracker
*Machine
,
1657 const Module
*Context
) {
1662 WriteAsOperandInternal(Out
, MD
, TypePrinter
, Machine
, Context
);
1665 void MDFieldPrinter::printMetadata(StringRef Name
, const Metadata
*MD
,
1666 bool ShouldSkipNull
) {
1667 if (ShouldSkipNull
&& !MD
)
1670 Out
<< FS
<< Name
<< ": ";
1671 writeMetadataAsOperand(Out
, MD
, TypePrinter
, Machine
, Context
);
1674 template <class IntTy
>
1675 void MDFieldPrinter::printInt(StringRef Name
, IntTy Int
, bool ShouldSkipZero
) {
1676 if (ShouldSkipZero
&& !Int
)
1679 Out
<< FS
<< Name
<< ": " << Int
;
1682 void MDFieldPrinter::printBool(StringRef Name
, bool Value
,
1683 Optional
<bool> Default
) {
1684 if (Default
&& Value
== *Default
)
1686 Out
<< FS
<< Name
<< ": " << (Value
? "true" : "false");
1689 void MDFieldPrinter::printDIFlags(StringRef Name
, DINode::DIFlags Flags
) {
1693 Out
<< FS
<< Name
<< ": ";
1695 SmallVector
<DINode::DIFlags
, 8> SplitFlags
;
1696 auto Extra
= DINode::splitFlags(Flags
, SplitFlags
);
1698 FieldSeparator
FlagsFS(" | ");
1699 for (auto F
: SplitFlags
) {
1700 auto StringF
= DINode::getFlagString(F
);
1701 assert(!StringF
.empty() && "Expected valid flag");
1702 Out
<< FlagsFS
<< StringF
;
1704 if (Extra
|| SplitFlags
.empty())
1705 Out
<< FlagsFS
<< Extra
;
1708 void MDFieldPrinter::printEmissionKind(StringRef Name
,
1709 DICompileUnit::DebugEmissionKind EK
) {
1710 Out
<< FS
<< Name
<< ": " << DICompileUnit::emissionKindString(EK
);
1713 void MDFieldPrinter::printNameTableKind(StringRef Name
,
1714 DICompileUnit::DebugNameTableKind NTK
) {
1715 if (NTK
== DICompileUnit::DebugNameTableKind::Default
)
1717 Out
<< FS
<< Name
<< ": " << DICompileUnit::nameTableKindString(NTK
);
1720 template <class IntTy
, class Stringifier
>
1721 void MDFieldPrinter::printDwarfEnum(StringRef Name
, IntTy Value
,
1722 Stringifier toString
, bool ShouldSkipZero
) {
1726 Out
<< FS
<< Name
<< ": ";
1727 auto S
= toString(Value
);
1734 static void writeGenericDINode(raw_ostream
&Out
, const GenericDINode
*N
,
1735 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1736 const Module
*Context
) {
1737 Out
<< "!GenericDINode(";
1738 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1739 Printer
.printTag(N
);
1740 Printer
.printString("header", N
->getHeader());
1741 if (N
->getNumDwarfOperands()) {
1742 Out
<< Printer
.FS
<< "operands: {";
1744 for (auto &I
: N
->dwarf_operands()) {
1746 writeMetadataAsOperand(Out
, I
, TypePrinter
, Machine
, Context
);
1753 static void writeDILocation(raw_ostream
&Out
, const DILocation
*DL
,
1754 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1755 const Module
*Context
) {
1756 Out
<< "!DILocation(";
1757 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1758 // Always output the line, since 0 is a relevant and important value for it.
1759 Printer
.printInt("line", DL
->getLine(), /* ShouldSkipZero */ false);
1760 Printer
.printInt("column", DL
->getColumn());
1761 Printer
.printMetadata("scope", DL
->getRawScope(), /* ShouldSkipNull */ false);
1762 Printer
.printMetadata("inlinedAt", DL
->getRawInlinedAt());
1763 Printer
.printBool("isImplicitCode", DL
->isImplicitCode(),
1764 /* Default */ false);
1768 static void writeDISubrange(raw_ostream
&Out
, const DISubrange
*N
,
1769 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1770 const Module
*Context
) {
1771 Out
<< "!DISubrange(";
1772 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1773 if (auto *CE
= N
->getCount().dyn_cast
<ConstantInt
*>())
1774 Printer
.printInt("count", CE
->getSExtValue(), /* ShouldSkipZero */ false);
1776 Printer
.printMetadata("count", N
->getCount().dyn_cast
<DIVariable
*>(),
1777 /*ShouldSkipNull */ false);
1778 Printer
.printInt("lowerBound", N
->getLowerBound());
1782 static void writeDIEnumerator(raw_ostream
&Out
, const DIEnumerator
*N
,
1783 TypePrinting
*, SlotTracker
*, const Module
*) {
1784 Out
<< "!DIEnumerator(";
1785 MDFieldPrinter
Printer(Out
);
1786 Printer
.printString("name", N
->getName(), /* ShouldSkipEmpty */ false);
1787 if (N
->isUnsigned()) {
1788 auto Value
= static_cast<uint64_t>(N
->getValue());
1789 Printer
.printInt("value", Value
, /* ShouldSkipZero */ false);
1790 Printer
.printBool("isUnsigned", true);
1792 Printer
.printInt("value", N
->getValue(), /* ShouldSkipZero */ false);
1797 static void writeDIBasicType(raw_ostream
&Out
, const DIBasicType
*N
,
1798 TypePrinting
*, SlotTracker
*, const Module
*) {
1799 Out
<< "!DIBasicType(";
1800 MDFieldPrinter
Printer(Out
);
1801 if (N
->getTag() != dwarf::DW_TAG_base_type
)
1802 Printer
.printTag(N
);
1803 Printer
.printString("name", N
->getName());
1804 Printer
.printInt("size", N
->getSizeInBits());
1805 Printer
.printInt("align", N
->getAlignInBits());
1806 Printer
.printDwarfEnum("encoding", N
->getEncoding(),
1807 dwarf::AttributeEncodingString
);
1808 Printer
.printDIFlags("flags", N
->getFlags());
1812 static void writeDIDerivedType(raw_ostream
&Out
, const DIDerivedType
*N
,
1813 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1814 const Module
*Context
) {
1815 Out
<< "!DIDerivedType(";
1816 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1817 Printer
.printTag(N
);
1818 Printer
.printString("name", N
->getName());
1819 Printer
.printMetadata("scope", N
->getRawScope());
1820 Printer
.printMetadata("file", N
->getRawFile());
1821 Printer
.printInt("line", N
->getLine());
1822 Printer
.printMetadata("baseType", N
->getRawBaseType(),
1823 /* ShouldSkipNull */ false);
1824 Printer
.printInt("size", N
->getSizeInBits());
1825 Printer
.printInt("align", N
->getAlignInBits());
1826 Printer
.printInt("offset", N
->getOffsetInBits());
1827 Printer
.printDIFlags("flags", N
->getFlags());
1828 Printer
.printMetadata("extraData", N
->getRawExtraData());
1829 if (const auto &DWARFAddressSpace
= N
->getDWARFAddressSpace())
1830 Printer
.printInt("dwarfAddressSpace", *DWARFAddressSpace
,
1831 /* ShouldSkipZero */ false);
1835 static void writeDICompositeType(raw_ostream
&Out
, const DICompositeType
*N
,
1836 TypePrinting
*TypePrinter
,
1837 SlotTracker
*Machine
, const Module
*Context
) {
1838 Out
<< "!DICompositeType(";
1839 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1840 Printer
.printTag(N
);
1841 Printer
.printString("name", N
->getName());
1842 Printer
.printMetadata("scope", N
->getRawScope());
1843 Printer
.printMetadata("file", N
->getRawFile());
1844 Printer
.printInt("line", N
->getLine());
1845 Printer
.printMetadata("baseType", N
->getRawBaseType());
1846 Printer
.printInt("size", N
->getSizeInBits());
1847 Printer
.printInt("align", N
->getAlignInBits());
1848 Printer
.printInt("offset", N
->getOffsetInBits());
1849 Printer
.printDIFlags("flags", N
->getFlags());
1850 Printer
.printMetadata("elements", N
->getRawElements());
1851 Printer
.printDwarfEnum("runtimeLang", N
->getRuntimeLang(),
1852 dwarf::LanguageString
);
1853 Printer
.printMetadata("vtableHolder", N
->getRawVTableHolder());
1854 Printer
.printMetadata("templateParams", N
->getRawTemplateParams());
1855 Printer
.printString("identifier", N
->getIdentifier());
1856 Printer
.printMetadata("discriminator", N
->getRawDiscriminator());
1860 static void writeDISubroutineType(raw_ostream
&Out
, const DISubroutineType
*N
,
1861 TypePrinting
*TypePrinter
,
1862 SlotTracker
*Machine
, const Module
*Context
) {
1863 Out
<< "!DISubroutineType(";
1864 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1865 Printer
.printDIFlags("flags", N
->getFlags());
1866 Printer
.printDwarfEnum("cc", N
->getCC(), dwarf::ConventionString
);
1867 Printer
.printMetadata("types", N
->getRawTypeArray(),
1868 /* ShouldSkipNull */ false);
1872 static void writeDIFile(raw_ostream
&Out
, const DIFile
*N
, TypePrinting
*,
1873 SlotTracker
*, const Module
*) {
1875 MDFieldPrinter
Printer(Out
);
1876 Printer
.printString("filename", N
->getFilename(),
1877 /* ShouldSkipEmpty */ false);
1878 Printer
.printString("directory", N
->getDirectory(),
1879 /* ShouldSkipEmpty */ false);
1880 // Print all values for checksum together, or not at all.
1881 if (N
->getChecksum())
1882 Printer
.printChecksum(*N
->getChecksum());
1883 Printer
.printString("source", N
->getSource().getValueOr(StringRef()),
1884 /* ShouldSkipEmpty */ true);
1888 static void writeDICompileUnit(raw_ostream
&Out
, const DICompileUnit
*N
,
1889 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1890 const Module
*Context
) {
1891 Out
<< "!DICompileUnit(";
1892 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1893 Printer
.printDwarfEnum("language", N
->getSourceLanguage(),
1894 dwarf::LanguageString
, /* ShouldSkipZero */ false);
1895 Printer
.printMetadata("file", N
->getRawFile(), /* ShouldSkipNull */ false);
1896 Printer
.printString("producer", N
->getProducer());
1897 Printer
.printBool("isOptimized", N
->isOptimized());
1898 Printer
.printString("flags", N
->getFlags());
1899 Printer
.printInt("runtimeVersion", N
->getRuntimeVersion(),
1900 /* ShouldSkipZero */ false);
1901 Printer
.printString("splitDebugFilename", N
->getSplitDebugFilename());
1902 Printer
.printEmissionKind("emissionKind", N
->getEmissionKind());
1903 Printer
.printMetadata("enums", N
->getRawEnumTypes());
1904 Printer
.printMetadata("retainedTypes", N
->getRawRetainedTypes());
1905 Printer
.printMetadata("globals", N
->getRawGlobalVariables());
1906 Printer
.printMetadata("imports", N
->getRawImportedEntities());
1907 Printer
.printMetadata("macros", N
->getRawMacros());
1908 Printer
.printInt("dwoId", N
->getDWOId());
1909 Printer
.printBool("splitDebugInlining", N
->getSplitDebugInlining(), true);
1910 Printer
.printBool("debugInfoForProfiling", N
->getDebugInfoForProfiling(),
1912 Printer
.printNameTableKind("nameTableKind", N
->getNameTableKind());
1916 static void writeDISubprogram(raw_ostream
&Out
, const DISubprogram
*N
,
1917 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1918 const Module
*Context
) {
1919 Out
<< "!DISubprogram(";
1920 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1921 Printer
.printString("name", N
->getName());
1922 Printer
.printString("linkageName", N
->getLinkageName());
1923 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
1924 Printer
.printMetadata("file", N
->getRawFile());
1925 Printer
.printInt("line", N
->getLine());
1926 Printer
.printMetadata("type", N
->getRawType());
1927 Printer
.printBool("isLocal", N
->isLocalToUnit());
1928 Printer
.printBool("isDefinition", N
->isDefinition());
1929 Printer
.printInt("scopeLine", N
->getScopeLine());
1930 Printer
.printMetadata("containingType", N
->getRawContainingType());
1931 Printer
.printDwarfEnum("virtuality", N
->getVirtuality(),
1932 dwarf::VirtualityString
);
1933 if (N
->getVirtuality() != dwarf::DW_VIRTUALITY_none
||
1934 N
->getVirtualIndex() != 0)
1935 Printer
.printInt("virtualIndex", N
->getVirtualIndex(), false);
1936 Printer
.printInt("thisAdjustment", N
->getThisAdjustment());
1937 Printer
.printDIFlags("flags", N
->getFlags());
1938 Printer
.printBool("isOptimized", N
->isOptimized());
1939 Printer
.printMetadata("unit", N
->getRawUnit());
1940 Printer
.printMetadata("templateParams", N
->getRawTemplateParams());
1941 Printer
.printMetadata("declaration", N
->getRawDeclaration());
1942 Printer
.printMetadata("retainedNodes", N
->getRawRetainedNodes());
1943 Printer
.printMetadata("thrownTypes", N
->getRawThrownTypes());
1947 static void writeDILexicalBlock(raw_ostream
&Out
, const DILexicalBlock
*N
,
1948 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1949 const Module
*Context
) {
1950 Out
<< "!DILexicalBlock(";
1951 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1952 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
1953 Printer
.printMetadata("file", N
->getRawFile());
1954 Printer
.printInt("line", N
->getLine());
1955 Printer
.printInt("column", N
->getColumn());
1959 static void writeDILexicalBlockFile(raw_ostream
&Out
,
1960 const DILexicalBlockFile
*N
,
1961 TypePrinting
*TypePrinter
,
1962 SlotTracker
*Machine
,
1963 const Module
*Context
) {
1964 Out
<< "!DILexicalBlockFile(";
1965 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1966 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
1967 Printer
.printMetadata("file", N
->getRawFile());
1968 Printer
.printInt("discriminator", N
->getDiscriminator(),
1969 /* ShouldSkipZero */ false);
1973 static void writeDINamespace(raw_ostream
&Out
, const DINamespace
*N
,
1974 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1975 const Module
*Context
) {
1976 Out
<< "!DINamespace(";
1977 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1978 Printer
.printString("name", N
->getName());
1979 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
1980 Printer
.printBool("exportSymbols", N
->getExportSymbols(), false);
1984 static void writeDIMacro(raw_ostream
&Out
, const DIMacro
*N
,
1985 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1986 const Module
*Context
) {
1988 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
1989 Printer
.printMacinfoType(N
);
1990 Printer
.printInt("line", N
->getLine());
1991 Printer
.printString("name", N
->getName());
1992 Printer
.printString("value", N
->getValue());
1996 static void writeDIMacroFile(raw_ostream
&Out
, const DIMacroFile
*N
,
1997 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
1998 const Module
*Context
) {
1999 Out
<< "!DIMacroFile(";
2000 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2001 Printer
.printInt("line", N
->getLine());
2002 Printer
.printMetadata("file", N
->getRawFile(), /* ShouldSkipNull */ false);
2003 Printer
.printMetadata("nodes", N
->getRawElements());
2007 static void writeDIModule(raw_ostream
&Out
, const DIModule
*N
,
2008 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2009 const Module
*Context
) {
2010 Out
<< "!DIModule(";
2011 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2012 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2013 Printer
.printString("name", N
->getName());
2014 Printer
.printString("configMacros", N
->getConfigurationMacros());
2015 Printer
.printString("includePath", N
->getIncludePath());
2016 Printer
.printString("isysroot", N
->getISysRoot());
2021 static void writeDITemplateTypeParameter(raw_ostream
&Out
,
2022 const DITemplateTypeParameter
*N
,
2023 TypePrinting
*TypePrinter
,
2024 SlotTracker
*Machine
,
2025 const Module
*Context
) {
2026 Out
<< "!DITemplateTypeParameter(";
2027 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2028 Printer
.printString("name", N
->getName());
2029 Printer
.printMetadata("type", N
->getRawType(), /* ShouldSkipNull */ false);
2033 static void writeDITemplateValueParameter(raw_ostream
&Out
,
2034 const DITemplateValueParameter
*N
,
2035 TypePrinting
*TypePrinter
,
2036 SlotTracker
*Machine
,
2037 const Module
*Context
) {
2038 Out
<< "!DITemplateValueParameter(";
2039 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2040 if (N
->getTag() != dwarf::DW_TAG_template_value_parameter
)
2041 Printer
.printTag(N
);
2042 Printer
.printString("name", N
->getName());
2043 Printer
.printMetadata("type", N
->getRawType());
2044 Printer
.printMetadata("value", N
->getValue(), /* ShouldSkipNull */ false);
2048 static void writeDIGlobalVariable(raw_ostream
&Out
, const DIGlobalVariable
*N
,
2049 TypePrinting
*TypePrinter
,
2050 SlotTracker
*Machine
, const Module
*Context
) {
2051 Out
<< "!DIGlobalVariable(";
2052 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2053 Printer
.printString("name", N
->getName());
2054 Printer
.printString("linkageName", N
->getLinkageName());
2055 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2056 Printer
.printMetadata("file", N
->getRawFile());
2057 Printer
.printInt("line", N
->getLine());
2058 Printer
.printMetadata("type", N
->getRawType());
2059 Printer
.printBool("isLocal", N
->isLocalToUnit());
2060 Printer
.printBool("isDefinition", N
->isDefinition());
2061 Printer
.printMetadata("declaration", N
->getRawStaticDataMemberDeclaration());
2062 Printer
.printMetadata("templateParams", N
->getRawTemplateParams());
2063 Printer
.printInt("align", N
->getAlignInBits());
2067 static void writeDILocalVariable(raw_ostream
&Out
, const DILocalVariable
*N
,
2068 TypePrinting
*TypePrinter
,
2069 SlotTracker
*Machine
, const Module
*Context
) {
2070 Out
<< "!DILocalVariable(";
2071 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2072 Printer
.printString("name", N
->getName());
2073 Printer
.printInt("arg", N
->getArg());
2074 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2075 Printer
.printMetadata("file", N
->getRawFile());
2076 Printer
.printInt("line", N
->getLine());
2077 Printer
.printMetadata("type", N
->getRawType());
2078 Printer
.printDIFlags("flags", N
->getFlags());
2079 Printer
.printInt("align", N
->getAlignInBits());
2083 static void writeDILabel(raw_ostream
&Out
, const DILabel
*N
,
2084 TypePrinting
*TypePrinter
,
2085 SlotTracker
*Machine
, const Module
*Context
) {
2087 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2088 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2089 Printer
.printString("name", N
->getName());
2090 Printer
.printMetadata("file", N
->getRawFile());
2091 Printer
.printInt("line", N
->getLine());
2095 static void writeDIExpression(raw_ostream
&Out
, const DIExpression
*N
,
2096 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2097 const Module
*Context
) {
2098 Out
<< "!DIExpression(";
2101 for (auto I
= N
->expr_op_begin(), E
= N
->expr_op_end(); I
!= E
; ++I
) {
2102 auto OpStr
= dwarf::OperationEncodingString(I
->getOp());
2103 assert(!OpStr
.empty() && "Expected valid opcode");
2106 for (unsigned A
= 0, AE
= I
->getNumArgs(); A
!= AE
; ++A
)
2107 Out
<< FS
<< I
->getArg(A
);
2110 for (const auto &I
: N
->getElements())
2116 static void writeDIGlobalVariableExpression(raw_ostream
&Out
,
2117 const DIGlobalVariableExpression
*N
,
2118 TypePrinting
*TypePrinter
,
2119 SlotTracker
*Machine
,
2120 const Module
*Context
) {
2121 Out
<< "!DIGlobalVariableExpression(";
2122 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2123 Printer
.printMetadata("var", N
->getVariable());
2124 Printer
.printMetadata("expr", N
->getExpression());
2128 static void writeDIObjCProperty(raw_ostream
&Out
, const DIObjCProperty
*N
,
2129 TypePrinting
*TypePrinter
, SlotTracker
*Machine
,
2130 const Module
*Context
) {
2131 Out
<< "!DIObjCProperty(";
2132 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2133 Printer
.printString("name", N
->getName());
2134 Printer
.printMetadata("file", N
->getRawFile());
2135 Printer
.printInt("line", N
->getLine());
2136 Printer
.printString("setter", N
->getSetterName());
2137 Printer
.printString("getter", N
->getGetterName());
2138 Printer
.printInt("attributes", N
->getAttributes());
2139 Printer
.printMetadata("type", N
->getRawType());
2143 static void writeDIImportedEntity(raw_ostream
&Out
, const DIImportedEntity
*N
,
2144 TypePrinting
*TypePrinter
,
2145 SlotTracker
*Machine
, const Module
*Context
) {
2146 Out
<< "!DIImportedEntity(";
2147 MDFieldPrinter
Printer(Out
, TypePrinter
, Machine
, Context
);
2148 Printer
.printTag(N
);
2149 Printer
.printString("name", N
->getName());
2150 Printer
.printMetadata("scope", N
->getRawScope(), /* ShouldSkipNull */ false);
2151 Printer
.printMetadata("entity", N
->getRawEntity());
2152 Printer
.printMetadata("file", N
->getRawFile());
2153 Printer
.printInt("line", N
->getLine());
2157 static void WriteMDNodeBodyInternal(raw_ostream
&Out
, const MDNode
*Node
,
2158 TypePrinting
*TypePrinter
,
2159 SlotTracker
*Machine
,
2160 const Module
*Context
) {
2161 if (Node
->isDistinct())
2163 else if (Node
->isTemporary())
2164 Out
<< "<temporary!> "; // Handle broken code.
2166 switch (Node
->getMetadataID()) {
2168 llvm_unreachable("Expected uniquable MDNode");
2169 #define HANDLE_MDNODE_LEAF(CLASS) \
2170 case Metadata::CLASS##Kind: \
2171 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
2173 #include "llvm/IR/Metadata.def"
2177 // Full implementation of printing a Value as an operand with support for
2178 // TypePrinting, etc.
2179 static void WriteAsOperandInternal(raw_ostream
&Out
, const Value
*V
,
2180 TypePrinting
*TypePrinter
,
2181 SlotTracker
*Machine
,
2182 const Module
*Context
) {
2184 PrintLLVMName(Out
, V
);
2188 const Constant
*CV
= dyn_cast
<Constant
>(V
);
2189 if (CV
&& !isa
<GlobalValue
>(CV
)) {
2190 assert(TypePrinter
&& "Constants require TypePrinting!");
2191 WriteConstantInternal(Out
, CV
, *TypePrinter
, Machine
, Context
);
2195 if (const InlineAsm
*IA
= dyn_cast
<InlineAsm
>(V
)) {
2197 if (IA
->hasSideEffects())
2198 Out
<< "sideeffect ";
2199 if (IA
->isAlignStack())
2200 Out
<< "alignstack ";
2201 // We don't emit the AD_ATT dialect as it's the assumed default.
2202 if (IA
->getDialect() == InlineAsm::AD_Intel
)
2203 Out
<< "inteldialect ";
2205 printEscapedString(IA
->getAsmString(), Out
);
2207 printEscapedString(IA
->getConstraintString(), Out
);
2212 if (auto *MD
= dyn_cast
<MetadataAsValue
>(V
)) {
2213 WriteAsOperandInternal(Out
, MD
->getMetadata(), TypePrinter
, Machine
,
2214 Context
, /* FromValue */ true);
2220 // If we have a SlotTracker, use it.
2222 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
2223 Slot
= Machine
->getGlobalSlot(GV
);
2226 Slot
= Machine
->getLocalSlot(V
);
2228 // If the local value didn't succeed, then we may be referring to a value
2229 // from a different function. Translate it, as this can happen when using
2230 // address of blocks.
2232 if ((Machine
= createSlotTracker(V
))) {
2233 Slot
= Machine
->getLocalSlot(V
);
2237 } else if ((Machine
= createSlotTracker(V
))) {
2238 // Otherwise, create one to get the # and then destroy it.
2239 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
2240 Slot
= Machine
->getGlobalSlot(GV
);
2243 Slot
= Machine
->getLocalSlot(V
);
2252 Out
<< Prefix
<< Slot
;
2257 static void WriteAsOperandInternal(raw_ostream
&Out
, const Metadata
*MD
,
2258 TypePrinting
*TypePrinter
,
2259 SlotTracker
*Machine
, const Module
*Context
,
2261 // Write DIExpressions inline when used as a value. Improves readability of
2262 // debug info intrinsics.
2263 if (const DIExpression
*Expr
= dyn_cast
<DIExpression
>(MD
)) {
2264 writeDIExpression(Out
, Expr
, TypePrinter
, Machine
, Context
);
2268 if (const MDNode
*N
= dyn_cast
<MDNode
>(MD
)) {
2269 std::unique_ptr
<SlotTracker
> MachineStorage
;
2271 MachineStorage
= make_unique
<SlotTracker
>(Context
);
2272 Machine
= MachineStorage
.get();
2274 int Slot
= Machine
->getMetadataSlot(N
);
2276 // Give the pointer value instead of "badref", since this comes up all
2277 // the time when debugging.
2278 Out
<< "<" << N
<< ">";
2284 if (const MDString
*MDS
= dyn_cast
<MDString
>(MD
)) {
2286 printEscapedString(MDS
->getString(), Out
);
2291 auto *V
= cast
<ValueAsMetadata
>(MD
);
2292 assert(TypePrinter
&& "TypePrinter required for metadata values");
2293 assert((FromValue
|| !isa
<LocalAsMetadata
>(V
)) &&
2294 "Unexpected function-local metadata outside of value argument");
2296 TypePrinter
->print(V
->getValue()->getType(), Out
);
2298 WriteAsOperandInternal(Out
, V
->getValue(), TypePrinter
, Machine
, Context
);
2303 class AssemblyWriter
{
2304 formatted_raw_ostream
&Out
;
2305 const Module
*TheModule
= nullptr;
2306 const ModuleSummaryIndex
*TheIndex
= nullptr;
2307 std::unique_ptr
<SlotTracker
> SlotTrackerStorage
;
2308 SlotTracker
&Machine
;
2309 TypePrinting TypePrinter
;
2310 AssemblyAnnotationWriter
*AnnotationWriter
= nullptr;
2311 SetVector
<const Comdat
*> Comdats
;
2313 bool ShouldPreserveUseListOrder
;
2314 UseListOrderStack UseListOrders
;
2315 SmallVector
<StringRef
, 8> MDNames
;
2316 /// Synchronization scope names registered with LLVMContext.
2317 SmallVector
<StringRef
, 8> SSNs
;
2318 DenseMap
<const GlobalValueSummary
*, GlobalValue::GUID
> SummaryToGUIDMap
;
2321 /// Construct an AssemblyWriter with an external SlotTracker
2322 AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
, const Module
*M
,
2323 AssemblyAnnotationWriter
*AAW
, bool IsForDebug
,
2324 bool ShouldPreserveUseListOrder
= false);
2326 AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
2327 const ModuleSummaryIndex
*Index
, bool IsForDebug
);
2329 void printMDNodeBody(const MDNode
*MD
);
2330 void printNamedMDNode(const NamedMDNode
*NMD
);
2332 void printModule(const Module
*M
);
2334 void writeOperand(const Value
*Op
, bool PrintType
);
2335 void writeParamOperand(const Value
*Operand
, AttributeSet Attrs
);
2336 void writeOperandBundles(ImmutableCallSite CS
);
2337 void writeSyncScope(const LLVMContext
&Context
,
2338 SyncScope::ID SSID
);
2339 void writeAtomic(const LLVMContext
&Context
,
2340 AtomicOrdering Ordering
,
2341 SyncScope::ID SSID
);
2342 void writeAtomicCmpXchg(const LLVMContext
&Context
,
2343 AtomicOrdering SuccessOrdering
,
2344 AtomicOrdering FailureOrdering
,
2345 SyncScope::ID SSID
);
2347 void writeAllMDNodes();
2348 void writeMDNode(unsigned Slot
, const MDNode
*Node
);
2349 void writeAllAttributeGroups();
2351 void printTypeIdentities();
2352 void printGlobal(const GlobalVariable
*GV
);
2353 void printIndirectSymbol(const GlobalIndirectSymbol
*GIS
);
2354 void printComdat(const Comdat
*C
);
2355 void printFunction(const Function
*F
);
2356 void printArgument(const Argument
*FA
, AttributeSet Attrs
);
2357 void printBasicBlock(const BasicBlock
*BB
);
2358 void printInstructionLine(const Instruction
&I
);
2359 void printInstruction(const Instruction
&I
);
2361 void printUseListOrder(const UseListOrder
&Order
);
2362 void printUseLists(const Function
*F
);
2364 void printModuleSummaryIndex();
2365 void printSummaryInfo(unsigned Slot
, const ValueInfo
&VI
);
2366 void printSummary(const GlobalValueSummary
&Summary
);
2367 void printAliasSummary(const AliasSummary
*AS
);
2368 void printGlobalVarSummary(const GlobalVarSummary
*GS
);
2369 void printFunctionSummary(const FunctionSummary
*FS
);
2370 void printTypeIdSummary(const TypeIdSummary
&TIS
);
2371 void printTypeTestResolution(const TypeTestResolution
&TTRes
);
2372 void printArgs(const std::vector
<uint64_t> &Args
);
2373 void printWPDRes(const WholeProgramDevirtResolution
&WPDRes
);
2374 void printTypeIdInfo(const FunctionSummary::TypeIdInfo
&TIDInfo
);
2375 void printVFuncId(const FunctionSummary::VFuncId VFId
);
2377 printNonConstVCalls(const std::vector
<FunctionSummary::VFuncId
> VCallList
,
2380 printConstVCalls(const std::vector
<FunctionSummary::ConstVCall
> VCallList
,
2384 /// Print out metadata attachments.
2385 void printMetadataAttachments(
2386 const SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &MDs
,
2387 StringRef Separator
);
2389 // printInfoComment - Print a little comment after the instruction indicating
2390 // which slot it occupies.
2391 void printInfoComment(const Value
&V
);
2393 // printGCRelocateComment - print comment after call to the gc.relocate
2394 // intrinsic indicating base and derived pointer names.
2395 void printGCRelocateComment(const GCRelocateInst
&Relocate
);
2398 } // end anonymous namespace
2400 AssemblyWriter::AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
2401 const Module
*M
, AssemblyAnnotationWriter
*AAW
,
2402 bool IsForDebug
, bool ShouldPreserveUseListOrder
)
2403 : Out(o
), TheModule(M
), Machine(Mac
), TypePrinter(M
), AnnotationWriter(AAW
),
2404 IsForDebug(IsForDebug
),
2405 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder
) {
2408 for (const GlobalObject
&GO
: TheModule
->global_objects())
2409 if (const Comdat
*C
= GO
.getComdat())
2413 AssemblyWriter::AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
2414 const ModuleSummaryIndex
*Index
, bool IsForDebug
)
2415 : Out(o
), TheIndex(Index
), Machine(Mac
), TypePrinter(/*Module=*/nullptr),
2416 IsForDebug(IsForDebug
), ShouldPreserveUseListOrder(false) {}
2418 void AssemblyWriter::writeOperand(const Value
*Operand
, bool PrintType
) {
2420 Out
<< "<null operand!>";
2424 TypePrinter
.print(Operand
->getType(), Out
);
2427 WriteAsOperandInternal(Out
, Operand
, &TypePrinter
, &Machine
, TheModule
);
2430 void AssemblyWriter::writeSyncScope(const LLVMContext
&Context
,
2431 SyncScope::ID SSID
) {
2433 case SyncScope::System
: {
2438 Context
.getSyncScopeNames(SSNs
);
2440 Out
<< " syncscope(\"";
2441 printEscapedString(SSNs
[SSID
], Out
);
2448 void AssemblyWriter::writeAtomic(const LLVMContext
&Context
,
2449 AtomicOrdering Ordering
,
2450 SyncScope::ID SSID
) {
2451 if (Ordering
== AtomicOrdering::NotAtomic
)
2454 writeSyncScope(Context
, SSID
);
2455 Out
<< " " << toIRString(Ordering
);
2458 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext
&Context
,
2459 AtomicOrdering SuccessOrdering
,
2460 AtomicOrdering FailureOrdering
,
2461 SyncScope::ID SSID
) {
2462 assert(SuccessOrdering
!= AtomicOrdering::NotAtomic
&&
2463 FailureOrdering
!= AtomicOrdering::NotAtomic
);
2465 writeSyncScope(Context
, SSID
);
2466 Out
<< " " << toIRString(SuccessOrdering
);
2467 Out
<< " " << toIRString(FailureOrdering
);
2470 void AssemblyWriter::writeParamOperand(const Value
*Operand
,
2471 AttributeSet Attrs
) {
2473 Out
<< "<null operand!>";
2478 TypePrinter
.print(Operand
->getType(), Out
);
2479 // Print parameter attributes list
2480 if (Attrs
.hasAttributes())
2481 Out
<< ' ' << Attrs
.getAsString();
2483 // Print the operand
2484 WriteAsOperandInternal(Out
, Operand
, &TypePrinter
, &Machine
, TheModule
);
2487 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS
) {
2488 if (!CS
.hasOperandBundles())
2493 bool FirstBundle
= true;
2494 for (unsigned i
= 0, e
= CS
.getNumOperandBundles(); i
!= e
; ++i
) {
2495 OperandBundleUse BU
= CS
.getOperandBundleAt(i
);
2499 FirstBundle
= false;
2502 printEscapedString(BU
.getTagName(), Out
);
2507 bool FirstInput
= true;
2508 for (const auto &Input
: BU
.Inputs
) {
2513 TypePrinter
.print(Input
->getType(), Out
);
2515 WriteAsOperandInternal(Out
, Input
, &TypePrinter
, &Machine
, TheModule
);
2524 void AssemblyWriter::printModule(const Module
*M
) {
2525 Machine
.initializeIfNeeded();
2527 if (ShouldPreserveUseListOrder
)
2528 UseListOrders
= predictUseListOrder(M
);
2530 if (!M
->getModuleIdentifier().empty() &&
2531 // Don't print the ID if it will start a new line (which would
2532 // require a comment char before it).
2533 M
->getModuleIdentifier().find('\n') == std::string::npos
)
2534 Out
<< "; ModuleID = '" << M
->getModuleIdentifier() << "'\n";
2536 if (!M
->getSourceFileName().empty()) {
2537 Out
<< "source_filename = \"";
2538 printEscapedString(M
->getSourceFileName(), Out
);
2542 const std::string
&DL
= M
->getDataLayoutStr();
2544 Out
<< "target datalayout = \"" << DL
<< "\"\n";
2545 if (!M
->getTargetTriple().empty())
2546 Out
<< "target triple = \"" << M
->getTargetTriple() << "\"\n";
2548 if (!M
->getModuleInlineAsm().empty()) {
2551 // Split the string into lines, to make it easier to read the .ll file.
2552 StringRef Asm
= M
->getModuleInlineAsm();
2555 std::tie(Front
, Asm
) = Asm
.split('\n');
2557 // We found a newline, print the portion of the asm string from the
2558 // last newline up to this newline.
2559 Out
<< "module asm \"";
2560 printEscapedString(Front
, Out
);
2562 } while (!Asm
.empty());
2565 printTypeIdentities();
2567 // Output all comdats.
2568 if (!Comdats
.empty())
2570 for (const Comdat
*C
: Comdats
) {
2572 if (C
!= Comdats
.back())
2576 // Output all globals.
2577 if (!M
->global_empty()) Out
<< '\n';
2578 for (const GlobalVariable
&GV
: M
->globals()) {
2579 printGlobal(&GV
); Out
<< '\n';
2582 // Output all aliases.
2583 if (!M
->alias_empty()) Out
<< "\n";
2584 for (const GlobalAlias
&GA
: M
->aliases())
2585 printIndirectSymbol(&GA
);
2587 // Output all ifuncs.
2588 if (!M
->ifunc_empty()) Out
<< "\n";
2589 for (const GlobalIFunc
&GI
: M
->ifuncs())
2590 printIndirectSymbol(&GI
);
2592 // Output global use-lists.
2593 printUseLists(nullptr);
2595 // Output all of the functions.
2596 for (const Function
&F
: *M
)
2598 assert(UseListOrders
.empty() && "All use-lists should have been consumed");
2600 // Output all attribute groups.
2601 if (!Machine
.as_empty()) {
2603 writeAllAttributeGroups();
2606 // Output named metadata.
2607 if (!M
->named_metadata_empty()) Out
<< '\n';
2609 for (const NamedMDNode
&Node
: M
->named_metadata())
2610 printNamedMDNode(&Node
);
2613 if (!Machine
.mdn_empty()) {
2619 void AssemblyWriter::printModuleSummaryIndex() {
2621 Machine
.initializeIndexIfNeeded();
2625 // Print module path entries. To print in order, add paths to a vector
2626 // indexed by module slot.
2627 std::vector
<std::pair
<std::string
, ModuleHash
>> moduleVec
;
2628 std::string RegularLTOModuleName
= "[Regular LTO]";
2629 moduleVec
.resize(TheIndex
->modulePaths().size());
2630 for (auto &ModPath
: TheIndex
->modulePaths())
2631 moduleVec
[Machine
.getModulePathSlot(ModPath
.first())] = std::make_pair(
2632 // A module id of -1 is a special entry for a regular LTO module created
2633 // during the thin link.
2634 ModPath
.second
.first
== -1u ? RegularLTOModuleName
2635 : (std::string
)ModPath
.first(),
2636 ModPath
.second
.second
);
2639 for (auto &ModPair
: moduleVec
) {
2640 Out
<< "^" << i
++ << " = module: (";
2642 printEscapedString(ModPair
.first
, Out
);
2643 Out
<< "\", hash: (";
2645 for (auto Hash
: ModPair
.second
)
2650 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2651 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2652 for (auto &GlobalList
: *TheIndex
) {
2653 auto GUID
= GlobalList
.first
;
2654 for (auto &Summary
: GlobalList
.second
.SummaryList
)
2655 SummaryToGUIDMap
[Summary
.get()] = GUID
;
2658 // Print the global value summary entries.
2659 for (auto &GlobalList
: *TheIndex
) {
2660 auto GUID
= GlobalList
.first
;
2661 auto VI
= TheIndex
->getValueInfo(GlobalList
);
2662 printSummaryInfo(Machine
.getGUIDSlot(GUID
), VI
);
2665 // Print the TypeIdMap entries.
2666 for (auto TidIter
= TheIndex
->typeIds().begin();
2667 TidIter
!= TheIndex
->typeIds().end(); TidIter
++) {
2668 Out
<< "^" << Machine
.getTypeIdSlot(TidIter
->second
.first
)
2669 << " = typeid: (name: \"" << TidIter
->second
.first
<< "\"";
2670 printTypeIdSummary(TidIter
->second
.second
);
2671 Out
<< ") ; guid = " << TidIter
->first
<< "\n";
2676 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K
) {
2678 case WholeProgramDevirtResolution::Indir
:
2680 case WholeProgramDevirtResolution::SingleImpl
:
2681 return "singleImpl";
2682 case WholeProgramDevirtResolution::BranchFunnel
:
2683 return "branchFunnel";
2685 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2688 static const char *getWholeProgDevirtResByArgKindName(
2689 WholeProgramDevirtResolution::ByArg::Kind K
) {
2691 case WholeProgramDevirtResolution::ByArg::Indir
:
2693 case WholeProgramDevirtResolution::ByArg::UniformRetVal
:
2694 return "uniformRetVal";
2695 case WholeProgramDevirtResolution::ByArg::UniqueRetVal
:
2696 return "uniqueRetVal";
2697 case WholeProgramDevirtResolution::ByArg::VirtualConstProp
:
2698 return "virtualConstProp";
2700 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2703 static const char *getTTResKindName(TypeTestResolution::Kind K
) {
2705 case TypeTestResolution::Unsat
:
2707 case TypeTestResolution::ByteArray
:
2709 case TypeTestResolution::Inline
:
2711 case TypeTestResolution::Single
:
2713 case TypeTestResolution::AllOnes
:
2716 llvm_unreachable("invalid TypeTestResolution kind");
2719 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution
&TTRes
) {
2720 Out
<< "typeTestRes: (kind: " << getTTResKindName(TTRes
.TheKind
)
2721 << ", sizeM1BitWidth: " << TTRes
.SizeM1BitWidth
;
2723 // The following fields are only used if the target does not support the use
2724 // of absolute symbols to store constants. Print only if non-zero.
2725 if (TTRes
.AlignLog2
)
2726 Out
<< ", alignLog2: " << TTRes
.AlignLog2
;
2728 Out
<< ", sizeM1: " << TTRes
.SizeM1
;
2730 // BitMask is uint8_t which causes it to print the corresponding char.
2731 Out
<< ", bitMask: " << (unsigned)TTRes
.BitMask
;
2732 if (TTRes
.InlineBits
)
2733 Out
<< ", inlineBits: " << TTRes
.InlineBits
;
2738 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary
&TIS
) {
2739 Out
<< ", summary: (";
2740 printTypeTestResolution(TIS
.TTRes
);
2741 if (!TIS
.WPDRes
.empty()) {
2742 Out
<< ", wpdResolutions: (";
2744 for (auto &WPDRes
: TIS
.WPDRes
) {
2746 Out
<< "(offset: " << WPDRes
.first
<< ", ";
2747 printWPDRes(WPDRes
.second
);
2755 void AssemblyWriter::printArgs(const std::vector
<uint64_t> &Args
) {
2758 for (auto arg
: Args
) {
2765 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution
&WPDRes
) {
2766 Out
<< "wpdRes: (kind: ";
2767 Out
<< getWholeProgDevirtResKindName(WPDRes
.TheKind
);
2769 if (WPDRes
.TheKind
== WholeProgramDevirtResolution::SingleImpl
)
2770 Out
<< ", singleImplName: \"" << WPDRes
.SingleImplName
<< "\"";
2772 if (!WPDRes
.ResByArg
.empty()) {
2773 Out
<< ", resByArg: (";
2775 for (auto &ResByArg
: WPDRes
.ResByArg
) {
2777 printArgs(ResByArg
.first
);
2778 Out
<< ", byArg: (kind: ";
2779 Out
<< getWholeProgDevirtResByArgKindName(ResByArg
.second
.TheKind
);
2780 if (ResByArg
.second
.TheKind
==
2781 WholeProgramDevirtResolution::ByArg::UniformRetVal
||
2782 ResByArg
.second
.TheKind
==
2783 WholeProgramDevirtResolution::ByArg::UniqueRetVal
)
2784 Out
<< ", info: " << ResByArg
.second
.Info
;
2786 // The following fields are only used if the target does not support the
2787 // use of absolute symbols to store constants. Print only if non-zero.
2788 if (ResByArg
.second
.Byte
|| ResByArg
.second
.Bit
)
2789 Out
<< ", byte: " << ResByArg
.second
.Byte
2790 << ", bit: " << ResByArg
.second
.Bit
;
2799 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK
) {
2801 case GlobalValueSummary::AliasKind
:
2803 case GlobalValueSummary::FunctionKind
:
2805 case GlobalValueSummary::GlobalVarKind
:
2808 llvm_unreachable("invalid summary kind");
2811 void AssemblyWriter::printAliasSummary(const AliasSummary
*AS
) {
2812 Out
<< ", aliasee: ";
2813 // The indexes emitted for distributed backends may not include the
2814 // aliasee summary (only if it is being imported directly). Handle
2815 // that case by just emitting "null" as the aliasee.
2816 if (AS
->hasAliasee())
2817 Out
<< "^" << Machine
.getGUIDSlot(SummaryToGUIDMap
[&AS
->getAliasee()]);
2822 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary
*GS
) {
2826 static std::string
getLinkageName(GlobalValue::LinkageTypes LT
) {
2828 case GlobalValue::ExternalLinkage
:
2830 case GlobalValue::PrivateLinkage
:
2832 case GlobalValue::InternalLinkage
:
2834 case GlobalValue::LinkOnceAnyLinkage
:
2836 case GlobalValue::LinkOnceODRLinkage
:
2837 return "linkonce_odr";
2838 case GlobalValue::WeakAnyLinkage
:
2840 case GlobalValue::WeakODRLinkage
:
2842 case GlobalValue::CommonLinkage
:
2844 case GlobalValue::AppendingLinkage
:
2846 case GlobalValue::ExternalWeakLinkage
:
2847 return "extern_weak";
2848 case GlobalValue::AvailableExternallyLinkage
:
2849 return "available_externally";
2851 llvm_unreachable("invalid linkage");
2854 // When printing the linkage types in IR where the ExternalLinkage is
2855 // not printed, and other linkage types are expected to be printed with
2856 // a space after the name.
2857 static std::string
getLinkageNameWithSpace(GlobalValue::LinkageTypes LT
) {
2858 if (LT
== GlobalValue::ExternalLinkage
)
2860 return getLinkageName(LT
) + " ";
2863 void AssemblyWriter::printFunctionSummary(const FunctionSummary
*FS
) {
2864 Out
<< ", insts: " << FS
->instCount();
2866 FunctionSummary::FFlags FFlags
= FS
->fflags();
2867 if (FFlags
.ReadNone
| FFlags
.ReadOnly
| FFlags
.NoRecurse
|
2868 FFlags
.ReturnDoesNotAlias
) {
2869 Out
<< ", funcFlags: (";
2870 Out
<< "readNone: " << FFlags
.ReadNone
;
2871 Out
<< ", readOnly: " << FFlags
.ReadOnly
;
2872 Out
<< ", noRecurse: " << FFlags
.NoRecurse
;
2873 Out
<< ", returnDoesNotAlias: " << FFlags
.ReturnDoesNotAlias
;
2876 if (!FS
->calls().empty()) {
2877 Out
<< ", calls: (";
2879 for (auto &Call
: FS
->calls()) {
2881 Out
<< "(callee: ^" << Machine
.getGUIDSlot(Call
.first
.getGUID());
2882 if (Call
.second
.getHotness() != CalleeInfo::HotnessType::Unknown
)
2883 Out
<< ", hotness: " << getHotnessName(Call
.second
.getHotness());
2884 else if (Call
.second
.RelBlockFreq
)
2885 Out
<< ", relbf: " << Call
.second
.RelBlockFreq
;
2891 if (const auto *TIdInfo
= FS
->getTypeIdInfo())
2892 printTypeIdInfo(*TIdInfo
);
2895 void AssemblyWriter::printTypeIdInfo(
2896 const FunctionSummary::TypeIdInfo
&TIDInfo
) {
2897 Out
<< ", typeIdInfo: (";
2898 FieldSeparator TIDFS
;
2899 if (!TIDInfo
.TypeTests
.empty()) {
2901 Out
<< "typeTests: (";
2903 for (auto &GUID
: TIDInfo
.TypeTests
) {
2904 auto TidIter
= TheIndex
->typeIds().equal_range(GUID
);
2905 if (TidIter
.first
== TidIter
.second
) {
2910 // Print all type id that correspond to this GUID.
2911 for (auto It
= TidIter
.first
; It
!= TidIter
.second
; ++It
) {
2913 auto Slot
= Machine
.getTypeIdSlot(It
->second
.first
);
2920 if (!TIDInfo
.TypeTestAssumeVCalls
.empty()) {
2922 printNonConstVCalls(TIDInfo
.TypeTestAssumeVCalls
, "typeTestAssumeVCalls");
2924 if (!TIDInfo
.TypeCheckedLoadVCalls
.empty()) {
2926 printNonConstVCalls(TIDInfo
.TypeCheckedLoadVCalls
, "typeCheckedLoadVCalls");
2928 if (!TIDInfo
.TypeTestAssumeConstVCalls
.empty()) {
2930 printConstVCalls(TIDInfo
.TypeTestAssumeConstVCalls
,
2931 "typeTestAssumeConstVCalls");
2933 if (!TIDInfo
.TypeCheckedLoadConstVCalls
.empty()) {
2935 printConstVCalls(TIDInfo
.TypeCheckedLoadConstVCalls
,
2936 "typeCheckedLoadConstVCalls");
2941 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId
) {
2942 auto TidIter
= TheIndex
->typeIds().equal_range(VFId
.GUID
);
2943 if (TidIter
.first
== TidIter
.second
) {
2944 Out
<< "vFuncId: (";
2945 Out
<< "guid: " << VFId
.GUID
;
2946 Out
<< ", offset: " << VFId
.Offset
;
2950 // Print all type id that correspond to this GUID.
2952 for (auto It
= TidIter
.first
; It
!= TidIter
.second
; ++It
) {
2954 Out
<< "vFuncId: (";
2955 auto Slot
= Machine
.getTypeIdSlot(It
->second
.first
);
2958 Out
<< ", offset: " << VFId
.Offset
;
2963 void AssemblyWriter::printNonConstVCalls(
2964 const std::vector
<FunctionSummary::VFuncId
> VCallList
, const char *Tag
) {
2965 Out
<< Tag
<< ": (";
2967 for (auto &VFuncId
: VCallList
) {
2969 printVFuncId(VFuncId
);
2974 void AssemblyWriter::printConstVCalls(
2975 const std::vector
<FunctionSummary::ConstVCall
> VCallList
, const char *Tag
) {
2976 Out
<< Tag
<< ": (";
2978 for (auto &ConstVCall
: VCallList
) {
2981 printVFuncId(ConstVCall
.VFunc
);
2982 if (!ConstVCall
.Args
.empty()) {
2984 printArgs(ConstVCall
.Args
);
2991 void AssemblyWriter::printSummary(const GlobalValueSummary
&Summary
) {
2992 GlobalValueSummary::GVFlags GVFlags
= Summary
.flags();
2993 GlobalValue::LinkageTypes LT
= (GlobalValue::LinkageTypes
)GVFlags
.Linkage
;
2994 Out
<< getSummaryKindName(Summary
.getSummaryKind()) << ": ";
2995 Out
<< "(module: ^" << Machine
.getModulePathSlot(Summary
.modulePath())
2997 Out
<< "linkage: " << getLinkageName(LT
);
2998 Out
<< ", notEligibleToImport: " << GVFlags
.NotEligibleToImport
;
2999 Out
<< ", live: " << GVFlags
.Live
;
3000 Out
<< ", dsoLocal: " << GVFlags
.DSOLocal
;
3003 if (Summary
.getSummaryKind() == GlobalValueSummary::AliasKind
)
3004 printAliasSummary(cast
<AliasSummary
>(&Summary
));
3005 else if (Summary
.getSummaryKind() == GlobalValueSummary::FunctionKind
)
3006 printFunctionSummary(cast
<FunctionSummary
>(&Summary
));
3008 printGlobalVarSummary(cast
<GlobalVarSummary
>(&Summary
));
3010 auto RefList
= Summary
.refs();
3011 if (!RefList
.empty()) {
3014 for (auto &Ref
: RefList
) {
3016 Out
<< "^" << Machine
.getGUIDSlot(Ref
.getGUID());
3024 void AssemblyWriter::printSummaryInfo(unsigned Slot
, const ValueInfo
&VI
) {
3025 Out
<< "^" << Slot
<< " = gv: (";
3026 if (!VI
.name().empty())
3027 Out
<< "name: \"" << VI
.name() << "\"";
3029 Out
<< "guid: " << VI
.getGUID();
3030 if (!VI
.getSummaryList().empty()) {
3031 Out
<< ", summaries: (";
3033 for (auto &Summary
: VI
.getSummaryList()) {
3035 printSummary(*Summary
);
3040 if (!VI
.name().empty())
3041 Out
<< " ; guid = " << VI
.getGUID();
3045 static void printMetadataIdentifier(StringRef Name
,
3046 formatted_raw_ostream
&Out
) {
3048 Out
<< "<empty name> ";
3050 if (isalpha(static_cast<unsigned char>(Name
[0])) || Name
[0] == '-' ||
3051 Name
[0] == '$' || Name
[0] == '.' || Name
[0] == '_')
3054 Out
<< '\\' << hexdigit(Name
[0] >> 4) << hexdigit(Name
[0] & 0x0F);
3055 for (unsigned i
= 1, e
= Name
.size(); i
!= e
; ++i
) {
3056 unsigned char C
= Name
[i
];
3057 if (isalnum(static_cast<unsigned char>(C
)) || C
== '-' || C
== '$' ||
3058 C
== '.' || C
== '_')
3061 Out
<< '\\' << hexdigit(C
>> 4) << hexdigit(C
& 0x0F);
3066 void AssemblyWriter::printNamedMDNode(const NamedMDNode
*NMD
) {
3068 printMetadataIdentifier(NMD
->getName(), Out
);
3070 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
) {
3074 // Write DIExpressions inline.
3075 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3076 MDNode
*Op
= NMD
->getOperand(i
);
3077 if (auto *Expr
= dyn_cast
<DIExpression
>(Op
)) {
3078 writeDIExpression(Out
, Expr
, nullptr, nullptr, nullptr);
3082 int Slot
= Machine
.getMetadataSlot(Op
);
3091 static void PrintVisibility(GlobalValue::VisibilityTypes Vis
,
3092 formatted_raw_ostream
&Out
) {
3094 case GlobalValue::DefaultVisibility
: break;
3095 case GlobalValue::HiddenVisibility
: Out
<< "hidden "; break;
3096 case GlobalValue::ProtectedVisibility
: Out
<< "protected "; break;
3100 static void PrintDSOLocation(const GlobalValue
&GV
,
3101 formatted_raw_ostream
&Out
) {
3102 // GVs with local linkage or non default visibility are implicitly dso_local,
3103 // so we don't print it.
3104 bool Implicit
= GV
.hasLocalLinkage() ||
3105 (!GV
.hasExternalWeakLinkage() && !GV
.hasDefaultVisibility());
3106 if (GV
.isDSOLocal() && !Implicit
)
3107 Out
<< "dso_local ";
3110 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT
,
3111 formatted_raw_ostream
&Out
) {
3113 case GlobalValue::DefaultStorageClass
: break;
3114 case GlobalValue::DLLImportStorageClass
: Out
<< "dllimport "; break;
3115 case GlobalValue::DLLExportStorageClass
: Out
<< "dllexport "; break;
3119 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM
,
3120 formatted_raw_ostream
&Out
) {
3122 case GlobalVariable::NotThreadLocal
:
3124 case GlobalVariable::GeneralDynamicTLSModel
:
3125 Out
<< "thread_local ";
3127 case GlobalVariable::LocalDynamicTLSModel
:
3128 Out
<< "thread_local(localdynamic) ";
3130 case GlobalVariable::InitialExecTLSModel
:
3131 Out
<< "thread_local(initialexec) ";
3133 case GlobalVariable::LocalExecTLSModel
:
3134 Out
<< "thread_local(localexec) ";
3139 static StringRef
getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA
) {
3141 case GlobalVariable::UnnamedAddr::None
:
3143 case GlobalVariable::UnnamedAddr::Local
:
3144 return "local_unnamed_addr";
3145 case GlobalVariable::UnnamedAddr::Global
:
3146 return "unnamed_addr";
3148 llvm_unreachable("Unknown UnnamedAddr");
3151 static void maybePrintComdat(formatted_raw_ostream
&Out
,
3152 const GlobalObject
&GO
) {
3153 const Comdat
*C
= GO
.getComdat();
3157 if (isa
<GlobalVariable
>(GO
))
3161 if (GO
.getName() == C
->getName())
3165 PrintLLVMName(Out
, C
->getName(), ComdatPrefix
);
3169 void AssemblyWriter::printGlobal(const GlobalVariable
*GV
) {
3170 if (GV
->isMaterializable())
3171 Out
<< "; Materializable\n";
3173 WriteAsOperandInternal(Out
, GV
, &TypePrinter
, &Machine
, GV
->getParent());
3176 if (!GV
->hasInitializer() && GV
->hasExternalLinkage())
3179 Out
<< getLinkageNameWithSpace(GV
->getLinkage());
3180 PrintDSOLocation(*GV
, Out
);
3181 PrintVisibility(GV
->getVisibility(), Out
);
3182 PrintDLLStorageClass(GV
->getDLLStorageClass(), Out
);
3183 PrintThreadLocalModel(GV
->getThreadLocalMode(), Out
);
3184 StringRef UA
= getUnnamedAddrEncoding(GV
->getUnnamedAddr());
3188 if (unsigned AddressSpace
= GV
->getType()->getAddressSpace())
3189 Out
<< "addrspace(" << AddressSpace
<< ") ";
3190 if (GV
->isExternallyInitialized()) Out
<< "externally_initialized ";
3191 Out
<< (GV
->isConstant() ? "constant " : "global ");
3192 TypePrinter
.print(GV
->getValueType(), Out
);
3194 if (GV
->hasInitializer()) {
3196 writeOperand(GV
->getInitializer(), false);
3199 if (GV
->hasSection()) {
3200 Out
<< ", section \"";
3201 printEscapedString(GV
->getSection(), Out
);
3204 maybePrintComdat(Out
, *GV
);
3205 if (GV
->getAlignment())
3206 Out
<< ", align " << GV
->getAlignment();
3208 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
3209 GV
->getAllMetadata(MDs
);
3210 printMetadataAttachments(MDs
, ", ");
3212 auto Attrs
= GV
->getAttributes();
3213 if (Attrs
.hasAttributes())
3214 Out
<< " #" << Machine
.getAttributeGroupSlot(Attrs
);
3216 printInfoComment(*GV
);
3219 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol
*GIS
) {
3220 if (GIS
->isMaterializable())
3221 Out
<< "; Materializable\n";
3223 WriteAsOperandInternal(Out
, GIS
, &TypePrinter
, &Machine
, GIS
->getParent());
3226 Out
<< getLinkageNameWithSpace(GIS
->getLinkage());
3227 PrintDSOLocation(*GIS
, Out
);
3228 PrintVisibility(GIS
->getVisibility(), Out
);
3229 PrintDLLStorageClass(GIS
->getDLLStorageClass(), Out
);
3230 PrintThreadLocalModel(GIS
->getThreadLocalMode(), Out
);
3231 StringRef UA
= getUnnamedAddrEncoding(GIS
->getUnnamedAddr());
3235 if (isa
<GlobalAlias
>(GIS
))
3237 else if (isa
<GlobalIFunc
>(GIS
))
3240 llvm_unreachable("Not an alias or ifunc!");
3242 TypePrinter
.print(GIS
->getValueType(), Out
);
3246 const Constant
*IS
= GIS
->getIndirectSymbol();
3249 TypePrinter
.print(GIS
->getType(), Out
);
3250 Out
<< " <<NULL ALIASEE>>";
3252 writeOperand(IS
, !isa
<ConstantExpr
>(IS
));
3255 printInfoComment(*GIS
);
3259 void AssemblyWriter::printComdat(const Comdat
*C
) {
3263 void AssemblyWriter::printTypeIdentities() {
3264 if (TypePrinter
.empty())
3269 // Emit all numbered types.
3270 auto &NumberedTypes
= TypePrinter
.getNumberedTypes();
3271 for (unsigned I
= 0, E
= NumberedTypes
.size(); I
!= E
; ++I
) {
3272 Out
<< '%' << I
<< " = type ";
3274 // Make sure we print out at least one level of the type structure, so
3275 // that we do not get %2 = type %2
3276 TypePrinter
.printStructBody(NumberedTypes
[I
], Out
);
3280 auto &NamedTypes
= TypePrinter
.getNamedTypes();
3281 for (unsigned I
= 0, E
= NamedTypes
.size(); I
!= E
; ++I
) {
3282 PrintLLVMName(Out
, NamedTypes
[I
]->getName(), LocalPrefix
);
3285 // Make sure we print out at least one level of the type structure, so
3286 // that we do not get %FILE = type %FILE
3287 TypePrinter
.printStructBody(NamedTypes
[I
], Out
);
3292 /// printFunction - Print all aspects of a function.
3293 void AssemblyWriter::printFunction(const Function
*F
) {
3294 // Print out the return type and name.
3297 if (AnnotationWriter
) AnnotationWriter
->emitFunctionAnnot(F
, Out
);
3299 if (F
->isMaterializable())
3300 Out
<< "; Materializable\n";
3302 const AttributeList
&Attrs
= F
->getAttributes();
3303 if (Attrs
.hasAttributes(AttributeList::FunctionIndex
)) {
3304 AttributeSet AS
= Attrs
.getFnAttributes();
3305 std::string AttrStr
;
3307 for (const Attribute
&Attr
: AS
) {
3308 if (!Attr
.isStringAttribute()) {
3309 if (!AttrStr
.empty()) AttrStr
+= ' ';
3310 AttrStr
+= Attr
.getAsString();
3314 if (!AttrStr
.empty())
3315 Out
<< "; Function Attrs: " << AttrStr
<< '\n';
3318 Machine
.incorporateFunction(F
);
3320 if (F
->isDeclaration()) {
3322 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
3323 F
->getAllMetadata(MDs
);
3324 printMetadataAttachments(MDs
, " ");
3329 Out
<< getLinkageNameWithSpace(F
->getLinkage());
3330 PrintDSOLocation(*F
, Out
);
3331 PrintVisibility(F
->getVisibility(), Out
);
3332 PrintDLLStorageClass(F
->getDLLStorageClass(), Out
);
3334 // Print the calling convention.
3335 if (F
->getCallingConv() != CallingConv::C
) {
3336 PrintCallingConv(F
->getCallingConv(), Out
);
3340 FunctionType
*FT
= F
->getFunctionType();
3341 if (Attrs
.hasAttributes(AttributeList::ReturnIndex
))
3342 Out
<< Attrs
.getAsString(AttributeList::ReturnIndex
) << ' ';
3343 TypePrinter
.print(F
->getReturnType(), Out
);
3345 WriteAsOperandInternal(Out
, F
, &TypePrinter
, &Machine
, F
->getParent());
3348 // Loop over the arguments, printing them...
3349 if (F
->isDeclaration() && !IsForDebug
) {
3350 // We're only interested in the type here - don't print argument names.
3351 for (unsigned I
= 0, E
= FT
->getNumParams(); I
!= E
; ++I
) {
3352 // Insert commas as we go... the first arg doesn't get a comma
3356 TypePrinter
.print(FT
->getParamType(I
), Out
);
3358 AttributeSet ArgAttrs
= Attrs
.getParamAttributes(I
);
3359 if (ArgAttrs
.hasAttributes())
3360 Out
<< ' ' << ArgAttrs
.getAsString();
3363 // The arguments are meaningful here, print them in detail.
3364 for (const Argument
&Arg
: F
->args()) {
3365 // Insert commas as we go... the first arg doesn't get a comma
3366 if (Arg
.getArgNo() != 0)
3368 printArgument(&Arg
, Attrs
.getParamAttributes(Arg
.getArgNo()));
3372 // Finish printing arguments...
3373 if (FT
->isVarArg()) {
3374 if (FT
->getNumParams()) Out
<< ", ";
3375 Out
<< "..."; // Output varargs portion of signature!
3378 StringRef UA
= getUnnamedAddrEncoding(F
->getUnnamedAddr());
3381 // We print the function address space if it is non-zero or if we are writing
3382 // a module with a non-zero program address space or if there is no valid
3383 // Module* so that the file can be parsed without the datalayout string.
3384 const Module
*Mod
= F
->getParent();
3385 if (F
->getAddressSpace() != 0 || !Mod
||
3386 Mod
->getDataLayout().getProgramAddressSpace() != 0)
3387 Out
<< " addrspace(" << F
->getAddressSpace() << ")";
3388 if (Attrs
.hasAttributes(AttributeList::FunctionIndex
))
3389 Out
<< " #" << Machine
.getAttributeGroupSlot(Attrs
.getFnAttributes());
3390 if (F
->hasSection()) {
3391 Out
<< " section \"";
3392 printEscapedString(F
->getSection(), Out
);
3395 maybePrintComdat(Out
, *F
);
3396 if (F
->getAlignment())
3397 Out
<< " align " << F
->getAlignment();
3399 Out
<< " gc \"" << F
->getGC() << '"';
3400 if (F
->hasPrefixData()) {
3402 writeOperand(F
->getPrefixData(), true);
3404 if (F
->hasPrologueData()) {
3405 Out
<< " prologue ";
3406 writeOperand(F
->getPrologueData(), true);
3408 if (F
->hasPersonalityFn()) {
3409 Out
<< " personality ";
3410 writeOperand(F
->getPersonalityFn(), /*PrintType=*/true);
3413 if (F
->isDeclaration()) {
3416 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
3417 F
->getAllMetadata(MDs
);
3418 printMetadataAttachments(MDs
, " ");
3421 // Output all of the function's basic blocks.
3422 for (const BasicBlock
&BB
: *F
)
3423 printBasicBlock(&BB
);
3425 // Output the function's use-lists.
3431 Machine
.purgeFunction();
3434 /// printArgument - This member is called for every argument that is passed into
3435 /// the function. Simply print it out
3436 void AssemblyWriter::printArgument(const Argument
*Arg
, AttributeSet Attrs
) {
3438 TypePrinter
.print(Arg
->getType(), Out
);
3440 // Output parameter attributes list
3441 if (Attrs
.hasAttributes())
3442 Out
<< ' ' << Attrs
.getAsString();
3444 // Output name, if available...
3445 if (Arg
->hasName()) {
3447 PrintLLVMName(Out
, Arg
);
3451 /// printBasicBlock - This member is called for each basic block in a method.
3452 void AssemblyWriter::printBasicBlock(const BasicBlock
*BB
) {
3453 if (BB
->hasName()) { // Print out the label if it exists...
3455 PrintLLVMName(Out
, BB
->getName(), LabelPrefix
);
3457 } else if (!BB
->use_empty()) { // Don't print block # of no uses...
3458 Out
<< "\n; <label>:";
3459 int Slot
= Machine
.getLocalSlot(BB
);
3466 if (!BB
->getParent()) {
3467 Out
.PadToColumn(50);
3468 Out
<< "; Error: Block without parent!";
3469 } else if (BB
!= &BB
->getParent()->getEntryBlock()) { // Not the entry block?
3470 // Output predecessors for the block.
3471 Out
.PadToColumn(50);
3473 const_pred_iterator PI
= pred_begin(BB
), PE
= pred_end(BB
);
3476 Out
<< " No predecessors!";
3479 writeOperand(*PI
, false);
3480 for (++PI
; PI
!= PE
; ++PI
) {
3482 writeOperand(*PI
, false);
3489 if (AnnotationWriter
) AnnotationWriter
->emitBasicBlockStartAnnot(BB
, Out
);
3491 // Output all of the instructions in the basic block...
3492 for (const Instruction
&I
: *BB
) {
3493 printInstructionLine(I
);
3496 if (AnnotationWriter
) AnnotationWriter
->emitBasicBlockEndAnnot(BB
, Out
);
3499 /// printInstructionLine - Print an instruction and a newline character.
3500 void AssemblyWriter::printInstructionLine(const Instruction
&I
) {
3501 printInstruction(I
);
3505 /// printGCRelocateComment - print comment after call to the gc.relocate
3506 /// intrinsic indicating base and derived pointer names.
3507 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst
&Relocate
) {
3509 writeOperand(Relocate
.getBasePtr(), false);
3511 writeOperand(Relocate
.getDerivedPtr(), false);
3515 /// printInfoComment - Print a little comment after the instruction indicating
3516 /// which slot it occupies.
3517 void AssemblyWriter::printInfoComment(const Value
&V
) {
3518 if (const auto *Relocate
= dyn_cast
<GCRelocateInst
>(&V
))
3519 printGCRelocateComment(*Relocate
);
3521 if (AnnotationWriter
)
3522 AnnotationWriter
->printInfoComment(V
, Out
);
3525 static void maybePrintCallAddrSpace(const Value
*Operand
, const Instruction
*I
,
3527 // We print the address space of the call if it is non-zero.
3528 unsigned CallAddrSpace
= Operand
->getType()->getPointerAddressSpace();
3529 bool PrintAddrSpace
= CallAddrSpace
!= 0;
3530 if (!PrintAddrSpace
) {
3531 const Module
*Mod
= getModuleFromVal(I
);
3532 // We also print it if it is zero but not equal to the program address space
3533 // or if we can't find a valid Module* to make it possible to parse
3534 // the resulting file even without a datalayout string.
3535 if (!Mod
|| Mod
->getDataLayout().getProgramAddressSpace() != 0)
3536 PrintAddrSpace
= true;
3539 Out
<< " addrspace(" << CallAddrSpace
<< ")";
3542 // This member is called for each Instruction in a function..
3543 void AssemblyWriter::printInstruction(const Instruction
&I
) {
3544 if (AnnotationWriter
) AnnotationWriter
->emitInstructionAnnot(&I
, Out
);
3546 // Print out indentation for an instruction.
3549 // Print out name if it exists...
3551 PrintLLVMName(Out
, &I
);
3553 } else if (!I
.getType()->isVoidTy()) {
3554 // Print out the def slot taken.
3555 int SlotNum
= Machine
.getLocalSlot(&I
);
3557 Out
<< "<badref> = ";
3559 Out
<< '%' << SlotNum
<< " = ";
3562 if (const CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
3563 if (CI
->isMustTailCall())
3565 else if (CI
->isTailCall())
3567 else if (CI
->isNoTailCall())
3571 // Print out the opcode...
3572 Out
<< I
.getOpcodeName();
3574 // If this is an atomic load or store, print out the atomic marker.
3575 if ((isa
<LoadInst
>(I
) && cast
<LoadInst
>(I
).isAtomic()) ||
3576 (isa
<StoreInst
>(I
) && cast
<StoreInst
>(I
).isAtomic()))
3579 if (isa
<AtomicCmpXchgInst
>(I
) && cast
<AtomicCmpXchgInst
>(I
).isWeak())
3582 // If this is a volatile operation, print out the volatile marker.
3583 if ((isa
<LoadInst
>(I
) && cast
<LoadInst
>(I
).isVolatile()) ||
3584 (isa
<StoreInst
>(I
) && cast
<StoreInst
>(I
).isVolatile()) ||
3585 (isa
<AtomicCmpXchgInst
>(I
) && cast
<AtomicCmpXchgInst
>(I
).isVolatile()) ||
3586 (isa
<AtomicRMWInst
>(I
) && cast
<AtomicRMWInst
>(I
).isVolatile()))
3589 // Print out optimization information.
3590 WriteOptimizationInfo(Out
, &I
);
3592 // Print out the compare instruction predicates
3593 if (const CmpInst
*CI
= dyn_cast
<CmpInst
>(&I
))
3594 Out
<< ' ' << CmpInst::getPredicateName(CI
->getPredicate());
3596 // Print out the atomicrmw operation
3597 if (const AtomicRMWInst
*RMWI
= dyn_cast
<AtomicRMWInst
>(&I
))
3598 Out
<< ' ' << AtomicRMWInst::getOperationName(RMWI
->getOperation());
3600 // Print out the type of the operands...
3601 const Value
*Operand
= I
.getNumOperands() ? I
.getOperand(0) : nullptr;
3603 // Special case conditional branches to swizzle the condition out to the front
3604 if (isa
<BranchInst
>(I
) && cast
<BranchInst
>(I
).isConditional()) {
3605 const BranchInst
&BI(cast
<BranchInst
>(I
));
3607 writeOperand(BI
.getCondition(), true);
3609 writeOperand(BI
.getSuccessor(0), true);
3611 writeOperand(BI
.getSuccessor(1), true);
3613 } else if (isa
<SwitchInst
>(I
)) {
3614 const SwitchInst
& SI(cast
<SwitchInst
>(I
));
3615 // Special case switch instruction to get formatting nice and correct.
3617 writeOperand(SI
.getCondition(), true);
3619 writeOperand(SI
.getDefaultDest(), true);
3621 for (auto Case
: SI
.cases()) {
3623 writeOperand(Case
.getCaseValue(), true);
3625 writeOperand(Case
.getCaseSuccessor(), true);
3628 } else if (isa
<IndirectBrInst
>(I
)) {
3629 // Special case indirectbr instruction to get formatting nice and correct.
3631 writeOperand(Operand
, true);
3634 for (unsigned i
= 1, e
= I
.getNumOperands(); i
!= e
; ++i
) {
3637 writeOperand(I
.getOperand(i
), true);
3640 } else if (const PHINode
*PN
= dyn_cast
<PHINode
>(&I
)) {
3642 TypePrinter
.print(I
.getType(), Out
);
3645 for (unsigned op
= 0, Eop
= PN
->getNumIncomingValues(); op
< Eop
; ++op
) {
3646 if (op
) Out
<< ", ";
3648 writeOperand(PN
->getIncomingValue(op
), false); Out
<< ", ";
3649 writeOperand(PN
->getIncomingBlock(op
), false); Out
<< " ]";
3651 } else if (const ExtractValueInst
*EVI
= dyn_cast
<ExtractValueInst
>(&I
)) {
3653 writeOperand(I
.getOperand(0), true);
3654 for (const unsigned *i
= EVI
->idx_begin(), *e
= EVI
->idx_end(); i
!= e
; ++i
)
3656 } else if (const InsertValueInst
*IVI
= dyn_cast
<InsertValueInst
>(&I
)) {
3658 writeOperand(I
.getOperand(0), true); Out
<< ", ";
3659 writeOperand(I
.getOperand(1), true);
3660 for (const unsigned *i
= IVI
->idx_begin(), *e
= IVI
->idx_end(); i
!= e
; ++i
)
3662 } else if (const LandingPadInst
*LPI
= dyn_cast
<LandingPadInst
>(&I
)) {
3664 TypePrinter
.print(I
.getType(), Out
);
3665 if (LPI
->isCleanup() || LPI
->getNumClauses() != 0)
3668 if (LPI
->isCleanup())
3671 for (unsigned i
= 0, e
= LPI
->getNumClauses(); i
!= e
; ++i
) {
3672 if (i
!= 0 || LPI
->isCleanup()) Out
<< "\n";
3673 if (LPI
->isCatch(i
))
3678 writeOperand(LPI
->getClause(i
), true);
3680 } else if (const auto *CatchSwitch
= dyn_cast
<CatchSwitchInst
>(&I
)) {
3682 writeOperand(CatchSwitch
->getParentPad(), /*PrintType=*/false);
3685 for (const BasicBlock
*PadBB
: CatchSwitch
->handlers()) {
3688 writeOperand(PadBB
, /*PrintType=*/true);
3692 if (const BasicBlock
*UnwindDest
= CatchSwitch
->getUnwindDest())
3693 writeOperand(UnwindDest
, /*PrintType=*/true);
3696 } else if (const auto *FPI
= dyn_cast
<FuncletPadInst
>(&I
)) {
3698 writeOperand(FPI
->getParentPad(), /*PrintType=*/false);
3700 for (unsigned Op
= 0, NumOps
= FPI
->getNumArgOperands(); Op
< NumOps
;
3704 writeOperand(FPI
->getArgOperand(Op
), /*PrintType=*/true);
3707 } else if (isa
<ReturnInst
>(I
) && !Operand
) {
3709 } else if (const auto *CRI
= dyn_cast
<CatchReturnInst
>(&I
)) {
3711 writeOperand(CRI
->getOperand(0), /*PrintType=*/false);
3714 writeOperand(CRI
->getOperand(1), /*PrintType=*/true);
3715 } else if (const auto *CRI
= dyn_cast
<CleanupReturnInst
>(&I
)) {
3717 writeOperand(CRI
->getOperand(0), /*PrintType=*/false);
3720 if (CRI
->hasUnwindDest())
3721 writeOperand(CRI
->getOperand(1), /*PrintType=*/true);
3724 } else if (const CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
3725 // Print the calling convention being used.
3726 if (CI
->getCallingConv() != CallingConv::C
) {
3728 PrintCallingConv(CI
->getCallingConv(), Out
);
3731 Operand
= CI
->getCalledValue();
3732 FunctionType
*FTy
= CI
->getFunctionType();
3733 Type
*RetTy
= FTy
->getReturnType();
3734 const AttributeList
&PAL
= CI
->getAttributes();
3736 if (PAL
.hasAttributes(AttributeList::ReturnIndex
))
3737 Out
<< ' ' << PAL
.getAsString(AttributeList::ReturnIndex
);
3739 // Only print addrspace(N) if necessary:
3740 maybePrintCallAddrSpace(Operand
, &I
, Out
);
3742 // If possible, print out the short form of the call instruction. We can
3743 // only do this if the first argument is a pointer to a nonvararg function,
3744 // and if the return type is not a pointer to a function.
3747 TypePrinter
.print(FTy
->isVarArg() ? FTy
: RetTy
, Out
);
3749 writeOperand(Operand
, false);
3751 for (unsigned op
= 0, Eop
= CI
->getNumArgOperands(); op
< Eop
; ++op
) {
3754 writeParamOperand(CI
->getArgOperand(op
), PAL
.getParamAttributes(op
));
3757 // Emit an ellipsis if this is a musttail call in a vararg function. This
3758 // is only to aid readability, musttail calls forward varargs by default.
3759 if (CI
->isMustTailCall() && CI
->getParent() &&
3760 CI
->getParent()->getParent() &&
3761 CI
->getParent()->getParent()->isVarArg())
3765 if (PAL
.hasAttributes(AttributeList::FunctionIndex
))
3766 Out
<< " #" << Machine
.getAttributeGroupSlot(PAL
.getFnAttributes());
3768 writeOperandBundles(CI
);
3769 } else if (const InvokeInst
*II
= dyn_cast
<InvokeInst
>(&I
)) {
3770 Operand
= II
->getCalledValue();
3771 FunctionType
*FTy
= II
->getFunctionType();
3772 Type
*RetTy
= FTy
->getReturnType();
3773 const AttributeList
&PAL
= II
->getAttributes();
3775 // Print the calling convention being used.
3776 if (II
->getCallingConv() != CallingConv::C
) {
3778 PrintCallingConv(II
->getCallingConv(), Out
);
3781 if (PAL
.hasAttributes(AttributeList::ReturnIndex
))
3782 Out
<< ' ' << PAL
.getAsString(AttributeList::ReturnIndex
);
3784 // Only print addrspace(N) if necessary:
3785 maybePrintCallAddrSpace(Operand
, &I
, Out
);
3787 // If possible, print out the short form of the invoke instruction. We can
3788 // only do this if the first argument is a pointer to a nonvararg function,
3789 // and if the return type is not a pointer to a function.
3792 TypePrinter
.print(FTy
->isVarArg() ? FTy
: RetTy
, Out
);
3794 writeOperand(Operand
, false);
3796 for (unsigned op
= 0, Eop
= II
->getNumArgOperands(); op
< Eop
; ++op
) {
3799 writeParamOperand(II
->getArgOperand(op
), PAL
.getParamAttributes(op
));
3803 if (PAL
.hasAttributes(AttributeList::FunctionIndex
))
3804 Out
<< " #" << Machine
.getAttributeGroupSlot(PAL
.getFnAttributes());
3806 writeOperandBundles(II
);
3809 writeOperand(II
->getNormalDest(), true);
3811 writeOperand(II
->getUnwindDest(), true);
3812 } else if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(&I
)) {
3814 if (AI
->isUsedWithInAlloca())
3816 if (AI
->isSwiftError())
3817 Out
<< "swifterror ";
3818 TypePrinter
.print(AI
->getAllocatedType(), Out
);
3820 // Explicitly write the array size if the code is broken, if it's an array
3821 // allocation, or if the type is not canonical for scalar allocations. The
3822 // latter case prevents the type from mutating when round-tripping through
3824 if (!AI
->getArraySize() || AI
->isArrayAllocation() ||
3825 !AI
->getArraySize()->getType()->isIntegerTy(32)) {
3827 writeOperand(AI
->getArraySize(), true);
3829 if (AI
->getAlignment()) {
3830 Out
<< ", align " << AI
->getAlignment();
3833 unsigned AddrSpace
= AI
->getType()->getAddressSpace();
3834 if (AddrSpace
!= 0) {
3835 Out
<< ", addrspace(" << AddrSpace
<< ')';
3837 } else if (isa
<CastInst
>(I
)) {
3840 writeOperand(Operand
, true); // Work with broken code
3843 TypePrinter
.print(I
.getType(), Out
);
3844 } else if (isa
<VAArgInst
>(I
)) {
3847 writeOperand(Operand
, true); // Work with broken code
3850 TypePrinter
.print(I
.getType(), Out
);
3851 } else if (Operand
) { // Print the normal way.
3852 if (const auto *GEP
= dyn_cast
<GetElementPtrInst
>(&I
)) {
3854 TypePrinter
.print(GEP
->getSourceElementType(), Out
);
3856 } else if (const auto *LI
= dyn_cast
<LoadInst
>(&I
)) {
3858 TypePrinter
.print(LI
->getType(), Out
);
3862 // PrintAllTypes - Instructions who have operands of all the same type
3863 // omit the type from all but the first operand. If the instruction has
3864 // different type operands (for example br), then they are all printed.
3865 bool PrintAllTypes
= false;
3866 Type
*TheType
= Operand
->getType();
3868 // Select, Store and ShuffleVector always print all types.
3869 if (isa
<SelectInst
>(I
) || isa
<StoreInst
>(I
) || isa
<ShuffleVectorInst
>(I
)
3870 || isa
<ReturnInst
>(I
)) {
3871 PrintAllTypes
= true;
3873 for (unsigned i
= 1, E
= I
.getNumOperands(); i
!= E
; ++i
) {
3874 Operand
= I
.getOperand(i
);
3875 // note that Operand shouldn't be null, but the test helps make dump()
3876 // more tolerant of malformed IR
3877 if (Operand
&& Operand
->getType() != TheType
) {
3878 PrintAllTypes
= true; // We have differing types! Print them all!
3884 if (!PrintAllTypes
) {
3886 TypePrinter
.print(TheType
, Out
);
3890 for (unsigned i
= 0, E
= I
.getNumOperands(); i
!= E
; ++i
) {
3892 writeOperand(I
.getOperand(i
), PrintAllTypes
);
3896 // Print atomic ordering/alignment for memory operations
3897 if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(&I
)) {
3899 writeAtomic(LI
->getContext(), LI
->getOrdering(), LI
->getSyncScopeID());
3900 if (LI
->getAlignment())
3901 Out
<< ", align " << LI
->getAlignment();
3902 } else if (const StoreInst
*SI
= dyn_cast
<StoreInst
>(&I
)) {
3904 writeAtomic(SI
->getContext(), SI
->getOrdering(), SI
->getSyncScopeID());
3905 if (SI
->getAlignment())
3906 Out
<< ", align " << SI
->getAlignment();
3907 } else if (const AtomicCmpXchgInst
*CXI
= dyn_cast
<AtomicCmpXchgInst
>(&I
)) {
3908 writeAtomicCmpXchg(CXI
->getContext(), CXI
->getSuccessOrdering(),
3909 CXI
->getFailureOrdering(), CXI
->getSyncScopeID());
3910 } else if (const AtomicRMWInst
*RMWI
= dyn_cast
<AtomicRMWInst
>(&I
)) {
3911 writeAtomic(RMWI
->getContext(), RMWI
->getOrdering(),
3912 RMWI
->getSyncScopeID());
3913 } else if (const FenceInst
*FI
= dyn_cast
<FenceInst
>(&I
)) {
3914 writeAtomic(FI
->getContext(), FI
->getOrdering(), FI
->getSyncScopeID());
3917 // Print Metadata info.
3918 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> InstMD
;
3919 I
.getAllMetadata(InstMD
);
3920 printMetadataAttachments(InstMD
, ", ");
3922 // Print a nice comment.
3923 printInfoComment(I
);
3926 void AssemblyWriter::printMetadataAttachments(
3927 const SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &MDs
,
3928 StringRef Separator
) {
3932 if (MDNames
.empty())
3933 MDs
[0].second
->getContext().getMDKindNames(MDNames
);
3935 for (const auto &I
: MDs
) {
3936 unsigned Kind
= I
.first
;
3938 if (Kind
< MDNames
.size()) {
3940 printMetadataIdentifier(MDNames
[Kind
], Out
);
3942 Out
<< "!<unknown kind #" << Kind
<< ">";
3944 WriteAsOperandInternal(Out
, I
.second
, &TypePrinter
, &Machine
, TheModule
);
3948 void AssemblyWriter::writeMDNode(unsigned Slot
, const MDNode
*Node
) {
3949 Out
<< '!' << Slot
<< " = ";
3950 printMDNodeBody(Node
);
3954 void AssemblyWriter::writeAllMDNodes() {
3955 SmallVector
<const MDNode
*, 16> Nodes
;
3956 Nodes
.resize(Machine
.mdn_size());
3957 for (SlotTracker::mdn_iterator I
= Machine
.mdn_begin(), E
= Machine
.mdn_end();
3959 Nodes
[I
->second
] = cast
<MDNode
>(I
->first
);
3961 for (unsigned i
= 0, e
= Nodes
.size(); i
!= e
; ++i
) {
3962 writeMDNode(i
, Nodes
[i
]);
3966 void AssemblyWriter::printMDNodeBody(const MDNode
*Node
) {
3967 WriteMDNodeBodyInternal(Out
, Node
, &TypePrinter
, &Machine
, TheModule
);
3970 void AssemblyWriter::writeAllAttributeGroups() {
3971 std::vector
<std::pair
<AttributeSet
, unsigned>> asVec
;
3972 asVec
.resize(Machine
.as_size());
3974 for (SlotTracker::as_iterator I
= Machine
.as_begin(), E
= Machine
.as_end();
3976 asVec
[I
->second
] = *I
;
3978 for (const auto &I
: asVec
)
3979 Out
<< "attributes #" << I
.second
<< " = { "
3980 << I
.first
.getAsString(true) << " }\n";
3983 void AssemblyWriter::printUseListOrder(const UseListOrder
&Order
) {
3984 bool IsInFunction
= Machine
.getFunction();
3988 Out
<< "uselistorder";
3989 if (const BasicBlock
*BB
=
3990 IsInFunction
? nullptr : dyn_cast
<BasicBlock
>(Order
.V
)) {
3992 writeOperand(BB
->getParent(), false);
3994 writeOperand(BB
, false);
3997 writeOperand(Order
.V
, true);
4001 assert(Order
.Shuffle
.size() >= 2 && "Shuffle too small");
4002 Out
<< Order
.Shuffle
[0];
4003 for (unsigned I
= 1, E
= Order
.Shuffle
.size(); I
!= E
; ++I
)
4004 Out
<< ", " << Order
.Shuffle
[I
];
4008 void AssemblyWriter::printUseLists(const Function
*F
) {
4010 [&]() { return !UseListOrders
.empty() && UseListOrders
.back().F
== F
; };
4015 Out
<< "\n; uselistorder directives\n";
4017 printUseListOrder(UseListOrders
.back());
4018 UseListOrders
.pop_back();
4022 //===----------------------------------------------------------------------===//
4023 // External Interface declarations
4024 //===----------------------------------------------------------------------===//
4026 void Function::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
,
4027 bool ShouldPreserveUseListOrder
,
4028 bool IsForDebug
) const {
4029 SlotTracker
SlotTable(this->getParent());
4030 formatted_raw_ostream
OS(ROS
);
4031 AssemblyWriter
W(OS
, SlotTable
, this->getParent(), AAW
,
4033 ShouldPreserveUseListOrder
);
4034 W
.printFunction(this);
4037 void Module::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
,
4038 bool ShouldPreserveUseListOrder
, bool IsForDebug
) const {
4039 SlotTracker
SlotTable(this);
4040 formatted_raw_ostream
OS(ROS
);
4041 AssemblyWriter
W(OS
, SlotTable
, this, AAW
, IsForDebug
,
4042 ShouldPreserveUseListOrder
);
4043 W
.printModule(this);
4046 void NamedMDNode::print(raw_ostream
&ROS
, bool IsForDebug
) const {
4047 SlotTracker
SlotTable(getParent());
4048 formatted_raw_ostream
OS(ROS
);
4049 AssemblyWriter
W(OS
, SlotTable
, getParent(), nullptr, IsForDebug
);
4050 W
.printNamedMDNode(this);
4053 void NamedMDNode::print(raw_ostream
&ROS
, ModuleSlotTracker
&MST
,
4054 bool IsForDebug
) const {
4055 Optional
<SlotTracker
> LocalST
;
4056 SlotTracker
*SlotTable
;
4057 if (auto *ST
= MST
.getMachine())
4060 LocalST
.emplace(getParent());
4061 SlotTable
= &*LocalST
;
4064 formatted_raw_ostream
OS(ROS
);
4065 AssemblyWriter
W(OS
, *SlotTable
, getParent(), nullptr, IsForDebug
);
4066 W
.printNamedMDNode(this);
4069 void Comdat::print(raw_ostream
&ROS
, bool /*IsForDebug*/) const {
4070 PrintLLVMName(ROS
, getName(), ComdatPrefix
);
4071 ROS
<< " = comdat ";
4073 switch (getSelectionKind()) {
4077 case Comdat::ExactMatch
:
4078 ROS
<< "exactmatch";
4080 case Comdat::Largest
:
4083 case Comdat::NoDuplicates
:
4084 ROS
<< "noduplicates";
4086 case Comdat::SameSize
:
4094 void Type::print(raw_ostream
&OS
, bool /*IsForDebug*/, bool NoDetails
) const {
4096 TP
.print(const_cast<Type
*>(this), OS
);
4101 // If the type is a named struct type, print the body as well.
4102 if (StructType
*STy
= dyn_cast
<StructType
>(const_cast<Type
*>(this)))
4103 if (!STy
->isLiteral()) {
4105 TP
.printStructBody(STy
, OS
);
4109 static bool isReferencingMDNode(const Instruction
&I
) {
4110 if (const auto *CI
= dyn_cast
<CallInst
>(&I
))
4111 if (Function
*F
= CI
->getCalledFunction())
4112 if (F
->isIntrinsic())
4113 for (auto &Op
: I
.operands())
4114 if (auto *V
= dyn_cast_or_null
<MetadataAsValue
>(Op
))
4115 if (isa
<MDNode
>(V
->getMetadata()))
4120 void Value::print(raw_ostream
&ROS
, bool IsForDebug
) const {
4121 bool ShouldInitializeAllMetadata
= false;
4122 if (auto *I
= dyn_cast
<Instruction
>(this))
4123 ShouldInitializeAllMetadata
= isReferencingMDNode(*I
);
4124 else if (isa
<Function
>(this) || isa
<MetadataAsValue
>(this))
4125 ShouldInitializeAllMetadata
= true;
4127 ModuleSlotTracker
MST(getModuleFromVal(this), ShouldInitializeAllMetadata
);
4128 print(ROS
, MST
, IsForDebug
);
4131 void Value::print(raw_ostream
&ROS
, ModuleSlotTracker
&MST
,
4132 bool IsForDebug
) const {
4133 formatted_raw_ostream
OS(ROS
);
4134 SlotTracker
EmptySlotTable(static_cast<const Module
*>(nullptr));
4135 SlotTracker
&SlotTable
=
4136 MST
.getMachine() ? *MST
.getMachine() : EmptySlotTable
;
4137 auto incorporateFunction
= [&](const Function
*F
) {
4139 MST
.incorporateFunction(*F
);
4142 if (const Instruction
*I
= dyn_cast
<Instruction
>(this)) {
4143 incorporateFunction(I
->getParent() ? I
->getParent()->getParent() : nullptr);
4144 AssemblyWriter
W(OS
, SlotTable
, getModuleFromVal(I
), nullptr, IsForDebug
);
4145 W
.printInstruction(*I
);
4146 } else if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(this)) {
4147 incorporateFunction(BB
->getParent());
4148 AssemblyWriter
W(OS
, SlotTable
, getModuleFromVal(BB
), nullptr, IsForDebug
);
4149 W
.printBasicBlock(BB
);
4150 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(this)) {
4151 AssemblyWriter
W(OS
, SlotTable
, GV
->getParent(), nullptr, IsForDebug
);
4152 if (const GlobalVariable
*V
= dyn_cast
<GlobalVariable
>(GV
))
4154 else if (const Function
*F
= dyn_cast
<Function
>(GV
))
4157 W
.printIndirectSymbol(cast
<GlobalIndirectSymbol
>(GV
));
4158 } else if (const MetadataAsValue
*V
= dyn_cast
<MetadataAsValue
>(this)) {
4159 V
->getMetadata()->print(ROS
, MST
, getModuleFromVal(V
));
4160 } else if (const Constant
*C
= dyn_cast
<Constant
>(this)) {
4161 TypePrinting TypePrinter
;
4162 TypePrinter
.print(C
->getType(), OS
);
4164 WriteConstantInternal(OS
, C
, TypePrinter
, MST
.getMachine(), nullptr);
4165 } else if (isa
<InlineAsm
>(this) || isa
<Argument
>(this)) {
4166 this->printAsOperand(OS
, /* PrintType */ true, MST
);
4168 llvm_unreachable("Unknown value to print out!");
4172 /// Print without a type, skipping the TypePrinting object.
4174 /// \return \c true iff printing was successful.
4175 static bool printWithoutType(const Value
&V
, raw_ostream
&O
,
4176 SlotTracker
*Machine
, const Module
*M
) {
4177 if (V
.hasName() || isa
<GlobalValue
>(V
) ||
4178 (!isa
<Constant
>(V
) && !isa
<MetadataAsValue
>(V
))) {
4179 WriteAsOperandInternal(O
, &V
, nullptr, Machine
, M
);
4185 static void printAsOperandImpl(const Value
&V
, raw_ostream
&O
, bool PrintType
,
4186 ModuleSlotTracker
&MST
) {
4187 TypePrinting
TypePrinter(MST
.getModule());
4189 TypePrinter
.print(V
.getType(), O
);
4193 WriteAsOperandInternal(O
, &V
, &TypePrinter
, MST
.getMachine(),
4197 void Value::printAsOperand(raw_ostream
&O
, bool PrintType
,
4198 const Module
*M
) const {
4200 M
= getModuleFromVal(this);
4203 if (printWithoutType(*this, O
, nullptr, M
))
4206 SlotTracker
Machine(
4207 M
, /* ShouldInitializeAllMetadata */ isa
<MetadataAsValue
>(this));
4208 ModuleSlotTracker
MST(Machine
, M
);
4209 printAsOperandImpl(*this, O
, PrintType
, MST
);
4212 void Value::printAsOperand(raw_ostream
&O
, bool PrintType
,
4213 ModuleSlotTracker
&MST
) const {
4215 if (printWithoutType(*this, O
, MST
.getMachine(), MST
.getModule()))
4218 printAsOperandImpl(*this, O
, PrintType
, MST
);
4221 static void printMetadataImpl(raw_ostream
&ROS
, const Metadata
&MD
,
4222 ModuleSlotTracker
&MST
, const Module
*M
,
4223 bool OnlyAsOperand
) {
4224 formatted_raw_ostream
OS(ROS
);
4226 TypePrinting
TypePrinter(M
);
4228 WriteAsOperandInternal(OS
, &MD
, &TypePrinter
, MST
.getMachine(), M
,
4229 /* FromValue */ true);
4231 auto *N
= dyn_cast
<MDNode
>(&MD
);
4232 if (OnlyAsOperand
|| !N
|| isa
<DIExpression
>(MD
))
4236 WriteMDNodeBodyInternal(OS
, N
, &TypePrinter
, MST
.getMachine(), M
);
4239 void Metadata::printAsOperand(raw_ostream
&OS
, const Module
*M
) const {
4240 ModuleSlotTracker
MST(M
, isa
<MDNode
>(this));
4241 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ true);
4244 void Metadata::printAsOperand(raw_ostream
&OS
, ModuleSlotTracker
&MST
,
4245 const Module
*M
) const {
4246 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ true);
4249 void Metadata::print(raw_ostream
&OS
, const Module
*M
,
4250 bool /*IsForDebug*/) const {
4251 ModuleSlotTracker
MST(M
, isa
<MDNode
>(this));
4252 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ false);
4255 void Metadata::print(raw_ostream
&OS
, ModuleSlotTracker
&MST
,
4256 const Module
*M
, bool /*IsForDebug*/) const {
4257 printMetadataImpl(OS
, *this, MST
, M
, /* OnlyAsOperand */ false);
4260 void ModuleSummaryIndex::print(raw_ostream
&ROS
, bool IsForDebug
) const {
4261 SlotTracker
SlotTable(this);
4262 formatted_raw_ostream
OS(ROS
);
4263 AssemblyWriter
W(OS
, SlotTable
, this, IsForDebug
);
4264 W
.printModuleSummaryIndex();
4267 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4268 // Value::dump - allow easy printing of Values from the debugger.
4270 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4272 // Type::dump - allow easy printing of Types from the debugger.
4274 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4276 // Module::dump() - Allow printing of Modules from the debugger.
4278 void Module::dump() const {
4279 print(dbgs(), nullptr,
4280 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4283 // Allow printing of Comdats from the debugger.
4285 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4287 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4289 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4292 void Metadata::dump() const { dump(nullptr); }
4295 void Metadata::dump(const Module
*M
) const {
4296 print(dbgs(), M
, /*IsForDebug=*/true);
4300 // Allow printing of ModuleSummaryIndex from the debugger.
4302 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }