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 "llvm/IR/Metadata.h"
15 #include "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/LeakDetector.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueHandle.h"
31 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
32 : Value(Ty, MetadataAsValueVal), MD(MD) {
36 MetadataAsValue::~MetadataAsValue() {
37 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
41 /// \brief Canonicalize metadata arguments to intrinsics.
43 /// To support bitcode upgrades (and assembly semantic sugar) for \a
44 /// MetadataAsValue, we need to canonicalize certain metadata.
46 /// - nullptr is replaced by an empty MDNode.
47 /// - An MDNode with a single null operand is replaced by an empty MDNode.
48 /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
50 /// This maintains readability of bitcode from when metadata was a type of
51 /// value, and these bridges were unnecessary.
52 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
56 return MDNode::get(Context, None);
58 // Return early if this isn't a single-operand MDNode.
59 auto *N = dyn_cast<MDNode>(MD);
60 if (!N || N->getNumOperands() != 1)
63 if (!N->getOperand(0))
65 return MDNode::get(Context, None);
67 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
68 // Look through the MDNode.
74 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
75 MD = canonicalizeMetadataForValue(Context, MD);
76 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
78 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
82 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
84 MD = canonicalizeMetadataForValue(Context, MD);
85 auto &Store = Context.pImpl->MetadataAsValues;
86 auto I = Store.find(MD);
87 return I == Store.end() ? nullptr : I->second;
90 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
91 LLVMContext &Context = getContext();
92 MD = canonicalizeMetadataForValue(Context, MD);
93 auto &Store = Context.pImpl->MetadataAsValues;
95 // Stop tracking the old metadata.
96 Store.erase(this->MD);
100 // Start tracking MD, or RAUW if necessary.
101 auto *&Entry = Store[MD];
103 replaceAllUsesWith(Entry);
113 void MetadataAsValue::track() {
115 MetadataTracking::track(&MD, *MD, *this);
118 void MetadataAsValue::untrack() {
120 MetadataTracking::untrack(MD);
123 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
124 bool WasInserted = UseMap.insert(std::make_pair(Ref, Owner)).second;
126 assert(WasInserted && "Expected to add a reference");
129 void ReplaceableMetadataImpl::dropRef(void *Ref) {
130 bool WasErased = UseMap.erase(Ref);
132 assert(WasErased && "Expected to drop a reference");
135 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
136 const Metadata &MD) {
137 auto I = UseMap.find(Ref);
138 assert(I != UseMap.end() && "Expected to move a reference");
139 OwnerTy Owner = I->second;
143 // Check that the references are direct if there's no owner.
145 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
146 "Reference without owner must be direct");
147 assert((Owner || *static_cast<Metadata **>(New) == &MD) &&
148 "Reference without owner must be direct");
151 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
152 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Expected non-temp node");
157 // Copy out uses since UseMap will get touched below.
158 SmallVector<std::pair<void *, OwnerTy>, 8> Uses(UseMap.begin(), UseMap.end());
159 for (const auto &Pair : Uses) {
161 // Update unowned tracking references directly.
162 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
164 MetadataTracking::track(Ref);
165 UseMap.erase(Pair.first);
169 // Check for MetadataAsValue.
170 if (Pair.second.is<MetadataAsValue *>()) {
171 Pair.second.get<MetadataAsValue *>()->handleChangedMetadata(MD);
175 // There's a Metadata owner -- dispatch.
176 Metadata *Owner = Pair.second.get<Metadata *>();
177 switch (Owner->getMetadataID()) {
178 #define HANDLE_METADATA_LEAF(CLASS) \
179 case Metadata::CLASS##Kind: \
180 cast<CLASS>(Owner)->handleChangedOperand(Pair.first, MD); \
182 #include "llvm/IR/Metadata.def"
184 llvm_unreachable("Invalid metadata subclass");
187 assert(UseMap.empty() && "Expected all uses to be replaced");
190 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
199 // Copy out uses since UseMap could get touched below.
200 SmallVector<std::pair<void *, OwnerTy>, 8> Uses(UseMap.begin(), UseMap.end());
202 for (const auto &Pair : Uses) {
205 if (Pair.second.is<MetadataAsValue *>())
208 // Resolve GenericMDNodes that point at this.
209 auto *Owner = dyn_cast<GenericMDNode>(Pair.second.get<Metadata *>());
212 if (Owner->isResolved())
214 Owner->decrementUnresolvedOperands();
215 if (!Owner->hasUnresolvedOperands())
220 static Function *getLocalFunction(Value *V) {
221 assert(V && "Expected value");
222 if (auto *A = dyn_cast<Argument>(V))
223 return A->getParent();
224 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
225 return BB->getParent();
229 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
230 assert(V && "Unexpected null Value");
232 auto &Context = V->getContext();
233 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
235 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
236 "Expected constant or function-local value");
237 assert(!V->NameAndIsUsedByMD.getInt() &&
238 "Expected this to be the only metadata use");
239 V->NameAndIsUsedByMD.setInt(true);
240 if (auto *C = dyn_cast<Constant>(V))
241 Entry = new ConstantAsMetadata(Context, C);
243 Entry = new LocalAsMetadata(Context, V);
249 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
250 assert(V && "Unexpected null Value");
251 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
254 void ValueAsMetadata::handleDeletion(Value *V) {
255 assert(V && "Expected valid value");
257 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
258 auto I = Store.find(V);
259 if (I == Store.end())
262 // Remove old entry from the map.
263 ValueAsMetadata *MD = I->second;
264 assert(MD && "Expected valid metadata");
265 assert(MD->getValue() == V && "Expected valid mapping");
268 // Delete the metadata.
269 MD->replaceAllUsesWith(nullptr);
273 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
274 assert(From && "Expected valid value");
275 assert(To && "Expected valid value");
276 assert(From != To && "Expected changed value");
277 assert(From->getType() == To->getType() && "Unexpected type change");
279 LLVMContext &Context = From->getType()->getContext();
280 auto &Store = Context.pImpl->ValuesAsMetadata;
281 auto I = Store.find(From);
282 if (I == Store.end()) {
283 assert(!From->NameAndIsUsedByMD.getInt() &&
284 "Expected From not to be used by metadata");
288 // Remove old entry from the map.
289 assert(From->NameAndIsUsedByMD.getInt() &&
290 "Expected From to be used by metadata");
291 From->NameAndIsUsedByMD.setInt(false);
292 ValueAsMetadata *MD = I->second;
293 assert(MD && "Expected valid metadata");
294 assert(MD->getValue() == From && "Expected valid mapping");
297 if (isa<LocalAsMetadata>(MD)) {
298 if (auto *C = dyn_cast<Constant>(To)) {
299 // Local became a constant.
300 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
304 if (getLocalFunction(From) && getLocalFunction(To) &&
305 getLocalFunction(From) != getLocalFunction(To)) {
307 MD->replaceAllUsesWith(nullptr);
311 } else if (!isa<Constant>(To)) {
312 // Changed to function-local value.
313 MD->replaceAllUsesWith(nullptr);
318 auto *&Entry = Store[To];
320 // The target already exists.
321 MD->replaceAllUsesWith(Entry);
326 // Update MD in place (and update the map entry).
327 assert(!To->NameAndIsUsedByMD.getInt() &&
328 "Expected this to be the only metadata use");
329 To->NameAndIsUsedByMD.setInt(true);
334 //===----------------------------------------------------------------------===//
335 // MDString implementation.
338 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
339 auto &Store = Context.pImpl->MDStringCache;
340 auto I = Store.find(Str);
341 if (I != Store.end())
345 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
346 bool WasInserted = Store.insert(Entry);
348 assert(WasInserted && "Expected entry to be inserted");
349 Entry->second.Entry = Entry;
350 return &Entry->second;
353 StringRef MDString::getString() const {
354 assert(Entry && "Expected to find string map entry");
355 return Entry->first();
358 //===----------------------------------------------------------------------===//
359 // MDNode implementation.
362 void *MDNode::operator new(size_t Size, unsigned NumOps) {
363 void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
364 MDOperand *First = new (Ptr) MDOperand[NumOps];
365 return First + NumOps;
368 void MDNode::operator delete(void *Mem) {
369 MDNode *N = static_cast<MDNode *>(Mem);
370 MDOperand *Last = static_cast<MDOperand *>(Mem);
371 ::operator delete(Last - N->NumOperands);
374 MDNode::MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs)
375 : Metadata(ID), Context(Context), NumOperands(MDs.size()),
376 MDNodeSubclassData(0) {
377 for (unsigned I = 0, E = MDs.size(); I != E; ++I)
378 setOperand(I, MDs[I]);
381 bool MDNode::isResolved() const {
382 if (isa<MDNodeFwdDecl>(this))
384 return cast<GenericMDNode>(this)->isResolved();
387 static bool isOperandUnresolved(Metadata *Op) {
388 if (auto *N = dyn_cast_or_null<MDNode>(Op))
389 return !N->isResolved();
393 GenericMDNode::GenericMDNode(LLVMContext &C, ArrayRef<Metadata *> Vals)
394 : MDNode(C, GenericMDNodeKind, Vals) {
395 // Check whether any operands are unresolved, requiring re-uniquing.
396 for (const auto &Op : operands())
397 if (isOperandUnresolved(Op))
398 incrementUnresolvedOperands();
400 if (hasUnresolvedOperands())
401 ReplaceableUses.reset(new ReplaceableMetadataImpl);
404 GenericMDNode::~GenericMDNode() {
405 LLVMContextImpl *pImpl = getContext().pImpl;
406 if (isStoredDistinctInContext())
407 pImpl->NonUniquedMDNodes.erase(this);
409 pImpl->MDNodeSet.erase(this);
412 void GenericMDNode::resolve() {
413 assert(!isResolved() && "Expected this to be unresolved");
415 // Move the map, so that this immediately looks resolved.
416 auto Uses = std::move(ReplaceableUses);
418 assert(isResolved() && "Expected this to be resolved");
420 // Drop RAUW support.
421 Uses->resolveAllUses();
424 void GenericMDNode::resolveCycles() {
428 // Resolve this node immediately.
431 // Resolve all operands.
432 for (const auto &Op : operands()) {
435 assert(!isa<MDNodeFwdDecl>(Op) &&
436 "Expected all forward declarations to be resolved");
437 if (auto *N = dyn_cast<GenericMDNode>(Op))
438 if (!N->isResolved())
443 void MDNode::dropAllReferences() {
444 for (unsigned I = 0, E = NumOperands; I != E; ++I)
445 setOperand(I, nullptr);
446 if (auto *G = dyn_cast<GenericMDNode>(this))
447 if (!G->isResolved()) {
448 G->ReplaceableUses->resolveAllUses(/* ResolveUsers */ false);
449 G->ReplaceableUses.reset();
454 /// \brief Make MDOperand transparent for hashing.
456 /// This overload of an implementation detail of the hashing library makes
457 /// MDOperand hash to the same value as a \a Metadata pointer.
459 /// Note that overloading \a hash_value() as follows:
462 /// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
465 /// does not cause MDOperand to be transparent. In particular, a bare pointer
466 /// doesn't get hashed before it's combined, whereas \a MDOperand would.
467 static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
470 void GenericMDNode::handleChangedOperand(void *Ref, Metadata *New) {
471 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
472 assert(Op < getNumOperands() && "Expected valid operand");
474 if (isStoredDistinctInContext()) {
475 assert(isResolved() && "Expected distinct node to be resolved");
477 // This node is not uniqued. Just set the operand and be done with it.
482 auto &Store = getContext().pImpl->MDNodeSet;
485 Metadata *Old = getOperand(Op);
488 // Drop uniquing for self-reference cycles or if an operand drops to null.
490 // FIXME: Stop dropping uniquing when an operand drops to null. The original
491 // motivation was to prevent madness during teardown of LLVMContextImpl, but
492 // dropAllReferences() fixes that problem in a better way. (It's just here
493 // now for better staging of semantic changes.)
494 if (New == this || !New) {
495 storeDistinctInContext();
502 // Re-calculate the hash.
503 setHash(hash_combine_range(op_begin(), op_end()));
506 SmallVector<Metadata *, 8> MDs(op_begin(), op_end());
507 unsigned RawHash = hash_combine_range(MDs.begin(), MDs.end());
508 assert(getHash() == RawHash &&
509 "Expected hash of MDOperand to equal hash of Metadata*");
513 // Re-unique the node.
514 GenericMDNodeInfo::KeyTy Key(this);
515 auto I = Store.find_as(Key);
516 if (I == Store.end()) {
520 // Check if the last unresolved operand has just been resolved; if so,
521 // resolve this as well.
522 if (isOperandUnresolved(Old))
523 decrementUnresolvedOperands();
524 if (isOperandUnresolved(New))
525 incrementUnresolvedOperands();
526 if (!hasUnresolvedOperands())
535 // Still unresolved, so RAUW.
536 ReplaceableUses->replaceAllUsesWith(*I);
541 // Store in non-uniqued form if this node has already been resolved.
543 storeDistinctInContext();
546 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Metadata *> MDs,
548 auto &Store = Context.pImpl->MDNodeSet;
550 GenericMDNodeInfo::KeyTy Key(MDs);
551 auto I = Store.find_as(Key);
552 if (I != Store.end())
557 // Coallocate space for the node and Operands together, then placement new.
558 GenericMDNode *N = new (MDs.size()) GenericMDNode(Context, MDs);
559 N->setHash(Key.Hash);
564 MDNodeFwdDecl *MDNode::getTemporary(LLVMContext &Context,
565 ArrayRef<Metadata *> MDs) {
566 MDNodeFwdDecl *N = new (MDs.size()) MDNodeFwdDecl(Context, MDs);
567 LeakDetector::addGarbageObject(N);
571 void MDNode::deleteTemporary(MDNode *N) {
572 assert(isa<MDNodeFwdDecl>(N) && "Expected forward declaration");
573 LeakDetector::removeGarbageObject(N);
574 delete cast<MDNodeFwdDecl>(N);
577 void MDNode::storeDistinctInContext() {
578 assert(!IsDistinctInContext && "Expected newly distinct metadata");
579 IsDistinctInContext = true;
580 auto *G = cast<GenericMDNode>(this);
582 getContext().pImpl->NonUniquedMDNodes.insert(G);
585 // Replace value from this node's operand list.
586 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
587 if (getOperand(I) == New)
590 if (auto *N = dyn_cast<GenericMDNode>(this)) {
591 N->handleChangedOperand(mutable_begin() + I, New);
595 assert(isa<MDNodeFwdDecl>(this) && "Expected an MDNode");
599 void MDNode::setOperand(unsigned I, Metadata *New) {
600 assert(I < NumOperands);
601 if (isStoredDistinctInContext() || isa<MDNodeFwdDecl>(this))
602 // No need for a callback, this isn't uniqued.
603 mutable_begin()[I].reset(New, nullptr);
605 mutable_begin()[I].reset(New, this);
608 /// \brief Get a node, or a self-reference that looks like it.
610 /// Special handling for finding self-references, for use by \a
611 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
612 /// when self-referencing nodes were still uniqued. If the first operand has
613 /// the same operands as \c Ops, return the first operand instead.
614 static MDNode *getOrSelfReference(LLVMContext &Context,
615 ArrayRef<Metadata *> Ops) {
617 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
618 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
619 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
620 if (Ops[I] != N->getOperand(I))
621 return MDNode::get(Context, Ops);
625 return MDNode::get(Context, Ops);
628 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
634 SmallVector<Metadata *, 4> MDs(A->getNumOperands() + B->getNumOperands());
637 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
638 MDs[j++] = A->getOperand(i);
639 for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
640 MDs[j++] = B->getOperand(i);
642 // FIXME: This preserves long-standing behaviour, but is it really the right
643 // behaviour? Or was that an unintended side-effect of node uniquing?
644 return getOrSelfReference(A->getContext(), MDs);
647 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
651 SmallVector<Metadata *, 4> MDs;
652 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
653 Metadata *MD = A->getOperand(i);
654 for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
655 if (MD == B->getOperand(j)) {
661 // FIXME: This preserves long-standing behaviour, but is it really the right
662 // behaviour? Or was that an unintended side-effect of node uniquing?
663 return getOrSelfReference(A->getContext(), MDs);
666 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
670 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
671 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
672 if (AVal.compare(BVal) == APFloat::cmpLessThan)
677 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
678 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
681 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
682 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
685 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
686 ConstantInt *Low, ConstantInt *High) {
687 ConstantRange NewRange(Low->getValue(), High->getValue());
688 unsigned Size = EndPoints.size();
689 APInt LB = EndPoints[Size - 2]->getValue();
690 APInt LE = EndPoints[Size - 1]->getValue();
691 ConstantRange LastRange(LB, LE);
692 if (canBeMerged(NewRange, LastRange)) {
693 ConstantRange Union = LastRange.unionWith(NewRange);
694 Type *Ty = High->getType();
695 EndPoints[Size - 2] =
696 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
697 EndPoints[Size - 1] =
698 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
704 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
705 ConstantInt *Low, ConstantInt *High) {
706 if (!EndPoints.empty())
707 if (tryMergeRange(EndPoints, Low, High))
710 EndPoints.push_back(Low);
711 EndPoints.push_back(High);
714 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
715 // Given two ranges, we want to compute the union of the ranges. This
716 // is slightly complitade by having to combine the intervals and merge
717 // the ones that overlap.
725 // First, walk both lists in older of the lower boundary of each interval.
726 // At each step, try to merge the new interval to the last one we adedd.
727 SmallVector<ConstantInt *, 4> EndPoints;
730 int AN = A->getNumOperands() / 2;
731 int BN = B->getNumOperands() / 2;
732 while (AI < AN && BI < BN) {
733 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
734 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
736 if (ALow->getValue().slt(BLow->getValue())) {
737 addRange(EndPoints, ALow,
738 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
741 addRange(EndPoints, BLow,
742 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
747 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
748 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
752 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
753 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
757 // If we have more than 2 ranges (4 endpoints) we have to try to merge
758 // the last and first ones.
759 unsigned Size = EndPoints.size();
761 ConstantInt *FB = EndPoints[0];
762 ConstantInt *FE = EndPoints[1];
763 if (tryMergeRange(EndPoints, FB, FE)) {
764 for (unsigned i = 0; i < Size - 2; ++i) {
765 EndPoints[i] = EndPoints[i + 2];
767 EndPoints.resize(Size - 2);
771 // If in the end we have a single range, it is possible that it is now the
772 // full range. Just drop the metadata in that case.
773 if (EndPoints.size() == 2) {
774 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
775 if (Range.isFullSet())
779 SmallVector<Metadata *, 4> MDs;
780 MDs.reserve(EndPoints.size());
781 for (auto *I : EndPoints)
782 MDs.push_back(ConstantAsMetadata::get(I));
783 return MDNode::get(A->getContext(), MDs);
786 //===----------------------------------------------------------------------===//
787 // NamedMDNode implementation.
790 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
791 return *(SmallVector<TrackingMDRef, 4> *)Operands;
794 NamedMDNode::NamedMDNode(const Twine &N)
795 : Name(N.str()), Parent(nullptr),
796 Operands(new SmallVector<TrackingMDRef, 4>()) {}
798 NamedMDNode::~NamedMDNode() {
800 delete &getNMDOps(Operands);
803 unsigned NamedMDNode::getNumOperands() const {
804 return (unsigned)getNMDOps(Operands).size();
807 MDNode *NamedMDNode::getOperand(unsigned i) const {
808 assert(i < getNumOperands() && "Invalid Operand number!");
809 auto *N = getNMDOps(Operands)[i].get();
812 return cast_or_null<MDNode>(N);
815 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
817 void NamedMDNode::eraseFromParent() {
818 getParent()->eraseNamedMetadata(this);
821 void NamedMDNode::dropAllReferences() {
822 getNMDOps(Operands).clear();
825 StringRef NamedMDNode::getName() const {
826 return StringRef(Name);
829 //===----------------------------------------------------------------------===//
830 // Instruction Metadata method implementations.
833 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
834 if (!Node && !hasMetadata())
836 setMetadata(getContext().getMDKindID(Kind), Node);
839 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
840 return getMetadataImpl(getContext().getMDKindID(Kind));
843 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
844 SmallSet<unsigned, 5> KnownSet;
845 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
847 // Drop debug if needed
848 if (KnownSet.erase(LLVMContext::MD_dbg))
851 if (!hasMetadataHashEntry())
852 return; // Nothing to remove!
854 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
855 getContext().pImpl->MetadataStore;
857 if (KnownSet.empty()) {
858 // Just drop our entry at the store.
859 MetadataStore.erase(this);
860 setHasMetadataHashEntry(false);
864 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
867 // Walk the array and drop any metadata we don't know.
868 for (I = 0, E = Info.size(); I != E;) {
869 if (KnownSet.count(Info[I].first)) {
874 Info[I] = std::move(Info.back());
878 assert(E == Info.size());
881 // Drop our entry at the store.
882 MetadataStore.erase(this);
883 setHasMetadataHashEntry(false);
887 /// setMetadata - Set the metadata of of the specified kind to the specified
888 /// node. This updates/replaces metadata if already present, or removes it if
890 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
891 if (!Node && !hasMetadata())
894 // Handle 'dbg' as a special case since it is not stored in the hash table.
895 if (KindID == LLVMContext::MD_dbg) {
896 DbgLoc = DebugLoc::getFromDILocation(Node);
900 // Handle the case when we're adding/updating metadata on an instruction.
902 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
903 assert(!Info.empty() == hasMetadataHashEntry() &&
904 "HasMetadata bit is wonked");
906 setHasMetadataHashEntry(true);
908 // Handle replacement of an existing value.
910 if (P.first == KindID) {
911 P.second.reset(Node);
916 // No replacement, just add it to the list.
917 Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
918 std::make_tuple(Node));
922 // Otherwise, we're removing metadata from an instruction.
923 assert((hasMetadataHashEntry() ==
924 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
925 "HasMetadata bit out of date!");
926 if (!hasMetadataHashEntry())
927 return; // Nothing to remove!
928 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
930 // Common case is removing the only entry.
931 if (Info.size() == 1 && Info[0].first == KindID) {
932 getContext().pImpl->MetadataStore.erase(this);
933 setHasMetadataHashEntry(false);
937 // Handle removal of an existing value.
938 for (unsigned i = 0, e = Info.size(); i != e; ++i)
939 if (Info[i].first == KindID) {
940 Info[i] = std::move(Info.back());
942 assert(!Info.empty() && "Removing last entry should be handled above");
945 // Otherwise, removing an entry that doesn't exist on the instruction.
948 void Instruction::setAAMetadata(const AAMDNodes &N) {
949 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
950 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
951 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
954 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
955 // Handle 'dbg' as a special case since it is not stored in the hash table.
956 if (KindID == LLVMContext::MD_dbg)
957 return DbgLoc.getAsMDNode();
959 if (!hasMetadataHashEntry()) return nullptr;
961 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
962 assert(!Info.empty() && "bit out of sync with hash table");
964 for (const auto &I : Info)
965 if (I.first == KindID)
970 void Instruction::getAllMetadataImpl(
971 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
974 // Handle 'dbg' as a special case since it is not stored in the hash table.
975 if (!DbgLoc.isUnknown()) {
977 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
978 if (!hasMetadataHashEntry()) return;
981 assert(hasMetadataHashEntry() &&
982 getContext().pImpl->MetadataStore.count(this) &&
983 "Shouldn't have called this");
984 const LLVMContextImpl::MDMapTy &Info =
985 getContext().pImpl->MetadataStore.find(this)->second;
986 assert(!Info.empty() && "Shouldn't have called this");
988 Result.reserve(Result.size() + Info.size());
990 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
992 // Sort the resulting array so it is stable.
993 if (Result.size() > 1)
994 array_pod_sort(Result.begin(), Result.end());
997 void Instruction::getAllMetadataOtherThanDebugLocImpl(
998 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1000 assert(hasMetadataHashEntry() &&
1001 getContext().pImpl->MetadataStore.count(this) &&
1002 "Shouldn't have called this");
1003 const LLVMContextImpl::MDMapTy &Info =
1004 getContext().pImpl->MetadataStore.find(this)->second;
1005 assert(!Info.empty() && "Shouldn't have called this");
1006 Result.reserve(Result.size() + Info.size());
1007 for (auto &I : Info)
1008 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1010 // Sort the resulting array so it is stable.
1011 if (Result.size() > 1)
1012 array_pod_sort(Result.begin(), Result.end());
1015 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1016 /// this instruction.
1017 void Instruction::clearMetadataHashEntries() {
1018 assert(hasMetadataHashEntry() && "Caller should check");
1019 getContext().pImpl->MetadataStore.erase(this);
1020 setHasMetadataHashEntry(false);