1 //===- Metadata.cpp - Implement Metadata classes --------------------------===//
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 file implements the Metadata classes.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMContextImpl.h"
15 #include "MetadataImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/IR/Argument.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/ConstantRange.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalObject.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/TrackingMDRef.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/Value.h"
47 #include "llvm/IR/ValueHandle.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
57 #include <type_traits>
63 MetadataAsValue::MetadataAsValue(Type
*Ty
, Metadata
*MD
)
64 : Value(Ty
, MetadataAsValueVal
), MD(MD
) {
68 MetadataAsValue::~MetadataAsValue() {
69 getType()->getContext().pImpl
->MetadataAsValues
.erase(MD
);
73 /// Canonicalize metadata arguments to intrinsics.
75 /// To support bitcode upgrades (and assembly semantic sugar) for \a
76 /// MetadataAsValue, we need to canonicalize certain metadata.
78 /// - nullptr is replaced by an empty MDNode.
79 /// - An MDNode with a single null operand is replaced by an empty MDNode.
80 /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
82 /// This maintains readability of bitcode from when metadata was a type of
83 /// value, and these bridges were unnecessary.
84 static Metadata
*canonicalizeMetadataForValue(LLVMContext
&Context
,
88 return MDNode::get(Context
, None
);
90 // Return early if this isn't a single-operand MDNode.
91 auto *N
= dyn_cast
<MDNode
>(MD
);
92 if (!N
|| N
->getNumOperands() != 1)
95 if (!N
->getOperand(0))
97 return MDNode::get(Context
, None
);
99 if (auto *C
= dyn_cast
<ConstantAsMetadata
>(N
->getOperand(0)))
100 // Look through the MDNode.
106 MetadataAsValue
*MetadataAsValue::get(LLVMContext
&Context
, Metadata
*MD
) {
107 MD
= canonicalizeMetadataForValue(Context
, MD
);
108 auto *&Entry
= Context
.pImpl
->MetadataAsValues
[MD
];
110 Entry
= new MetadataAsValue(Type::getMetadataTy(Context
), MD
);
114 MetadataAsValue
*MetadataAsValue::getIfExists(LLVMContext
&Context
,
116 MD
= canonicalizeMetadataForValue(Context
, MD
);
117 auto &Store
= Context
.pImpl
->MetadataAsValues
;
118 return Store
.lookup(MD
);
121 void MetadataAsValue::handleChangedMetadata(Metadata
*MD
) {
122 LLVMContext
&Context
= getContext();
123 MD
= canonicalizeMetadataForValue(Context
, MD
);
124 auto &Store
= Context
.pImpl
->MetadataAsValues
;
126 // Stop tracking the old metadata.
127 Store
.erase(this->MD
);
131 // Start tracking MD, or RAUW if necessary.
132 auto *&Entry
= Store
[MD
];
134 replaceAllUsesWith(Entry
);
144 void MetadataAsValue::track() {
146 MetadataTracking::track(&MD
, *MD
, *this);
149 void MetadataAsValue::untrack() {
151 MetadataTracking::untrack(MD
);
154 bool MetadataTracking::track(void *Ref
, Metadata
&MD
, OwnerTy Owner
) {
155 assert(Ref
&& "Expected live reference");
156 assert((Owner
|| *static_cast<Metadata
**>(Ref
) == &MD
) &&
157 "Reference without owner must be direct");
158 if (auto *R
= ReplaceableMetadataImpl::getOrCreate(MD
)) {
159 R
->addRef(Ref
, Owner
);
162 if (auto *PH
= dyn_cast
<DistinctMDOperandPlaceholder
>(&MD
)) {
163 assert(!PH
->Use
&& "Placeholders can only be used once");
164 assert(!Owner
&& "Unexpected callback to owner");
165 PH
->Use
= static_cast<Metadata
**>(Ref
);
171 void MetadataTracking::untrack(void *Ref
, Metadata
&MD
) {
172 assert(Ref
&& "Expected live reference");
173 if (auto *R
= ReplaceableMetadataImpl::getIfExists(MD
))
175 else if (auto *PH
= dyn_cast
<DistinctMDOperandPlaceholder
>(&MD
))
179 bool MetadataTracking::retrack(void *Ref
, Metadata
&MD
, void *New
) {
180 assert(Ref
&& "Expected live reference");
181 assert(New
&& "Expected live reference");
182 assert(Ref
!= New
&& "Expected change");
183 if (auto *R
= ReplaceableMetadataImpl::getIfExists(MD
)) {
184 R
->moveRef(Ref
, New
, MD
);
187 assert(!isa
<DistinctMDOperandPlaceholder
>(MD
) &&
188 "Unexpected move of an MDOperand");
189 assert(!isReplaceable(MD
) &&
190 "Expected un-replaceable metadata, since we didn't move a reference");
194 bool MetadataTracking::isReplaceable(const Metadata
&MD
) {
195 return ReplaceableMetadataImpl::isReplaceable(MD
);
198 void ReplaceableMetadataImpl::addRef(void *Ref
, OwnerTy Owner
) {
200 UseMap
.insert(std::make_pair(Ref
, std::make_pair(Owner
, NextIndex
)))
203 assert(WasInserted
&& "Expected to add a reference");
206 assert(NextIndex
!= 0 && "Unexpected overflow");
209 void ReplaceableMetadataImpl::dropRef(void *Ref
) {
210 bool WasErased
= UseMap
.erase(Ref
);
212 assert(WasErased
&& "Expected to drop a reference");
215 void ReplaceableMetadataImpl::moveRef(void *Ref
, void *New
,
216 const Metadata
&MD
) {
217 auto I
= UseMap
.find(Ref
);
218 assert(I
!= UseMap
.end() && "Expected to move a reference");
219 auto OwnerAndIndex
= I
->second
;
221 bool WasInserted
= UseMap
.insert(std::make_pair(New
, OwnerAndIndex
)).second
;
223 assert(WasInserted
&& "Expected to add a reference");
225 // Check that the references are direct if there's no owner.
227 assert((OwnerAndIndex
.first
|| *static_cast<Metadata
**>(Ref
) == &MD
) &&
228 "Reference without owner must be direct");
229 assert((OwnerAndIndex
.first
|| *static_cast<Metadata
**>(New
) == &MD
) &&
230 "Reference without owner must be direct");
233 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata
*MD
) {
237 // Copy out uses since UseMap will get touched below.
238 using UseTy
= std::pair
<void *, std::pair
<OwnerTy
, uint64_t>>;
239 SmallVector
<UseTy
, 8> Uses(UseMap
.begin(), UseMap
.end());
240 llvm::sort(Uses
, [](const UseTy
&L
, const UseTy
&R
) {
241 return L
.second
.second
< R
.second
.second
;
243 for (const auto &Pair
: Uses
) {
244 // Check that this Ref hasn't disappeared after RAUW (when updating a
246 if (!UseMap
.count(Pair
.first
))
249 OwnerTy Owner
= Pair
.second
.first
;
251 // Update unowned tracking references directly.
252 Metadata
*&Ref
= *static_cast<Metadata
**>(Pair
.first
);
255 MetadataTracking::track(Ref
);
256 UseMap
.erase(Pair
.first
);
260 // Check for MetadataAsValue.
261 if (Owner
.is
<MetadataAsValue
*>()) {
262 Owner
.get
<MetadataAsValue
*>()->handleChangedMetadata(MD
);
266 // There's a Metadata owner -- dispatch.
267 Metadata
*OwnerMD
= Owner
.get
<Metadata
*>();
268 switch (OwnerMD
->getMetadataID()) {
269 #define HANDLE_METADATA_LEAF(CLASS) \
270 case Metadata::CLASS##Kind: \
271 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
273 #include "llvm/IR/Metadata.def"
275 llvm_unreachable("Invalid metadata subclass");
278 assert(UseMap
.empty() && "Expected all uses to be replaced");
281 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers
) {
290 // Copy out uses since UseMap could get touched below.
291 using UseTy
= std::pair
<void *, std::pair
<OwnerTy
, uint64_t>>;
292 SmallVector
<UseTy
, 8> Uses(UseMap
.begin(), UseMap
.end());
293 llvm::sort(Uses
, [](const UseTy
&L
, const UseTy
&R
) {
294 return L
.second
.second
< R
.second
.second
;
297 for (const auto &Pair
: Uses
) {
298 auto Owner
= Pair
.second
.first
;
301 if (Owner
.is
<MetadataAsValue
*>())
304 // Resolve MDNodes that point at this.
305 auto *OwnerMD
= dyn_cast
<MDNode
>(Owner
.get
<Metadata
*>());
308 if (OwnerMD
->isResolved())
310 OwnerMD
->decrementUnresolvedOperandCount();
314 ReplaceableMetadataImpl
*ReplaceableMetadataImpl::getOrCreate(Metadata
&MD
) {
315 if (auto *N
= dyn_cast
<MDNode
>(&MD
))
316 return N
->isResolved() ? nullptr : N
->Context
.getOrCreateReplaceableUses();
317 return dyn_cast
<ValueAsMetadata
>(&MD
);
320 ReplaceableMetadataImpl
*ReplaceableMetadataImpl::getIfExists(Metadata
&MD
) {
321 if (auto *N
= dyn_cast
<MDNode
>(&MD
))
322 return N
->isResolved() ? nullptr : N
->Context
.getReplaceableUses();
323 return dyn_cast
<ValueAsMetadata
>(&MD
);
326 bool ReplaceableMetadataImpl::isReplaceable(const Metadata
&MD
) {
327 if (auto *N
= dyn_cast
<MDNode
>(&MD
))
328 return !N
->isResolved();
329 return dyn_cast
<ValueAsMetadata
>(&MD
);
332 static DISubprogram
*getLocalFunctionMetadata(Value
*V
) {
333 assert(V
&& "Expected value");
334 if (auto *A
= dyn_cast
<Argument
>(V
)) {
335 if (auto *Fn
= A
->getParent())
336 return Fn
->getSubprogram();
340 if (BasicBlock
*BB
= cast
<Instruction
>(V
)->getParent()) {
341 if (auto *Fn
= BB
->getParent())
342 return Fn
->getSubprogram();
349 ValueAsMetadata
*ValueAsMetadata::get(Value
*V
) {
350 assert(V
&& "Unexpected null Value");
352 auto &Context
= V
->getContext();
353 auto *&Entry
= Context
.pImpl
->ValuesAsMetadata
[V
];
355 assert((isa
<Constant
>(V
) || isa
<Argument
>(V
) || isa
<Instruction
>(V
)) &&
356 "Expected constant or function-local value");
357 assert(!V
->IsUsedByMD
&& "Expected this to be the only metadata use");
358 V
->IsUsedByMD
= true;
359 if (auto *C
= dyn_cast
<Constant
>(V
))
360 Entry
= new ConstantAsMetadata(C
);
362 Entry
= new LocalAsMetadata(V
);
368 ValueAsMetadata
*ValueAsMetadata::getIfExists(Value
*V
) {
369 assert(V
&& "Unexpected null Value");
370 return V
->getContext().pImpl
->ValuesAsMetadata
.lookup(V
);
373 void ValueAsMetadata::handleDeletion(Value
*V
) {
374 assert(V
&& "Expected valid value");
376 auto &Store
= V
->getType()->getContext().pImpl
->ValuesAsMetadata
;
377 auto I
= Store
.find(V
);
378 if (I
== Store
.end())
381 // Remove old entry from the map.
382 ValueAsMetadata
*MD
= I
->second
;
383 assert(MD
&& "Expected valid metadata");
384 assert(MD
->getValue() == V
&& "Expected valid mapping");
387 // Delete the metadata.
388 MD
->replaceAllUsesWith(nullptr);
392 void ValueAsMetadata::handleRAUW(Value
*From
, Value
*To
) {
393 assert(From
&& "Expected valid value");
394 assert(To
&& "Expected valid value");
395 assert(From
!= To
&& "Expected changed value");
396 assert(From
->getType() == To
->getType() && "Unexpected type change");
398 LLVMContext
&Context
= From
->getType()->getContext();
399 auto &Store
= Context
.pImpl
->ValuesAsMetadata
;
400 auto I
= Store
.find(From
);
401 if (I
== Store
.end()) {
402 assert(!From
->IsUsedByMD
&& "Expected From not to be used by metadata");
406 // Remove old entry from the map.
407 assert(From
->IsUsedByMD
&& "Expected From to be used by metadata");
408 From
->IsUsedByMD
= false;
409 ValueAsMetadata
*MD
= I
->second
;
410 assert(MD
&& "Expected valid metadata");
411 assert(MD
->getValue() == From
&& "Expected valid mapping");
414 if (isa
<LocalAsMetadata
>(MD
)) {
415 if (auto *C
= dyn_cast
<Constant
>(To
)) {
416 // Local became a constant.
417 MD
->replaceAllUsesWith(ConstantAsMetadata::get(C
));
421 if (getLocalFunctionMetadata(From
) && getLocalFunctionMetadata(To
) &&
422 getLocalFunctionMetadata(From
) != getLocalFunctionMetadata(To
)) {
423 // DISubprogram changed.
424 MD
->replaceAllUsesWith(nullptr);
428 } else if (!isa
<Constant
>(To
)) {
429 // Changed to function-local value.
430 MD
->replaceAllUsesWith(nullptr);
435 auto *&Entry
= Store
[To
];
437 // The target already exists.
438 MD
->replaceAllUsesWith(Entry
);
443 // Update MD in place (and update the map entry).
444 assert(!To
->IsUsedByMD
&& "Expected this to be the only metadata use");
445 To
->IsUsedByMD
= true;
450 //===----------------------------------------------------------------------===//
451 // MDString implementation.
454 MDString
*MDString::get(LLVMContext
&Context
, StringRef Str
) {
455 auto &Store
= Context
.pImpl
->MDStringCache
;
456 auto I
= Store
.try_emplace(Str
);
457 auto &MapEntry
= I
.first
->getValue();
460 MapEntry
.Entry
= &*I
.first
;
464 StringRef
MDString::getString() const {
465 assert(Entry
&& "Expected to find string map entry");
466 return Entry
->first();
469 //===----------------------------------------------------------------------===//
470 // MDNode implementation.
473 // Assert that the MDNode types will not be unaligned by the objects
474 // prepended to them.
475 #define HANDLE_MDNODE_LEAF(CLASS) \
477 alignof(uint64_t) >= alignof(CLASS), \
478 "Alignment is insufficient after objects prepended to " #CLASS);
479 #include "llvm/IR/Metadata.def"
481 void *MDNode::operator new(size_t Size
, unsigned NumOps
) {
482 size_t OpSize
= NumOps
* sizeof(MDOperand
);
483 // uint64_t is the most aligned type we need support (ensured by static_assert
485 OpSize
= alignTo(OpSize
, alignof(uint64_t));
486 void *Ptr
= reinterpret_cast<char *>(::operator new(OpSize
+ Size
)) + OpSize
;
487 MDOperand
*O
= static_cast<MDOperand
*>(Ptr
);
488 for (MDOperand
*E
= O
- NumOps
; O
!= E
; --O
)
489 (void)new (O
- 1) MDOperand
;
493 void MDNode::operator delete(void *Mem
) {
494 MDNode
*N
= static_cast<MDNode
*>(Mem
);
495 size_t OpSize
= N
->NumOperands
* sizeof(MDOperand
);
496 OpSize
= alignTo(OpSize
, alignof(uint64_t));
498 MDOperand
*O
= static_cast<MDOperand
*>(Mem
);
499 for (MDOperand
*E
= O
- N
->NumOperands
; O
!= E
; --O
)
500 (O
- 1)->~MDOperand();
501 ::operator delete(reinterpret_cast<char *>(Mem
) - OpSize
);
504 MDNode::MDNode(LLVMContext
&Context
, unsigned ID
, StorageType Storage
,
505 ArrayRef
<Metadata
*> Ops1
, ArrayRef
<Metadata
*> Ops2
)
506 : Metadata(ID
, Storage
), NumOperands(Ops1
.size() + Ops2
.size()),
507 NumUnresolved(0), Context(Context
) {
509 for (Metadata
*MD
: Ops1
)
510 setOperand(Op
++, MD
);
511 for (Metadata
*MD
: Ops2
)
512 setOperand(Op
++, MD
);
517 // Count the unresolved operands. If there are any, RAUW support will be
518 // added lazily on first reference.
519 countUnresolvedOperands();
522 TempMDNode
MDNode::clone() const {
523 switch (getMetadataID()) {
525 llvm_unreachable("Invalid MDNode subclass");
526 #define HANDLE_MDNODE_LEAF(CLASS) \
528 return cast<CLASS>(this)->cloneImpl();
529 #include "llvm/IR/Metadata.def"
533 static bool isOperandUnresolved(Metadata
*Op
) {
534 if (auto *N
= dyn_cast_or_null
<MDNode
>(Op
))
535 return !N
->isResolved();
539 void MDNode::countUnresolvedOperands() {
540 assert(NumUnresolved
== 0 && "Expected unresolved ops to be uncounted");
541 assert(isUniqued() && "Expected this to be uniqued");
542 NumUnresolved
= count_if(operands(), isOperandUnresolved
);
545 void MDNode::makeUniqued() {
546 assert(isTemporary() && "Expected this to be temporary");
547 assert(!isResolved() && "Expected this to be unresolved");
549 // Enable uniquing callbacks.
550 for (auto &Op
: mutable_operands())
551 Op
.reset(Op
.get(), this);
553 // Make this 'uniqued'.
555 countUnresolvedOperands();
556 if (!NumUnresolved
) {
557 dropReplaceableUses();
558 assert(isResolved() && "Expected this to be resolved");
561 assert(isUniqued() && "Expected this to be uniqued");
564 void MDNode::makeDistinct() {
565 assert(isTemporary() && "Expected this to be temporary");
566 assert(!isResolved() && "Expected this to be unresolved");
568 // Drop RAUW support and store as a distinct node.
569 dropReplaceableUses();
570 storeDistinctInContext();
572 assert(isDistinct() && "Expected this to be distinct");
573 assert(isResolved() && "Expected this to be resolved");
576 void MDNode::resolve() {
577 assert(isUniqued() && "Expected this to be uniqued");
578 assert(!isResolved() && "Expected this to be unresolved");
581 dropReplaceableUses();
583 assert(isResolved() && "Expected this to be resolved");
586 void MDNode::dropReplaceableUses() {
587 assert(!NumUnresolved
&& "Unexpected unresolved operand");
589 // Drop any RAUW support.
590 if (Context
.hasReplaceableUses())
591 Context
.takeReplaceableUses()->resolveAllUses();
594 void MDNode::resolveAfterOperandChange(Metadata
*Old
, Metadata
*New
) {
595 assert(isUniqued() && "Expected this to be uniqued");
596 assert(NumUnresolved
!= 0 && "Expected unresolved operands");
598 // Check if an operand was resolved.
599 if (!isOperandUnresolved(Old
)) {
600 if (isOperandUnresolved(New
))
601 // An operand was un-resolved!
603 } else if (!isOperandUnresolved(New
))
604 decrementUnresolvedOperandCount();
607 void MDNode::decrementUnresolvedOperandCount() {
608 assert(!isResolved() && "Expected this to be unresolved");
612 assert(isUniqued() && "Expected this to be uniqued");
616 // Last unresolved operand has just been resolved.
617 dropReplaceableUses();
618 assert(isResolved() && "Expected this to become resolved");
621 void MDNode::resolveCycles() {
625 // Resolve this node immediately.
628 // Resolve all operands.
629 for (const auto &Op
: operands()) {
630 auto *N
= dyn_cast_or_null
<MDNode
>(Op
);
634 assert(!N
->isTemporary() &&
635 "Expected all forward declarations to be resolved");
636 if (!N
->isResolved())
641 static bool hasSelfReference(MDNode
*N
) {
642 for (Metadata
*MD
: N
->operands())
648 MDNode
*MDNode::replaceWithPermanentImpl() {
649 switch (getMetadataID()) {
651 // If this type isn't uniquable, replace with a distinct node.
652 return replaceWithDistinctImpl();
654 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
657 #include "llvm/IR/Metadata.def"
660 // Even if this type is uniquable, self-references have to be distinct.
661 if (hasSelfReference(this))
662 return replaceWithDistinctImpl();
663 return replaceWithUniquedImpl();
666 MDNode
*MDNode::replaceWithUniquedImpl() {
667 // Try to uniquify in place.
668 MDNode
*UniquedNode
= uniquify();
670 if (UniquedNode
== this) {
675 // Collision, so RAUW instead.
676 replaceAllUsesWith(UniquedNode
);
681 MDNode
*MDNode::replaceWithDistinctImpl() {
686 void MDTuple::recalculateHash() {
687 setHash(MDTupleInfo::KeyTy::calculateHash(this));
690 void MDNode::dropAllReferences() {
691 for (unsigned I
= 0, E
= NumOperands
; I
!= E
; ++I
)
692 setOperand(I
, nullptr);
693 if (Context
.hasReplaceableUses()) {
694 Context
.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
695 (void)Context
.takeReplaceableUses();
699 void MDNode::handleChangedOperand(void *Ref
, Metadata
*New
) {
700 unsigned Op
= static_cast<MDOperand
*>(Ref
) - op_begin();
701 assert(Op
< getNumOperands() && "Expected valid operand");
704 // This node is not uniqued. Just set the operand and be done with it.
709 // This node is uniqued.
712 Metadata
*Old
= getOperand(Op
);
715 // Drop uniquing for self-reference cycles and deleted constants.
716 if (New
== this || (!New
&& Old
&& isa
<ConstantAsMetadata
>(Old
))) {
719 storeDistinctInContext();
723 // Re-unique the node.
724 auto *Uniqued
= uniquify();
725 if (Uniqued
== this) {
727 resolveAfterOperandChange(Old
, New
);
733 // Still unresolved, so RAUW.
735 // First, clear out all operands to prevent any recursion (similar to
736 // dropAllReferences(), but we still need the use-list).
737 for (unsigned O
= 0, E
= getNumOperands(); O
!= E
; ++O
)
738 setOperand(O
, nullptr);
739 if (Context
.hasReplaceableUses())
740 Context
.getReplaceableUses()->replaceAllUsesWith(Uniqued
);
745 // Store in non-uniqued form if RAUW isn't possible.
746 storeDistinctInContext();
749 void MDNode::deleteAsSubclass() {
750 switch (getMetadataID()) {
752 llvm_unreachable("Invalid subclass of MDNode");
753 #define HANDLE_MDNODE_LEAF(CLASS) \
755 delete cast<CLASS>(this); \
757 #include "llvm/IR/Metadata.def"
761 template <class T
, class InfoT
>
762 static T
*uniquifyImpl(T
*N
, DenseSet
<T
*, InfoT
> &Store
) {
763 if (T
*U
= getUniqued(Store
, N
))
770 template <class NodeTy
> struct MDNode::HasCachedHash
{
773 template <class U
, U Val
> struct SFINAE
{};
776 static Yes
&check(SFINAE
<void (U::*)(unsigned), &U::setHash
> *);
777 template <class U
> static No
&check(...);
779 static const bool value
= sizeof(check
<NodeTy
>(nullptr)) == sizeof(Yes
);
782 MDNode
*MDNode::uniquify() {
783 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
785 // Try to insert into uniquing store.
786 switch (getMetadataID()) {
788 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
789 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
790 case CLASS##Kind: { \
791 CLASS *SubclassThis = cast<CLASS>(this); \
792 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
793 ShouldRecalculateHash; \
794 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
795 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
797 #include "llvm/IR/Metadata.def"
801 void MDNode::eraseFromStore() {
802 switch (getMetadataID()) {
804 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
805 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
807 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
809 #include "llvm/IR/Metadata.def"
813 MDTuple
*MDTuple::getImpl(LLVMContext
&Context
, ArrayRef
<Metadata
*> MDs
,
814 StorageType Storage
, bool ShouldCreate
) {
816 if (Storage
== Uniqued
) {
817 MDTupleInfo::KeyTy
Key(MDs
);
818 if (auto *N
= getUniqued(Context
.pImpl
->MDTuples
, Key
))
822 Hash
= Key
.getHash();
824 assert(ShouldCreate
&& "Expected non-uniqued nodes to always be created");
827 return storeImpl(new (MDs
.size()) MDTuple(Context
, Storage
, Hash
, MDs
),
828 Storage
, Context
.pImpl
->MDTuples
);
831 void MDNode::deleteTemporary(MDNode
*N
) {
832 assert(N
->isTemporary() && "Expected temporary node");
833 N
->replaceAllUsesWith(nullptr);
834 N
->deleteAsSubclass();
837 void MDNode::storeDistinctInContext() {
838 assert(!Context
.hasReplaceableUses() && "Unexpected replaceable uses");
839 assert(!NumUnresolved
&& "Unexpected unresolved nodes");
841 assert(isResolved() && "Expected this to be resolved");
844 switch (getMetadataID()) {
846 llvm_unreachable("Invalid subclass of MDNode");
847 #define HANDLE_MDNODE_LEAF(CLASS) \
848 case CLASS##Kind: { \
849 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
850 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
853 #include "llvm/IR/Metadata.def"
856 getContext().pImpl
->DistinctMDNodes
.push_back(this);
859 void MDNode::replaceOperandWith(unsigned I
, Metadata
*New
) {
860 if (getOperand(I
) == New
)
868 handleChangedOperand(mutable_begin() + I
, New
);
871 void MDNode::setOperand(unsigned I
, Metadata
*New
) {
872 assert(I
< NumOperands
);
873 mutable_begin()[I
].reset(New
, isUniqued() ? this : nullptr);
876 /// Get a node or a self-reference that looks like it.
878 /// Special handling for finding self-references, for use by \a
879 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
880 /// when self-referencing nodes were still uniqued. If the first operand has
881 /// the same operands as \c Ops, return the first operand instead.
882 static MDNode
*getOrSelfReference(LLVMContext
&Context
,
883 ArrayRef
<Metadata
*> Ops
) {
885 if (MDNode
*N
= dyn_cast_or_null
<MDNode
>(Ops
[0]))
886 if (N
->getNumOperands() == Ops
.size() && N
== N
->getOperand(0)) {
887 for (unsigned I
= 1, E
= Ops
.size(); I
!= E
; ++I
)
888 if (Ops
[I
] != N
->getOperand(I
))
889 return MDNode::get(Context
, Ops
);
893 return MDNode::get(Context
, Ops
);
896 MDNode
*MDNode::concatenate(MDNode
*A
, MDNode
*B
) {
902 SmallSetVector
<Metadata
*, 4> MDs(A
->op_begin(), A
->op_end());
903 MDs
.insert(B
->op_begin(), B
->op_end());
905 // FIXME: This preserves long-standing behaviour, but is it really the right
906 // behaviour? Or was that an unintended side-effect of node uniquing?
907 return getOrSelfReference(A
->getContext(), MDs
.getArrayRef());
910 MDNode
*MDNode::intersect(MDNode
*A
, MDNode
*B
) {
914 SmallSetVector
<Metadata
*, 4> MDs(A
->op_begin(), A
->op_end());
915 SmallPtrSet
<Metadata
*, 4> BSet(B
->op_begin(), B
->op_end());
916 MDs
.remove_if([&](Metadata
*MD
) { return !is_contained(BSet
, MD
); });
918 // FIXME: This preserves long-standing behaviour, but is it really the right
919 // behaviour? Or was that an unintended side-effect of node uniquing?
920 return getOrSelfReference(A
->getContext(), MDs
.getArrayRef());
923 MDNode
*MDNode::getMostGenericAliasScope(MDNode
*A
, MDNode
*B
) {
927 return concatenate(A
, B
);
930 MDNode
*MDNode::getMostGenericFPMath(MDNode
*A
, MDNode
*B
) {
934 APFloat AVal
= mdconst::extract
<ConstantFP
>(A
->getOperand(0))->getValueAPF();
935 APFloat BVal
= mdconst::extract
<ConstantFP
>(B
->getOperand(0))->getValueAPF();
936 if (AVal
.compare(BVal
) == APFloat::cmpLessThan
)
941 static bool isContiguous(const ConstantRange
&A
, const ConstantRange
&B
) {
942 return A
.getUpper() == B
.getLower() || A
.getLower() == B
.getUpper();
945 static bool canBeMerged(const ConstantRange
&A
, const ConstantRange
&B
) {
946 return !A
.intersectWith(B
).isEmptySet() || isContiguous(A
, B
);
949 static bool tryMergeRange(SmallVectorImpl
<ConstantInt
*> &EndPoints
,
950 ConstantInt
*Low
, ConstantInt
*High
) {
951 ConstantRange
NewRange(Low
->getValue(), High
->getValue());
952 unsigned Size
= EndPoints
.size();
953 APInt LB
= EndPoints
[Size
- 2]->getValue();
954 APInt LE
= EndPoints
[Size
- 1]->getValue();
955 ConstantRange
LastRange(LB
, LE
);
956 if (canBeMerged(NewRange
, LastRange
)) {
957 ConstantRange Union
= LastRange
.unionWith(NewRange
);
958 Type
*Ty
= High
->getType();
959 EndPoints
[Size
- 2] =
960 cast
<ConstantInt
>(ConstantInt::get(Ty
, Union
.getLower()));
961 EndPoints
[Size
- 1] =
962 cast
<ConstantInt
>(ConstantInt::get(Ty
, Union
.getUpper()));
968 static void addRange(SmallVectorImpl
<ConstantInt
*> &EndPoints
,
969 ConstantInt
*Low
, ConstantInt
*High
) {
970 if (!EndPoints
.empty())
971 if (tryMergeRange(EndPoints
, Low
, High
))
974 EndPoints
.push_back(Low
);
975 EndPoints
.push_back(High
);
978 MDNode
*MDNode::getMostGenericRange(MDNode
*A
, MDNode
*B
) {
979 // Given two ranges, we want to compute the union of the ranges. This
980 // is slightly complicated by having to combine the intervals and merge
981 // the ones that overlap.
989 // First, walk both lists in order of the lower boundary of each interval.
990 // At each step, try to merge the new interval to the last one we adedd.
991 SmallVector
<ConstantInt
*, 4> EndPoints
;
994 int AN
= A
->getNumOperands() / 2;
995 int BN
= B
->getNumOperands() / 2;
996 while (AI
< AN
&& BI
< BN
) {
997 ConstantInt
*ALow
= mdconst::extract
<ConstantInt
>(A
->getOperand(2 * AI
));
998 ConstantInt
*BLow
= mdconst::extract
<ConstantInt
>(B
->getOperand(2 * BI
));
1000 if (ALow
->getValue().slt(BLow
->getValue())) {
1001 addRange(EndPoints
, ALow
,
1002 mdconst::extract
<ConstantInt
>(A
->getOperand(2 * AI
+ 1)));
1005 addRange(EndPoints
, BLow
,
1006 mdconst::extract
<ConstantInt
>(B
->getOperand(2 * BI
+ 1)));
1011 addRange(EndPoints
, mdconst::extract
<ConstantInt
>(A
->getOperand(2 * AI
)),
1012 mdconst::extract
<ConstantInt
>(A
->getOperand(2 * AI
+ 1)));
1016 addRange(EndPoints
, mdconst::extract
<ConstantInt
>(B
->getOperand(2 * BI
)),
1017 mdconst::extract
<ConstantInt
>(B
->getOperand(2 * BI
+ 1)));
1021 // If we have more than 2 ranges (4 endpoints) we have to try to merge
1022 // the last and first ones.
1023 unsigned Size
= EndPoints
.size();
1025 ConstantInt
*FB
= EndPoints
[0];
1026 ConstantInt
*FE
= EndPoints
[1];
1027 if (tryMergeRange(EndPoints
, FB
, FE
)) {
1028 for (unsigned i
= 0; i
< Size
- 2; ++i
) {
1029 EndPoints
[i
] = EndPoints
[i
+ 2];
1031 EndPoints
.resize(Size
- 2);
1035 // If in the end we have a single range, it is possible that it is now the
1036 // full range. Just drop the metadata in that case.
1037 if (EndPoints
.size() == 2) {
1038 ConstantRange
Range(EndPoints
[0]->getValue(), EndPoints
[1]->getValue());
1039 if (Range
.isFullSet())
1043 SmallVector
<Metadata
*, 4> MDs
;
1044 MDs
.reserve(EndPoints
.size());
1045 for (auto *I
: EndPoints
)
1046 MDs
.push_back(ConstantAsMetadata::get(I
));
1047 return MDNode::get(A
->getContext(), MDs
);
1050 MDNode
*MDNode::getMostGenericAlignmentOrDereferenceable(MDNode
*A
, MDNode
*B
) {
1054 ConstantInt
*AVal
= mdconst::extract
<ConstantInt
>(A
->getOperand(0));
1055 ConstantInt
*BVal
= mdconst::extract
<ConstantInt
>(B
->getOperand(0));
1056 if (AVal
->getZExtValue() < BVal
->getZExtValue())
1061 //===----------------------------------------------------------------------===//
1062 // NamedMDNode implementation.
1065 static SmallVector
<TrackingMDRef
, 4> &getNMDOps(void *Operands
) {
1066 return *(SmallVector
<TrackingMDRef
, 4> *)Operands
;
1069 NamedMDNode::NamedMDNode(const Twine
&N
)
1070 : Name(N
.str()), Operands(new SmallVector
<TrackingMDRef
, 4>()) {}
1072 NamedMDNode::~NamedMDNode() {
1073 dropAllReferences();
1074 delete &getNMDOps(Operands
);
1077 unsigned NamedMDNode::getNumOperands() const {
1078 return (unsigned)getNMDOps(Operands
).size();
1081 MDNode
*NamedMDNode::getOperand(unsigned i
) const {
1082 assert(i
< getNumOperands() && "Invalid Operand number!");
1083 auto *N
= getNMDOps(Operands
)[i
].get();
1084 return cast_or_null
<MDNode
>(N
);
1087 void NamedMDNode::addOperand(MDNode
*M
) { getNMDOps(Operands
).emplace_back(M
); }
1089 void NamedMDNode::setOperand(unsigned I
, MDNode
*New
) {
1090 assert(I
< getNumOperands() && "Invalid operand number");
1091 getNMDOps(Operands
)[I
].reset(New
);
1094 void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
1096 void NamedMDNode::clearOperands() { getNMDOps(Operands
).clear(); }
1098 StringRef
NamedMDNode::getName() const { return StringRef(Name
); }
1100 //===----------------------------------------------------------------------===//
1101 // Instruction Metadata method implementations.
1103 void MDAttachmentMap::set(unsigned ID
, MDNode
&MD
) {
1104 for (auto &I
: Attachments
)
1105 if (I
.first
== ID
) {
1106 I
.second
.reset(&MD
);
1109 Attachments
.emplace_back(std::piecewise_construct
, std::make_tuple(ID
),
1110 std::make_tuple(&MD
));
1113 bool MDAttachmentMap::erase(unsigned ID
) {
1117 // Common case is one/last value.
1118 if (Attachments
.back().first
== ID
) {
1119 Attachments
.pop_back();
1123 for (auto I
= Attachments
.begin(), E
= std::prev(Attachments
.end()); I
!= E
;
1125 if (I
->first
== ID
) {
1126 *I
= std::move(Attachments
.back());
1127 Attachments
.pop_back();
1134 MDNode
*MDAttachmentMap::lookup(unsigned ID
) const {
1135 for (const auto &I
: Attachments
)
1141 void MDAttachmentMap::getAll(
1142 SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &Result
) const {
1143 Result
.append(Attachments
.begin(), Attachments
.end());
1145 // Sort the resulting array so it is stable.
1146 if (Result
.size() > 1)
1147 array_pod_sort(Result
.begin(), Result
.end());
1150 void MDGlobalAttachmentMap::insert(unsigned ID
, MDNode
&MD
) {
1151 Attachments
.push_back({ID
, TrackingMDNodeRef(&MD
)});
1154 MDNode
*MDGlobalAttachmentMap::lookup(unsigned ID
) const {
1155 for (const auto &A
: Attachments
)
1161 void MDGlobalAttachmentMap::get(unsigned ID
,
1162 SmallVectorImpl
<MDNode
*> &Result
) const {
1163 for (const auto &A
: Attachments
)
1165 Result
.push_back(A
.Node
);
1168 bool MDGlobalAttachmentMap::erase(unsigned ID
) {
1169 auto I
= std::remove_if(Attachments
.begin(), Attachments
.end(),
1170 [ID
](const Attachment
&A
) { return A
.MDKind
== ID
; });
1171 bool Changed
= I
!= Attachments
.end();
1172 Attachments
.erase(I
, Attachments
.end());
1176 void MDGlobalAttachmentMap::getAll(
1177 SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &Result
) const {
1178 for (const auto &A
: Attachments
)
1179 Result
.emplace_back(A
.MDKind
, A
.Node
);
1181 // Sort the resulting array so it is stable with respect to metadata IDs. We
1182 // need to preserve the original insertion order though.
1184 Result
.begin(), Result
.end(),
1185 [](const std::pair
<unsigned, MDNode
*> &A
,
1186 const std::pair
<unsigned, MDNode
*> &B
) { return A
.first
< B
.first
; });
1189 void Instruction::setMetadata(StringRef Kind
, MDNode
*Node
) {
1190 if (!Node
&& !hasMetadata())
1192 setMetadata(getContext().getMDKindID(Kind
), Node
);
1195 MDNode
*Instruction::getMetadataImpl(StringRef Kind
) const {
1196 return getMetadataImpl(getContext().getMDKindID(Kind
));
1199 void Instruction::dropUnknownNonDebugMetadata(ArrayRef
<unsigned> KnownIDs
) {
1200 if (!hasMetadataHashEntry())
1201 return; // Nothing to remove!
1203 auto &InstructionMetadata
= getContext().pImpl
->InstructionMetadata
;
1205 SmallSet
<unsigned, 4> KnownSet
;
1206 KnownSet
.insert(KnownIDs
.begin(), KnownIDs
.end());
1207 if (KnownSet
.empty()) {
1208 // Just drop our entry at the store.
1209 InstructionMetadata
.erase(this);
1210 setHasMetadataHashEntry(false);
1214 auto &Info
= InstructionMetadata
[this];
1215 Info
.remove_if([&KnownSet
](const std::pair
<unsigned, TrackingMDNodeRef
> &I
) {
1216 return !KnownSet
.count(I
.first
);
1220 // Drop our entry at the store.
1221 InstructionMetadata
.erase(this);
1222 setHasMetadataHashEntry(false);
1226 void Instruction::setMetadata(unsigned KindID
, MDNode
*Node
) {
1227 if (!Node
&& !hasMetadata())
1230 // Handle 'dbg' as a special case since it is not stored in the hash table.
1231 if (KindID
== LLVMContext::MD_dbg
) {
1232 DbgLoc
= DebugLoc(Node
);
1236 // Handle the case when we're adding/updating metadata on an instruction.
1238 auto &Info
= getContext().pImpl
->InstructionMetadata
[this];
1239 assert(!Info
.empty() == hasMetadataHashEntry() &&
1240 "HasMetadata bit is wonked");
1242 setHasMetadataHashEntry(true);
1243 Info
.set(KindID
, *Node
);
1247 // Otherwise, we're removing metadata from an instruction.
1248 assert((hasMetadataHashEntry() ==
1249 (getContext().pImpl
->InstructionMetadata
.count(this) > 0)) &&
1250 "HasMetadata bit out of date!");
1251 if (!hasMetadataHashEntry())
1252 return; // Nothing to remove!
1253 auto &Info
= getContext().pImpl
->InstructionMetadata
[this];
1255 // Handle removal of an existing value.
1261 getContext().pImpl
->InstructionMetadata
.erase(this);
1262 setHasMetadataHashEntry(false);
1265 void Instruction::setAAMetadata(const AAMDNodes
&N
) {
1266 setMetadata(LLVMContext::MD_tbaa
, N
.TBAA
);
1267 setMetadata(LLVMContext::MD_alias_scope
, N
.Scope
);
1268 setMetadata(LLVMContext::MD_noalias
, N
.NoAlias
);
1271 MDNode
*Instruction::getMetadataImpl(unsigned KindID
) const {
1272 // Handle 'dbg' as a special case since it is not stored in the hash table.
1273 if (KindID
== LLVMContext::MD_dbg
)
1274 return DbgLoc
.getAsMDNode();
1276 if (!hasMetadataHashEntry())
1278 auto &Info
= getContext().pImpl
->InstructionMetadata
[this];
1279 assert(!Info
.empty() && "bit out of sync with hash table");
1281 return Info
.lookup(KindID
);
1284 void Instruction::getAllMetadataImpl(
1285 SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &Result
) const {
1288 // Handle 'dbg' as a special case since it is not stored in the hash table.
1291 std::make_pair((unsigned)LLVMContext::MD_dbg
, DbgLoc
.getAsMDNode()));
1292 if (!hasMetadataHashEntry())
1296 assert(hasMetadataHashEntry() &&
1297 getContext().pImpl
->InstructionMetadata
.count(this) &&
1298 "Shouldn't have called this");
1299 const auto &Info
= getContext().pImpl
->InstructionMetadata
.find(this)->second
;
1300 assert(!Info
.empty() && "Shouldn't have called this");
1301 Info
.getAll(Result
);
1304 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1305 SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &Result
) const {
1307 assert(hasMetadataHashEntry() &&
1308 getContext().pImpl
->InstructionMetadata
.count(this) &&
1309 "Shouldn't have called this");
1310 const auto &Info
= getContext().pImpl
->InstructionMetadata
.find(this)->second
;
1311 assert(!Info
.empty() && "Shouldn't have called this");
1312 Info
.getAll(Result
);
1315 bool Instruction::extractProfMetadata(uint64_t &TrueVal
,
1316 uint64_t &FalseVal
) const {
1318 (getOpcode() == Instruction::Br
|| getOpcode() == Instruction::Select
) &&
1319 "Looking for branch weights on something besides branch or select");
1321 auto *ProfileData
= getMetadata(LLVMContext::MD_prof
);
1322 if (!ProfileData
|| ProfileData
->getNumOperands() != 3)
1325 auto *ProfDataName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0));
1326 if (!ProfDataName
|| !ProfDataName
->getString().equals("branch_weights"))
1329 auto *CITrue
= mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(1));
1330 auto *CIFalse
= mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(2));
1331 if (!CITrue
|| !CIFalse
)
1334 TrueVal
= CITrue
->getValue().getZExtValue();
1335 FalseVal
= CIFalse
->getValue().getZExtValue();
1340 bool Instruction::extractProfTotalWeight(uint64_t &TotalVal
) const {
1341 assert((getOpcode() == Instruction::Br
||
1342 getOpcode() == Instruction::Select
||
1343 getOpcode() == Instruction::Call
||
1344 getOpcode() == Instruction::Invoke
||
1345 getOpcode() == Instruction::Switch
) &&
1346 "Looking for branch weights on something besides branch");
1349 auto *ProfileData
= getMetadata(LLVMContext::MD_prof
);
1353 auto *ProfDataName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0));
1357 if (ProfDataName
->getString().equals("branch_weights")) {
1359 for (unsigned i
= 1; i
< ProfileData
->getNumOperands(); i
++) {
1360 auto *V
= mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(i
));
1363 TotalVal
+= V
->getValue().getZExtValue();
1366 } else if (ProfDataName
->getString().equals("VP") &&
1367 ProfileData
->getNumOperands() > 3) {
1368 TotalVal
= mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(2))
1376 void Instruction::clearMetadataHashEntries() {
1377 assert(hasMetadataHashEntry() && "Caller should check");
1378 getContext().pImpl
->InstructionMetadata
.erase(this);
1379 setHasMetadataHashEntry(false);
1382 void GlobalObject::getMetadata(unsigned KindID
,
1383 SmallVectorImpl
<MDNode
*> &MDs
) const {
1385 getContext().pImpl
->GlobalObjectMetadata
[this].get(KindID
, MDs
);
1388 void GlobalObject::getMetadata(StringRef Kind
,
1389 SmallVectorImpl
<MDNode
*> &MDs
) const {
1391 getMetadata(getContext().getMDKindID(Kind
), MDs
);
1394 void GlobalObject::addMetadata(unsigned KindID
, MDNode
&MD
) {
1396 setHasMetadataHashEntry(true);
1398 getContext().pImpl
->GlobalObjectMetadata
[this].insert(KindID
, MD
);
1401 void GlobalObject::addMetadata(StringRef Kind
, MDNode
&MD
) {
1402 addMetadata(getContext().getMDKindID(Kind
), MD
);
1405 bool GlobalObject::eraseMetadata(unsigned KindID
) {
1406 // Nothing to unset.
1410 auto &Store
= getContext().pImpl
->GlobalObjectMetadata
[this];
1411 bool Changed
= Store
.erase(KindID
);
1417 void GlobalObject::getAllMetadata(
1418 SmallVectorImpl
<std::pair
<unsigned, MDNode
*>> &MDs
) const {
1424 getContext().pImpl
->GlobalObjectMetadata
[this].getAll(MDs
);
1427 void GlobalObject::clearMetadata() {
1430 getContext().pImpl
->GlobalObjectMetadata
.erase(this);
1431 setHasMetadataHashEntry(false);
1434 void GlobalObject::setMetadata(unsigned KindID
, MDNode
*N
) {
1435 eraseMetadata(KindID
);
1437 addMetadata(KindID
, *N
);
1440 void GlobalObject::setMetadata(StringRef Kind
, MDNode
*N
) {
1441 setMetadata(getContext().getMDKindID(Kind
), N
);
1444 MDNode
*GlobalObject::getMetadata(unsigned KindID
) const {
1446 return getContext().pImpl
->GlobalObjectMetadata
[this].lookup(KindID
);
1450 MDNode
*GlobalObject::getMetadata(StringRef Kind
) const {
1451 return getMetadata(getContext().getMDKindID(Kind
));
1454 void GlobalObject::copyMetadata(const GlobalObject
*Other
, unsigned Offset
) {
1455 SmallVector
<std::pair
<unsigned, MDNode
*>, 8> MDs
;
1456 Other
->getAllMetadata(MDs
);
1457 for (auto &MD
: MDs
) {
1458 // We need to adjust the type metadata offset.
1459 if (Offset
!= 0 && MD
.first
== LLVMContext::MD_type
) {
1460 auto *OffsetConst
= cast
<ConstantInt
>(
1461 cast
<ConstantAsMetadata
>(MD
.second
->getOperand(0))->getValue());
1462 Metadata
*TypeId
= MD
.second
->getOperand(1);
1463 auto *NewOffsetMD
= ConstantAsMetadata::get(ConstantInt::get(
1464 OffsetConst
->getType(), OffsetConst
->getValue() + Offset
));
1465 addMetadata(LLVMContext::MD_type
,
1466 *MDNode::get(getContext(), {NewOffsetMD
, TypeId
}));
1469 // If an offset adjustment was specified we need to modify the DIExpression
1470 // to prepend the adjustment:
1471 // !DIExpression(DW_OP_plus, Offset, [original expr])
1472 auto *Attachment
= MD
.second
;
1473 if (Offset
!= 0 && MD
.first
== LLVMContext::MD_dbg
) {
1474 DIGlobalVariable
*GV
= dyn_cast
<DIGlobalVariable
>(Attachment
);
1475 DIExpression
*E
= nullptr;
1477 auto *GVE
= cast
<DIGlobalVariableExpression
>(Attachment
);
1478 GV
= GVE
->getVariable();
1479 E
= GVE
->getExpression();
1481 ArrayRef
<uint64_t> OrigElements
;
1483 OrigElements
= E
->getElements();
1484 std::vector
<uint64_t> Elements(OrigElements
.size() + 2);
1485 Elements
[0] = dwarf::DW_OP_plus_uconst
;
1486 Elements
[1] = Offset
;
1487 std::copy(OrigElements
.begin(), OrigElements
.end(), Elements
.begin() + 2);
1488 E
= DIExpression::get(getContext(), Elements
);
1489 Attachment
= DIGlobalVariableExpression::get(getContext(), GV
, E
);
1491 addMetadata(MD
.first
, *Attachment
);
1495 void GlobalObject::addTypeMetadata(unsigned Offset
, Metadata
*TypeID
) {
1497 LLVMContext::MD_type
,
1498 *MDTuple::get(getContext(),
1499 {ConstantAsMetadata::get(ConstantInt::get(
1500 Type::getInt64Ty(getContext()), Offset
)),
1504 void Function::setSubprogram(DISubprogram
*SP
) {
1505 setMetadata(LLVMContext::MD_dbg
, SP
);
1508 DISubprogram
*Function::getSubprogram() const {
1509 return cast_or_null
<DISubprogram
>(getMetadata(LLVMContext::MD_dbg
));
1512 bool Function::isDebugInfoForProfiling() const {
1513 if (DISubprogram
*SP
= getSubprogram()) {
1514 if (DICompileUnit
*CU
= SP
->getUnit()) {
1515 return CU
->getDebugInfoForProfiling();
1521 void GlobalVariable::addDebugInfo(DIGlobalVariableExpression
*GV
) {
1522 addMetadata(LLVMContext::MD_dbg
, *GV
);
1525 void GlobalVariable::getDebugInfo(
1526 SmallVectorImpl
<DIGlobalVariableExpression
*> &GVs
) const {
1527 SmallVector
<MDNode
*, 1> MDs
;
1528 getMetadata(LLVMContext::MD_dbg
, MDs
);
1529 for (MDNode
*MD
: MDs
)
1530 GVs
.push_back(cast
<DIGlobalVariableExpression
>(MD
));