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/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/ConstantRange.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfoMetadata.h"
35 #include "llvm/IR/DebugLoc.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalObject.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/TrackingMDRef.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/IR/ValueHandle.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
61 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
62 : Value(Ty, MetadataAsValueVal), MD(MD) {
66 MetadataAsValue::~MetadataAsValue() {
67 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
71 /// Canonicalize metadata arguments to intrinsics.
73 /// To support bitcode upgrades (and assembly semantic sugar) for \a
74 /// MetadataAsValue, we need to canonicalize certain metadata.
76 /// - nullptr is replaced by an empty MDNode.
77 /// - An MDNode with a single null operand is replaced by an empty MDNode.
78 /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
80 /// This maintains readability of bitcode from when metadata was a type of
81 /// value, and these bridges were unnecessary.
82 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
86 return MDNode::get(Context, None);
88 // Return early if this isn't a single-operand MDNode.
89 auto *N = dyn_cast<MDNode>(MD);
90 if (!N || N->getNumOperands() != 1)
93 if (!N->getOperand(0))
95 return MDNode::get(Context, None);
97 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
98 // Look through the MDNode.
104 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
105 MD = canonicalizeMetadataForValue(Context, MD);
106 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
108 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
112 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
114 MD = canonicalizeMetadataForValue(Context, MD);
115 auto &Store = Context.pImpl->MetadataAsValues;
116 return Store.lookup(MD);
119 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
120 LLVMContext &Context = getContext();
121 MD = canonicalizeMetadataForValue(Context, MD);
122 auto &Store = Context.pImpl->MetadataAsValues;
124 // Stop tracking the old metadata.
125 Store.erase(this->MD);
129 // Start tracking MD, or RAUW if necessary.
130 auto *&Entry = Store[MD];
132 replaceAllUsesWith(Entry);
142 void MetadataAsValue::track() {
144 MetadataTracking::track(&MD, *MD, *this);
147 void MetadataAsValue::untrack() {
149 MetadataTracking::untrack(MD);
152 bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
153 assert(Ref && "Expected live reference");
154 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
155 "Reference without owner must be direct");
156 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
157 R->addRef(Ref, Owner);
160 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
161 assert(!PH->Use && "Placeholders can only be used once");
162 assert(!Owner && "Unexpected callback to owner");
163 PH->Use = static_cast<Metadata **>(Ref);
169 void MetadataTracking::untrack(void *Ref, Metadata &MD) {
170 assert(Ref && "Expected live reference");
171 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
173 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
177 bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
178 assert(Ref && "Expected live reference");
179 assert(New && "Expected live reference");
180 assert(Ref != New && "Expected change");
181 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
182 R->moveRef(Ref, New, MD);
185 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
186 "Unexpected move of an MDOperand");
187 assert(!isReplaceable(MD) &&
188 "Expected un-replaceable metadata, since we didn't move a reference");
192 bool MetadataTracking::isReplaceable(const Metadata &MD) {
193 return ReplaceableMetadataImpl::isReplaceable(MD);
196 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
198 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
201 assert(WasInserted && "Expected to add a reference");
204 assert(NextIndex != 0 && "Unexpected overflow");
207 void ReplaceableMetadataImpl::dropRef(void *Ref) {
208 bool WasErased = UseMap.erase(Ref);
210 assert(WasErased && "Expected to drop a reference");
213 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
214 const Metadata &MD) {
215 auto I = UseMap.find(Ref);
216 assert(I != UseMap.end() && "Expected to move a reference");
217 auto OwnerAndIndex = I->second;
219 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
221 assert(WasInserted && "Expected to add a reference");
223 // Check that the references are direct if there's no owner.
225 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
226 "Reference without owner must be direct");
227 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
228 "Reference without owner must be direct");
231 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
235 // Copy out uses since UseMap will get touched below.
236 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
237 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
238 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
239 return L.second.second < R.second.second;
241 for (const auto &Pair : Uses) {
242 // Check that this Ref hasn't disappeared after RAUW (when updating a
244 if (!UseMap.count(Pair.first))
247 OwnerTy Owner = Pair.second.first;
249 // Update unowned tracking references directly.
250 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
253 MetadataTracking::track(Ref);
254 UseMap.erase(Pair.first);
258 // Check for MetadataAsValue.
259 if (Owner.is<MetadataAsValue *>()) {
260 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
264 // There's a Metadata owner -- dispatch.
265 Metadata *OwnerMD = Owner.get<Metadata *>();
266 switch (OwnerMD->getMetadataID()) {
267 #define HANDLE_METADATA_LEAF(CLASS) \
268 case Metadata::CLASS##Kind: \
269 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
271 #include "llvm/IR/Metadata.def"
273 llvm_unreachable("Invalid metadata subclass");
276 assert(UseMap.empty() && "Expected all uses to be replaced");
279 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
288 // Copy out uses since UseMap could get touched below.
289 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
290 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
291 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
292 return L.second.second < R.second.second;
295 for (const auto &Pair : Uses) {
296 auto Owner = Pair.second.first;
299 if (Owner.is<MetadataAsValue *>())
302 // Resolve MDNodes that point at this.
303 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
306 if (OwnerMD->isResolved())
308 OwnerMD->decrementUnresolvedOperandCount();
312 ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
313 if (auto *N = dyn_cast<MDNode>(&MD))
314 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
315 return dyn_cast<ValueAsMetadata>(&MD);
318 ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
319 if (auto *N = dyn_cast<MDNode>(&MD))
320 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
321 return dyn_cast<ValueAsMetadata>(&MD);
324 bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
325 if (auto *N = dyn_cast<MDNode>(&MD))
326 return !N->isResolved();
327 return dyn_cast<ValueAsMetadata>(&MD);
330 static Function *getLocalFunction(Value *V) {
331 assert(V && "Expected value");
332 if (auto *A = dyn_cast<Argument>(V))
333 return A->getParent();
334 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
335 return BB->getParent();
339 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
340 assert(V && "Unexpected null Value");
342 auto &Context = V->getContext();
343 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
345 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
346 "Expected constant or function-local value");
347 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
348 V->IsUsedByMD = true;
349 if (auto *C = dyn_cast<Constant>(V))
350 Entry = new ConstantAsMetadata(C);
352 Entry = new LocalAsMetadata(V);
358 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
359 assert(V && "Unexpected null Value");
360 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
363 void ValueAsMetadata::handleDeletion(Value *V) {
364 assert(V && "Expected valid value");
366 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
367 auto I = Store.find(V);
368 if (I == Store.end())
371 // Remove old entry from the map.
372 ValueAsMetadata *MD = I->second;
373 assert(MD && "Expected valid metadata");
374 assert(MD->getValue() == V && "Expected valid mapping");
377 // Delete the metadata.
378 MD->replaceAllUsesWith(nullptr);
382 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
383 assert(From && "Expected valid value");
384 assert(To && "Expected valid value");
385 assert(From != To && "Expected changed value");
386 assert(From->getType() == To->getType() && "Unexpected type change");
388 LLVMContext &Context = From->getType()->getContext();
389 auto &Store = Context.pImpl->ValuesAsMetadata;
390 auto I = Store.find(From);
391 if (I == Store.end()) {
392 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
396 // Remove old entry from the map.
397 assert(From->IsUsedByMD && "Expected From to be used by metadata");
398 From->IsUsedByMD = false;
399 ValueAsMetadata *MD = I->second;
400 assert(MD && "Expected valid metadata");
401 assert(MD->getValue() == From && "Expected valid mapping");
404 if (isa<LocalAsMetadata>(MD)) {
405 if (auto *C = dyn_cast<Constant>(To)) {
406 // Local became a constant.
407 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
411 if (getLocalFunction(From) && getLocalFunction(To) &&
412 getLocalFunction(From) != getLocalFunction(To)) {
414 MD->replaceAllUsesWith(nullptr);
418 } else if (!isa<Constant>(To)) {
419 // Changed to function-local value.
420 MD->replaceAllUsesWith(nullptr);
425 auto *&Entry = Store[To];
427 // The target already exists.
428 MD->replaceAllUsesWith(Entry);
433 // Update MD in place (and update the map entry).
434 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
435 To->IsUsedByMD = true;
440 //===----------------------------------------------------------------------===//
441 // MDString implementation.
444 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
445 auto &Store = Context.pImpl->MDStringCache;
446 auto I = Store.try_emplace(Str);
447 auto &MapEntry = I.first->getValue();
450 MapEntry.Entry = &*I.first;
454 StringRef MDString::getString() const {
455 assert(Entry && "Expected to find string map entry");
456 return Entry->first();
459 //===----------------------------------------------------------------------===//
460 // MDNode implementation.
463 // Assert that the MDNode types will not be unaligned by the objects
464 // prepended to them.
465 #define HANDLE_MDNODE_LEAF(CLASS) \
467 alignof(uint64_t) >= alignof(CLASS), \
468 "Alignment is insufficient after objects prepended to " #CLASS);
469 #include "llvm/IR/Metadata.def"
471 void *MDNode::operator new(size_t Size, unsigned NumOps) {
472 size_t OpSize = NumOps * sizeof(MDOperand);
473 // uint64_t is the most aligned type we need support (ensured by static_assert
475 OpSize = alignTo(OpSize, alignof(uint64_t));
476 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
477 MDOperand *O = static_cast<MDOperand *>(Ptr);
478 for (MDOperand *E = O - NumOps; O != E; --O)
479 (void)new (O - 1) MDOperand;
483 void MDNode::operator delete(void *Mem) {
484 MDNode *N = static_cast<MDNode *>(Mem);
485 size_t OpSize = N->NumOperands * sizeof(MDOperand);
486 OpSize = alignTo(OpSize, alignof(uint64_t));
488 MDOperand *O = static_cast<MDOperand *>(Mem);
489 for (MDOperand *E = O - N->NumOperands; O != E; --O)
490 (O - 1)->~MDOperand();
491 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
494 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
495 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
496 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
497 NumUnresolved(0), Context(Context) {
499 for (Metadata *MD : Ops1)
500 setOperand(Op++, MD);
501 for (Metadata *MD : Ops2)
502 setOperand(Op++, MD);
507 // Count the unresolved operands. If there are any, RAUW support will be
508 // added lazily on first reference.
509 countUnresolvedOperands();
512 TempMDNode MDNode::clone() const {
513 switch (getMetadataID()) {
515 llvm_unreachable("Invalid MDNode subclass");
516 #define HANDLE_MDNODE_LEAF(CLASS) \
518 return cast<CLASS>(this)->cloneImpl();
519 #include "llvm/IR/Metadata.def"
523 static bool isOperandUnresolved(Metadata *Op) {
524 if (auto *N = dyn_cast_or_null<MDNode>(Op))
525 return !N->isResolved();
529 void MDNode::countUnresolvedOperands() {
530 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
531 assert(isUniqued() && "Expected this to be uniqued");
532 NumUnresolved = count_if(operands(), isOperandUnresolved);
535 void MDNode::makeUniqued() {
536 assert(isTemporary() && "Expected this to be temporary");
537 assert(!isResolved() && "Expected this to be unresolved");
539 // Enable uniquing callbacks.
540 for (auto &Op : mutable_operands())
541 Op.reset(Op.get(), this);
543 // Make this 'uniqued'.
545 countUnresolvedOperands();
546 if (!NumUnresolved) {
547 dropReplaceableUses();
548 assert(isResolved() && "Expected this to be resolved");
551 assert(isUniqued() && "Expected this to be uniqued");
554 void MDNode::makeDistinct() {
555 assert(isTemporary() && "Expected this to be temporary");
556 assert(!isResolved() && "Expected this to be unresolved");
558 // Drop RAUW support and store as a distinct node.
559 dropReplaceableUses();
560 storeDistinctInContext();
562 assert(isDistinct() && "Expected this to be distinct");
563 assert(isResolved() && "Expected this to be resolved");
566 void MDNode::resolve() {
567 assert(isUniqued() && "Expected this to be uniqued");
568 assert(!isResolved() && "Expected this to be unresolved");
571 dropReplaceableUses();
573 assert(isResolved() && "Expected this to be resolved");
576 void MDNode::dropReplaceableUses() {
577 assert(!NumUnresolved && "Unexpected unresolved operand");
579 // Drop any RAUW support.
580 if (Context.hasReplaceableUses())
581 Context.takeReplaceableUses()->resolveAllUses();
584 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
585 assert(isUniqued() && "Expected this to be uniqued");
586 assert(NumUnresolved != 0 && "Expected unresolved operands");
588 // Check if an operand was resolved.
589 if (!isOperandUnresolved(Old)) {
590 if (isOperandUnresolved(New))
591 // An operand was un-resolved!
593 } else if (!isOperandUnresolved(New))
594 decrementUnresolvedOperandCount();
597 void MDNode::decrementUnresolvedOperandCount() {
598 assert(!isResolved() && "Expected this to be unresolved");
602 assert(isUniqued() && "Expected this to be uniqued");
606 // Last unresolved operand has just been resolved.
607 dropReplaceableUses();
608 assert(isResolved() && "Expected this to become resolved");
611 void MDNode::resolveCycles() {
615 // Resolve this node immediately.
618 // Resolve all operands.
619 for (const auto &Op : operands()) {
620 auto *N = dyn_cast_or_null<MDNode>(Op);
624 assert(!N->isTemporary() &&
625 "Expected all forward declarations to be resolved");
626 if (!N->isResolved())
631 static bool hasSelfReference(MDNode *N) {
632 for (Metadata *MD : N->operands())
638 MDNode *MDNode::replaceWithPermanentImpl() {
639 switch (getMetadataID()) {
641 // If this type isn't uniquable, replace with a distinct node.
642 return replaceWithDistinctImpl();
644 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
647 #include "llvm/IR/Metadata.def"
650 // Even if this type is uniquable, self-references have to be distinct.
651 if (hasSelfReference(this))
652 return replaceWithDistinctImpl();
653 return replaceWithUniquedImpl();
656 MDNode *MDNode::replaceWithUniquedImpl() {
657 // Try to uniquify in place.
658 MDNode *UniquedNode = uniquify();
660 if (UniquedNode == this) {
665 // Collision, so RAUW instead.
666 replaceAllUsesWith(UniquedNode);
671 MDNode *MDNode::replaceWithDistinctImpl() {
676 void MDTuple::recalculateHash() {
677 setHash(MDTupleInfo::KeyTy::calculateHash(this));
680 void MDNode::dropAllReferences() {
681 for (unsigned I = 0, E = NumOperands; I != E; ++I)
682 setOperand(I, nullptr);
683 if (Context.hasReplaceableUses()) {
684 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
685 (void)Context.takeReplaceableUses();
689 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
690 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
691 assert(Op < getNumOperands() && "Expected valid operand");
694 // This node is not uniqued. Just set the operand and be done with it.
699 // This node is uniqued.
702 Metadata *Old = getOperand(Op);
705 // Drop uniquing for self-reference cycles and deleted constants.
706 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
709 storeDistinctInContext();
713 // Re-unique the node.
714 auto *Uniqued = uniquify();
715 if (Uniqued == this) {
717 resolveAfterOperandChange(Old, New);
723 // Still unresolved, so RAUW.
725 // First, clear out all operands to prevent any recursion (similar to
726 // dropAllReferences(), but we still need the use-list).
727 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
728 setOperand(O, nullptr);
729 if (Context.hasReplaceableUses())
730 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
735 // Store in non-uniqued form if RAUW isn't possible.
736 storeDistinctInContext();
739 void MDNode::deleteAsSubclass() {
740 switch (getMetadataID()) {
742 llvm_unreachable("Invalid subclass of MDNode");
743 #define HANDLE_MDNODE_LEAF(CLASS) \
745 delete cast<CLASS>(this); \
747 #include "llvm/IR/Metadata.def"
751 template <class T, class InfoT>
752 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
753 if (T *U = getUniqued(Store, N))
760 template <class NodeTy> struct MDNode::HasCachedHash {
763 template <class U, U Val> struct SFINAE {};
766 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
767 template <class U> static No &check(...);
769 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
772 MDNode *MDNode::uniquify() {
773 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
775 // Try to insert into uniquing store.
776 switch (getMetadataID()) {
778 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
779 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
780 case CLASS##Kind: { \
781 CLASS *SubclassThis = cast<CLASS>(this); \
782 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
783 ShouldRecalculateHash; \
784 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
785 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
787 #include "llvm/IR/Metadata.def"
791 void MDNode::eraseFromStore() {
792 switch (getMetadataID()) {
794 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
795 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
797 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
799 #include "llvm/IR/Metadata.def"
803 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
804 StorageType Storage, bool ShouldCreate) {
806 if (Storage == Uniqued) {
807 MDTupleInfo::KeyTy Key(MDs);
808 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
812 Hash = Key.getHash();
814 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
817 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
818 Storage, Context.pImpl->MDTuples);
821 void MDNode::deleteTemporary(MDNode *N) {
822 assert(N->isTemporary() && "Expected temporary node");
823 N->replaceAllUsesWith(nullptr);
824 N->deleteAsSubclass();
827 void MDNode::storeDistinctInContext() {
828 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
829 assert(!NumUnresolved && "Unexpected unresolved nodes");
831 assert(isResolved() && "Expected this to be resolved");
834 switch (getMetadataID()) {
836 llvm_unreachable("Invalid subclass of MDNode");
837 #define HANDLE_MDNODE_LEAF(CLASS) \
838 case CLASS##Kind: { \
839 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
840 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
843 #include "llvm/IR/Metadata.def"
846 getContext().pImpl->DistinctMDNodes.push_back(this);
849 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
850 if (getOperand(I) == New)
858 handleChangedOperand(mutable_begin() + I, New);
861 void MDNode::setOperand(unsigned I, Metadata *New) {
862 assert(I < NumOperands);
863 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
866 /// Get a node or a self-reference that looks like it.
868 /// Special handling for finding self-references, for use by \a
869 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
870 /// when self-referencing nodes were still uniqued. If the first operand has
871 /// the same operands as \c Ops, return the first operand instead.
872 static MDNode *getOrSelfReference(LLVMContext &Context,
873 ArrayRef<Metadata *> Ops) {
875 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
876 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
877 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
878 if (Ops[I] != N->getOperand(I))
879 return MDNode::get(Context, Ops);
883 return MDNode::get(Context, Ops);
886 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
892 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
893 MDs.insert(B->op_begin(), B->op_end());
895 // FIXME: This preserves long-standing behaviour, but is it really the right
896 // behaviour? Or was that an unintended side-effect of node uniquing?
897 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
900 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
904 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
905 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
906 MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
908 // FIXME: This preserves long-standing behaviour, but is it really the right
909 // behaviour? Or was that an unintended side-effect of node uniquing?
910 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
913 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
917 return concatenate(A, B);
920 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
924 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
925 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
926 if (AVal.compare(BVal) == APFloat::cmpLessThan)
931 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
932 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
935 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
936 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
939 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
940 ConstantInt *Low, ConstantInt *High) {
941 ConstantRange NewRange(Low->getValue(), High->getValue());
942 unsigned Size = EndPoints.size();
943 APInt LB = EndPoints[Size - 2]->getValue();
944 APInt LE = EndPoints[Size - 1]->getValue();
945 ConstantRange LastRange(LB, LE);
946 if (canBeMerged(NewRange, LastRange)) {
947 ConstantRange Union = LastRange.unionWith(NewRange);
948 Type *Ty = High->getType();
949 EndPoints[Size - 2] =
950 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
951 EndPoints[Size - 1] =
952 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
958 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
959 ConstantInt *Low, ConstantInt *High) {
960 if (!EndPoints.empty())
961 if (tryMergeRange(EndPoints, Low, High))
964 EndPoints.push_back(Low);
965 EndPoints.push_back(High);
968 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
969 // Given two ranges, we want to compute the union of the ranges. This
970 // is slightly complicated by having to combine the intervals and merge
971 // the ones that overlap.
979 // First, walk both lists in order of the lower boundary of each interval.
980 // At each step, try to merge the new interval to the last one we adedd.
981 SmallVector<ConstantInt *, 4> EndPoints;
984 int AN = A->getNumOperands() / 2;
985 int BN = B->getNumOperands() / 2;
986 while (AI < AN && BI < BN) {
987 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
988 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
990 if (ALow->getValue().slt(BLow->getValue())) {
991 addRange(EndPoints, ALow,
992 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
995 addRange(EndPoints, BLow,
996 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1001 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1002 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1006 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1007 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1011 // If we have more than 2 ranges (4 endpoints) we have to try to merge
1012 // the last and first ones.
1013 unsigned Size = EndPoints.size();
1015 ConstantInt *FB = EndPoints[0];
1016 ConstantInt *FE = EndPoints[1];
1017 if (tryMergeRange(EndPoints, FB, FE)) {
1018 for (unsigned i = 0; i < Size - 2; ++i) {
1019 EndPoints[i] = EndPoints[i + 2];
1021 EndPoints.resize(Size - 2);
1025 // If in the end we have a single range, it is possible that it is now the
1026 // full range. Just drop the metadata in that case.
1027 if (EndPoints.size() == 2) {
1028 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1029 if (Range.isFullSet())
1033 SmallVector<Metadata *, 4> MDs;
1034 MDs.reserve(EndPoints.size());
1035 for (auto *I : EndPoints)
1036 MDs.push_back(ConstantAsMetadata::get(I));
1037 return MDNode::get(A->getContext(), MDs);
1040 MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1044 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1045 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1046 if (AVal->getZExtValue() < BVal->getZExtValue())
1051 //===----------------------------------------------------------------------===//
1052 // NamedMDNode implementation.
1055 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1056 return *(SmallVector<TrackingMDRef, 4> *)Operands;
1059 NamedMDNode::NamedMDNode(const Twine &N)
1060 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1062 NamedMDNode::~NamedMDNode() {
1063 dropAllReferences();
1064 delete &getNMDOps(Operands);
1067 unsigned NamedMDNode::getNumOperands() const {
1068 return (unsigned)getNMDOps(Operands).size();
1071 MDNode *NamedMDNode::getOperand(unsigned i) const {
1072 assert(i < getNumOperands() && "Invalid Operand number!");
1073 auto *N = getNMDOps(Operands)[i].get();
1074 return cast_or_null<MDNode>(N);
1077 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1079 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1080 assert(I < getNumOperands() && "Invalid operand number");
1081 getNMDOps(Operands)[I].reset(New);
1084 void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
1086 void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1088 StringRef NamedMDNode::getName() const { return StringRef(Name); }
1090 //===----------------------------------------------------------------------===//
1091 // Instruction Metadata method implementations.
1093 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1094 for (auto &I : Attachments)
1095 if (I.first == ID) {
1096 I.second.reset(&MD);
1099 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1100 std::make_tuple(&MD));
1103 void MDAttachmentMap::erase(unsigned ID) {
1107 // Common case is one/last value.
1108 if (Attachments.back().first == ID) {
1109 Attachments.pop_back();
1113 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1115 if (I->first == ID) {
1116 *I = std::move(Attachments.back());
1117 Attachments.pop_back();
1122 MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1123 for (const auto &I : Attachments)
1129 void MDAttachmentMap::getAll(
1130 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1131 Result.append(Attachments.begin(), Attachments.end());
1133 // Sort the resulting array so it is stable.
1134 if (Result.size() > 1)
1135 array_pod_sort(Result.begin(), Result.end());
1138 void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
1139 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1142 void MDGlobalAttachmentMap::get(unsigned ID,
1143 SmallVectorImpl<MDNode *> &Result) {
1144 for (auto A : Attachments)
1146 Result.push_back(A.Node);
1149 void MDGlobalAttachmentMap::erase(unsigned ID) {
1150 auto Follower = Attachments.begin();
1151 for (auto Leader = Attachments.begin(), E = Attachments.end(); Leader != E;
1153 if (Leader->MDKind != ID) {
1154 if (Follower != Leader)
1155 *Follower = std::move(*Leader);
1159 Attachments.resize(Follower - Attachments.begin());
1162 void MDGlobalAttachmentMap::getAll(
1163 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1164 for (auto &A : Attachments)
1165 Result.emplace_back(A.MDKind, A.Node);
1167 // Sort the resulting array so it is stable with respect to metadata IDs. We
1168 // need to preserve the original insertion order though.
1170 Result.begin(), Result.end(),
1171 [](const std::pair<unsigned, MDNode *> &A,
1172 const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1175 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1176 if (!Node && !hasMetadata())
1178 setMetadata(getContext().getMDKindID(Kind), Node);
1181 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1182 return getMetadataImpl(getContext().getMDKindID(Kind));
1185 void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
1186 if (!hasMetadataHashEntry())
1187 return; // Nothing to remove!
1189 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1191 SmallSet<unsigned, 4> KnownSet;
1192 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1193 if (KnownSet.empty()) {
1194 // Just drop our entry at the store.
1195 InstructionMetadata.erase(this);
1196 setHasMetadataHashEntry(false);
1200 auto &Info = InstructionMetadata[this];
1201 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1202 return !KnownSet.count(I.first);
1206 // Drop our entry at the store.
1207 InstructionMetadata.erase(this);
1208 setHasMetadataHashEntry(false);
1212 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1213 if (!Node && !hasMetadata())
1216 // Handle 'dbg' as a special case since it is not stored in the hash table.
1217 if (KindID == LLVMContext::MD_dbg) {
1218 DbgLoc = DebugLoc(Node);
1222 // Handle the case when we're adding/updating metadata on an instruction.
1224 auto &Info = getContext().pImpl->InstructionMetadata[this];
1225 assert(!Info.empty() == hasMetadataHashEntry() &&
1226 "HasMetadata bit is wonked");
1228 setHasMetadataHashEntry(true);
1229 Info.set(KindID, *Node);
1233 // Otherwise, we're removing metadata from an instruction.
1234 assert((hasMetadataHashEntry() ==
1235 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
1236 "HasMetadata bit out of date!");
1237 if (!hasMetadataHashEntry())
1238 return; // Nothing to remove!
1239 auto &Info = getContext().pImpl->InstructionMetadata[this];
1241 // Handle removal of an existing value.
1247 getContext().pImpl->InstructionMetadata.erase(this);
1248 setHasMetadataHashEntry(false);
1251 void Instruction::setAAMetadata(const AAMDNodes &N) {
1252 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1253 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1254 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1257 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1258 // Handle 'dbg' as a special case since it is not stored in the hash table.
1259 if (KindID == LLVMContext::MD_dbg)
1260 return DbgLoc.getAsMDNode();
1262 if (!hasMetadataHashEntry())
1264 auto &Info = getContext().pImpl->InstructionMetadata[this];
1265 assert(!Info.empty() && "bit out of sync with hash table");
1267 return Info.lookup(KindID);
1270 void Instruction::getAllMetadataImpl(
1271 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1274 // Handle 'dbg' as a special case since it is not stored in the hash table.
1277 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1278 if (!hasMetadataHashEntry())
1282 assert(hasMetadataHashEntry() &&
1283 getContext().pImpl->InstructionMetadata.count(this) &&
1284 "Shouldn't have called this");
1285 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1286 assert(!Info.empty() && "Shouldn't have called this");
1287 Info.getAll(Result);
1290 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1291 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1293 assert(hasMetadataHashEntry() &&
1294 getContext().pImpl->InstructionMetadata.count(this) &&
1295 "Shouldn't have called this");
1296 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1297 assert(!Info.empty() && "Shouldn't have called this");
1298 Info.getAll(Result);
1301 bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1302 uint64_t &FalseVal) const {
1304 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1305 "Looking for branch weights on something besides branch or select");
1307 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1308 if (!ProfileData || ProfileData->getNumOperands() != 3)
1311 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1312 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1315 auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1316 auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1317 if (!CITrue || !CIFalse)
1320 TrueVal = CITrue->getValue().getZExtValue();
1321 FalseVal = CIFalse->getValue().getZExtValue();
1326 bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
1327 assert((getOpcode() == Instruction::Br ||
1328 getOpcode() == Instruction::Select ||
1329 getOpcode() == Instruction::Call ||
1330 getOpcode() == Instruction::Invoke ||
1331 getOpcode() == Instruction::Switch) &&
1332 "Looking for branch weights on something besides branch");
1335 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1339 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1343 if (ProfDataName->getString().equals("branch_weights")) {
1345 for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1346 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1349 TotalVal += V->getValue().getZExtValue();
1352 } else if (ProfDataName->getString().equals("VP") &&
1353 ProfileData->getNumOperands() > 3) {
1354 TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1362 void Instruction::clearMetadataHashEntries() {
1363 assert(hasMetadataHashEntry() && "Caller should check");
1364 getContext().pImpl->InstructionMetadata.erase(this);
1365 setHasMetadataHashEntry(false);
1368 void GlobalObject::getMetadata(unsigned KindID,
1369 SmallVectorImpl<MDNode *> &MDs) const {
1371 getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
1374 void GlobalObject::getMetadata(StringRef Kind,
1375 SmallVectorImpl<MDNode *> &MDs) const {
1377 getMetadata(getContext().getMDKindID(Kind), MDs);
1380 void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1382 setHasMetadataHashEntry(true);
1384 getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1387 void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
1388 addMetadata(getContext().getMDKindID(Kind), MD);
1391 void GlobalObject::eraseMetadata(unsigned KindID) {
1392 // Nothing to unset.
1396 auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
1397 Store.erase(KindID);
1402 void GlobalObject::getAllMetadata(
1403 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1409 getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
1412 void GlobalObject::clearMetadata() {
1415 getContext().pImpl->GlobalObjectMetadata.erase(this);
1416 setHasMetadataHashEntry(false);
1419 void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1420 eraseMetadata(KindID);
1422 addMetadata(KindID, *N);
1425 void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
1426 setMetadata(getContext().getMDKindID(Kind), N);
1429 MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1430 SmallVector<MDNode *, 1> MDs;
1431 getMetadata(KindID, MDs);
1432 assert(MDs.size() <= 1 && "Expected at most one metadata attachment");
1438 MDNode *GlobalObject::getMetadata(StringRef Kind) const {
1439 return getMetadata(getContext().getMDKindID(Kind));
1442 void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
1443 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1444 Other->getAllMetadata(MDs);
1445 for (auto &MD : MDs) {
1446 // We need to adjust the type metadata offset.
1447 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1448 auto *OffsetConst = cast<ConstantInt>(
1449 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1450 Metadata *TypeId = MD.second->getOperand(1);
1451 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1452 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1453 addMetadata(LLVMContext::MD_type,
1454 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1457 // If an offset adjustment was specified we need to modify the DIExpression
1458 // to prepend the adjustment:
1459 // !DIExpression(DW_OP_plus, Offset, [original expr])
1460 auto *Attachment = MD.second;
1461 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1462 DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1463 DIExpression *E = nullptr;
1465 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1466 GV = GVE->getVariable();
1467 E = GVE->getExpression();
1469 ArrayRef<uint64_t> OrigElements;
1471 OrigElements = E->getElements();
1472 std::vector<uint64_t> Elements(OrigElements.size() + 2);
1473 Elements[0] = dwarf::DW_OP_plus;
1474 Elements[1] = Offset;
1475 std::copy(OrigElements.begin(), OrigElements.end(), Elements.begin() + 2);
1476 E = DIExpression::get(getContext(), Elements);
1477 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1479 addMetadata(MD.first, *Attachment);
1483 void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1485 LLVMContext::MD_type,
1486 *MDTuple::get(getContext(),
1487 {ConstantAsMetadata::get(llvm::ConstantInt::get(
1488 Type::getInt64Ty(getContext()), Offset)),
1492 void Function::setSubprogram(DISubprogram *SP) {
1493 setMetadata(LLVMContext::MD_dbg, SP);
1496 DISubprogram *Function::getSubprogram() const {
1497 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1500 bool Function::isDebugInfoForProfiling() const {
1501 if (DISubprogram *SP = getSubprogram()) {
1502 if (DICompileUnit *CU = SP->getUnit()) {
1503 return CU->getDebugInfoForProfiling();
1509 void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
1510 addMetadata(LLVMContext::MD_dbg, *GV);
1513 void GlobalVariable::getDebugInfo(
1514 SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
1515 SmallVector<MDNode *, 1> MDs;
1516 getMetadata(LLVMContext::MD_dbg, MDs);
1517 for (MDNode *MD : MDs)
1518 GVs.push_back(cast<DIGlobalVariableExpression>(MD));