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 "MetadataImpl.h"
17 #include "SymbolTableListTraitsImpl.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/IR/Instruction.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ValueHandle.h"
32 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
33 : Value(Ty, MetadataAsValueVal), MD(MD) {
37 MetadataAsValue::~MetadataAsValue() {
38 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
42 /// \brief Canonicalize metadata arguments to intrinsics.
44 /// To support bitcode upgrades (and assembly semantic sugar) for \a
45 /// MetadataAsValue, we need to canonicalize certain metadata.
47 /// - nullptr is replaced by an empty MDNode.
48 /// - An MDNode with a single null operand is replaced by an empty MDNode.
49 /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
51 /// This maintains readability of bitcode from when metadata was a type of
52 /// value, and these bridges were unnecessary.
53 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
57 return MDNode::get(Context, None);
59 // Return early if this isn't a single-operand MDNode.
60 auto *N = dyn_cast<MDNode>(MD);
61 if (!N || N->getNumOperands() != 1)
64 if (!N->getOperand(0))
66 return MDNode::get(Context, None);
68 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
69 // Look through the MDNode.
75 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
76 MD = canonicalizeMetadataForValue(Context, MD);
77 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
79 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
83 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
85 MD = canonicalizeMetadataForValue(Context, MD);
86 auto &Store = Context.pImpl->MetadataAsValues;
87 auto I = Store.find(MD);
88 return I == Store.end() ? nullptr : I->second;
91 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
92 LLVMContext &Context = getContext();
93 MD = canonicalizeMetadataForValue(Context, MD);
94 auto &Store = Context.pImpl->MetadataAsValues;
96 // Stop tracking the old metadata.
97 Store.erase(this->MD);
101 // Start tracking MD, or RAUW if necessary.
102 auto *&Entry = Store[MD];
104 replaceAllUsesWith(Entry);
114 void MetadataAsValue::track() {
116 MetadataTracking::track(&MD, *MD, *this);
119 void MetadataAsValue::untrack() {
121 MetadataTracking::untrack(MD);
124 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
126 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
129 assert(WasInserted && "Expected to add a reference");
132 assert(NextIndex != 0 && "Unexpected overflow");
135 void ReplaceableMetadataImpl::dropRef(void *Ref) {
136 bool WasErased = UseMap.erase(Ref);
138 assert(WasErased && "Expected to drop a reference");
141 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
142 const Metadata &MD) {
143 auto I = UseMap.find(Ref);
144 assert(I != UseMap.end() && "Expected to move a reference");
145 auto OwnerAndIndex = I->second;
147 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
149 assert(WasInserted && "Expected to add a reference");
151 // Check that the references are direct if there's no owner.
153 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
154 "Reference without owner must be direct");
155 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
156 "Reference without owner must be direct");
159 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
160 assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
161 "Expected non-temp node");
166 // Copy out uses since UseMap will get touched below.
167 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
168 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
169 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
170 return L.second.second < R.second.second;
172 for (const auto &Pair : Uses) {
173 // Check that this Ref hasn't disappeared after RAUW (when updating a
175 if (!UseMap.count(Pair.first))
178 OwnerTy Owner = Pair.second.first;
180 // Update unowned tracking references directly.
181 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
184 MetadataTracking::track(Ref);
185 UseMap.erase(Pair.first);
189 // Check for MetadataAsValue.
190 if (Owner.is<MetadataAsValue *>()) {
191 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
195 // There's a Metadata owner -- dispatch.
196 Metadata *OwnerMD = Owner.get<Metadata *>();
197 switch (OwnerMD->getMetadataID()) {
198 #define HANDLE_METADATA_LEAF(CLASS) \
199 case Metadata::CLASS##Kind: \
200 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
202 #include "llvm/IR/Metadata.def"
204 llvm_unreachable("Invalid metadata subclass");
207 assert(UseMap.empty() && "Expected all uses to be replaced");
210 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
219 // Copy out uses since UseMap could get touched below.
220 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
221 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
222 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
223 return L.second.second < R.second.second;
226 for (const auto &Pair : Uses) {
227 auto Owner = Pair.second.first;
230 if (Owner.is<MetadataAsValue *>())
233 // Resolve MDNodes that point at this.
234 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
237 if (OwnerMD->isResolved())
239 OwnerMD->decrementUnresolvedOperandCount();
243 static Function *getLocalFunction(Value *V) {
244 assert(V && "Expected value");
245 if (auto *A = dyn_cast<Argument>(V))
246 return A->getParent();
247 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
248 return BB->getParent();
252 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
253 assert(V && "Unexpected null Value");
255 auto &Context = V->getContext();
256 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
258 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
259 "Expected constant or function-local value");
260 assert(!V->NameAndIsUsedByMD.getInt() &&
261 "Expected this to be the only metadata use");
262 V->NameAndIsUsedByMD.setInt(true);
263 if (auto *C = dyn_cast<Constant>(V))
264 Entry = new ConstantAsMetadata(C);
266 Entry = new LocalAsMetadata(V);
272 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
273 assert(V && "Unexpected null Value");
274 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
277 void ValueAsMetadata::handleDeletion(Value *V) {
278 assert(V && "Expected valid value");
280 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
281 auto I = Store.find(V);
282 if (I == Store.end())
285 // Remove old entry from the map.
286 ValueAsMetadata *MD = I->second;
287 assert(MD && "Expected valid metadata");
288 assert(MD->getValue() == V && "Expected valid mapping");
291 // Delete the metadata.
292 MD->replaceAllUsesWith(nullptr);
296 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
297 assert(From && "Expected valid value");
298 assert(To && "Expected valid value");
299 assert(From != To && "Expected changed value");
300 assert(From->getType() == To->getType() && "Unexpected type change");
302 LLVMContext &Context = From->getType()->getContext();
303 auto &Store = Context.pImpl->ValuesAsMetadata;
304 auto I = Store.find(From);
305 if (I == Store.end()) {
306 assert(!From->NameAndIsUsedByMD.getInt() &&
307 "Expected From not to be used by metadata");
311 // Remove old entry from the map.
312 assert(From->NameAndIsUsedByMD.getInt() &&
313 "Expected From to be used by metadata");
314 From->NameAndIsUsedByMD.setInt(false);
315 ValueAsMetadata *MD = I->second;
316 assert(MD && "Expected valid metadata");
317 assert(MD->getValue() == From && "Expected valid mapping");
320 if (isa<LocalAsMetadata>(MD)) {
321 if (auto *C = dyn_cast<Constant>(To)) {
322 // Local became a constant.
323 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
327 if (getLocalFunction(From) && getLocalFunction(To) &&
328 getLocalFunction(From) != getLocalFunction(To)) {
330 MD->replaceAllUsesWith(nullptr);
334 } else if (!isa<Constant>(To)) {
335 // Changed to function-local value.
336 MD->replaceAllUsesWith(nullptr);
341 auto *&Entry = Store[To];
343 // The target already exists.
344 MD->replaceAllUsesWith(Entry);
349 // Update MD in place (and update the map entry).
350 assert(!To->NameAndIsUsedByMD.getInt() &&
351 "Expected this to be the only metadata use");
352 To->NameAndIsUsedByMD.setInt(true);
357 //===----------------------------------------------------------------------===//
358 // MDString implementation.
361 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
362 auto &Store = Context.pImpl->MDStringCache;
363 auto I = Store.find(Str);
364 if (I != Store.end())
368 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
369 bool WasInserted = Store.insert(Entry);
371 assert(WasInserted && "Expected entry to be inserted");
372 Entry->second.Entry = Entry;
373 return &Entry->second;
376 StringRef MDString::getString() const {
377 assert(Entry && "Expected to find string map entry");
378 return Entry->first();
381 //===----------------------------------------------------------------------===//
382 // MDNode implementation.
385 void *MDNode::operator new(size_t Size, unsigned NumOps) {
386 void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
387 MDOperand *O = static_cast<MDOperand *>(Ptr);
388 for (MDOperand *E = O + NumOps; O != E; ++O)
389 (void)new (O) MDOperand;
393 void MDNode::operator delete(void *Mem) {
394 MDNode *N = static_cast<MDNode *>(Mem);
395 MDOperand *O = static_cast<MDOperand *>(Mem);
396 for (MDOperand *E = O - N->NumOperands; O != E; --O)
397 (O - 1)->~MDOperand();
398 ::operator delete(O);
401 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
402 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
403 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
404 NumUnresolved(0), Context(Context) {
406 for (Metadata *MD : Ops1)
407 setOperand(Op++, MD);
408 for (Metadata *MD : Ops2)
409 setOperand(Op++, MD);
415 // Check whether any operands are unresolved, requiring re-uniquing. If
416 // not, don't support RAUW.
417 if (!countUnresolvedOperands())
420 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
423 TempMDNode MDNode::clone() const {
424 switch (getMetadataID()) {
426 llvm_unreachable("Invalid MDNode subclass");
427 #define HANDLE_MDNODE_LEAF(CLASS) \
429 return cast<CLASS>(this)->cloneImpl();
430 #include "llvm/IR/Metadata.def"
434 static bool isOperandUnresolved(Metadata *Op) {
435 if (auto *N = dyn_cast_or_null<MDNode>(Op))
436 return !N->isResolved();
440 unsigned MDNode::countUnresolvedOperands() {
441 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
442 for (const auto &Op : operands())
443 NumUnresolved += unsigned(isOperandUnresolved(Op));
444 return NumUnresolved;
447 void MDNode::makeUniqued() {
448 assert(isTemporary() && "Expected this to be temporary");
449 assert(!isResolved() && "Expected this to be unresolved");
451 // Make this 'uniqued'.
453 if (!countUnresolvedOperands())
456 assert(isUniqued() && "Expected this to be uniqued");
459 void MDNode::makeDistinct() {
460 assert(isTemporary() && "Expected this to be temporary");
461 assert(!isResolved() && "Expected this to be unresolved");
463 // Pretend to be uniqued, resolve the node, and then store in distinct table.
466 storeDistinctInContext();
468 assert(isDistinct() && "Expected this to be distinct");
469 assert(isResolved() && "Expected this to be resolved");
472 void MDNode::resolve() {
473 assert(isUniqued() && "Expected this to be uniqued");
474 assert(!isResolved() && "Expected this to be unresolved");
476 // Move the map, so that this immediately looks resolved.
477 auto Uses = Context.takeReplaceableUses();
479 assert(isResolved() && "Expected this to be resolved");
481 // Drop RAUW support.
482 Uses->resolveAllUses();
485 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
486 assert(NumUnresolved != 0 && "Expected unresolved operands");
488 // Check if an operand was resolved.
489 if (!isOperandUnresolved(Old)) {
490 if (isOperandUnresolved(New))
491 // An operand was un-resolved!
493 } else if (!isOperandUnresolved(New))
494 decrementUnresolvedOperandCount();
497 void MDNode::decrementUnresolvedOperandCount() {
498 if (!--NumUnresolved)
499 // Last unresolved operand has just been resolved.
503 void MDNode::resolveCycles() {
507 // Resolve this node immediately.
510 // Resolve all operands.
511 for (const auto &Op : operands()) {
512 auto *N = dyn_cast_or_null<MDNode>(Op);
516 assert(!N->isTemporary() &&
517 "Expected all forward declarations to be resolved");
518 if (!N->isResolved())
523 MDNode *MDNode::replaceWithUniquedImpl() {
524 // Try to uniquify in place.
525 MDNode *UniquedNode = uniquify();
526 if (UniquedNode == this) {
531 // Collision, so RAUW instead.
532 replaceAllUsesWith(UniquedNode);
537 MDNode *MDNode::replaceWithDistinctImpl() {
542 void MDTuple::recalculateHash() {
543 setHash(MDTupleInfo::KeyTy::calculateHash(this));
546 void MDNode::dropAllReferences() {
547 for (unsigned I = 0, E = NumOperands; I != E; ++I)
548 setOperand(I, nullptr);
550 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
551 (void)Context.takeReplaceableUses();
555 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
556 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
557 assert(Op < getNumOperands() && "Expected valid operand");
560 // This node is not uniqued. Just set the operand and be done with it.
565 // This node is uniqued.
568 Metadata *Old = getOperand(Op);
571 // Drop uniquing for self-reference cycles.
575 storeDistinctInContext();
579 // Re-unique the node.
580 auto *Uniqued = uniquify();
581 if (Uniqued == this) {
583 resolveAfterOperandChange(Old, New);
589 // Still unresolved, so RAUW.
591 // First, clear out all operands to prevent any recursion (similar to
592 // dropAllReferences(), but we still need the use-list).
593 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
594 setOperand(O, nullptr);
595 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
600 // Store in non-uniqued form if RAUW isn't possible.
601 storeDistinctInContext();
604 void MDNode::deleteAsSubclass() {
605 switch (getMetadataID()) {
607 llvm_unreachable("Invalid subclass of MDNode");
608 #define HANDLE_MDNODE_LEAF(CLASS) \
610 delete cast<CLASS>(this); \
612 #include "llvm/IR/Metadata.def"
616 template <class T, class InfoT>
617 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
618 if (T *U = getUniqued(Store, N))
625 template <class NodeTy> struct MDNode::HasCachedHash {
628 template <class U, U Val> struct SFINAE {};
631 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
632 template <class U> static No &check(...);
634 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
637 MDNode *MDNode::uniquify() {
638 // Try to insert into uniquing store.
639 switch (getMetadataID()) {
641 llvm_unreachable("Invalid subclass of MDNode");
642 #define HANDLE_MDNODE_LEAF(CLASS) \
643 case CLASS##Kind: { \
644 CLASS *SubclassThis = cast<CLASS>(this); \
645 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
646 ShouldRecalculateHash; \
647 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
648 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
650 #include "llvm/IR/Metadata.def"
654 void MDNode::eraseFromStore() {
655 switch (getMetadataID()) {
657 llvm_unreachable("Invalid subclass of MDNode");
658 #define HANDLE_MDNODE_LEAF(CLASS) \
660 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
662 #include "llvm/IR/Metadata.def"
666 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
667 StorageType Storage, bool ShouldCreate) {
669 if (Storage == Uniqued) {
670 MDTupleInfo::KeyTy Key(MDs);
671 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
675 Hash = Key.getHash();
677 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
680 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
681 Storage, Context.pImpl->MDTuples);
684 void MDNode::deleteTemporary(MDNode *N) {
685 assert(N->isTemporary() && "Expected temporary node");
686 N->replaceAllUsesWith(nullptr);
687 N->deleteAsSubclass();
690 void MDNode::storeDistinctInContext() {
691 assert(isResolved() && "Expected resolved nodes");
695 switch (getMetadataID()) {
697 llvm_unreachable("Invalid subclass of MDNode");
698 #define HANDLE_MDNODE_LEAF(CLASS) \
699 case CLASS##Kind: { \
700 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
701 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
704 #include "llvm/IR/Metadata.def"
707 getContext().pImpl->DistinctMDNodes.insert(this);
710 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
711 if (getOperand(I) == New)
719 handleChangedOperand(mutable_begin() + I, New);
722 void MDNode::setOperand(unsigned I, Metadata *New) {
723 assert(I < NumOperands);
724 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
727 /// \brief Get a node, or a self-reference that looks like it.
729 /// Special handling for finding self-references, for use by \a
730 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
731 /// when self-referencing nodes were still uniqued. If the first operand has
732 /// the same operands as \c Ops, return the first operand instead.
733 static MDNode *getOrSelfReference(LLVMContext &Context,
734 ArrayRef<Metadata *> Ops) {
736 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
737 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
738 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
739 if (Ops[I] != N->getOperand(I))
740 return MDNode::get(Context, Ops);
744 return MDNode::get(Context, Ops);
747 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
753 SmallVector<Metadata *, 4> MDs(A->getNumOperands() + B->getNumOperands());
756 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
757 MDs[j++] = A->getOperand(i);
758 for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
759 MDs[j++] = B->getOperand(i);
761 // FIXME: This preserves long-standing behaviour, but is it really the right
762 // behaviour? Or was that an unintended side-effect of node uniquing?
763 return getOrSelfReference(A->getContext(), MDs);
766 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
770 SmallVector<Metadata *, 4> MDs;
771 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
772 Metadata *MD = A->getOperand(i);
773 for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
774 if (MD == B->getOperand(j)) {
780 // FIXME: This preserves long-standing behaviour, but is it really the right
781 // behaviour? Or was that an unintended side-effect of node uniquing?
782 return getOrSelfReference(A->getContext(), MDs);
785 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
789 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
790 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
791 if (AVal.compare(BVal) == APFloat::cmpLessThan)
796 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
797 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
800 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
801 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
804 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
805 ConstantInt *Low, ConstantInt *High) {
806 ConstantRange NewRange(Low->getValue(), High->getValue());
807 unsigned Size = EndPoints.size();
808 APInt LB = EndPoints[Size - 2]->getValue();
809 APInt LE = EndPoints[Size - 1]->getValue();
810 ConstantRange LastRange(LB, LE);
811 if (canBeMerged(NewRange, LastRange)) {
812 ConstantRange Union = LastRange.unionWith(NewRange);
813 Type *Ty = High->getType();
814 EndPoints[Size - 2] =
815 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
816 EndPoints[Size - 1] =
817 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
823 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
824 ConstantInt *Low, ConstantInt *High) {
825 if (!EndPoints.empty())
826 if (tryMergeRange(EndPoints, Low, High))
829 EndPoints.push_back(Low);
830 EndPoints.push_back(High);
833 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
834 // Given two ranges, we want to compute the union of the ranges. This
835 // is slightly complitade by having to combine the intervals and merge
836 // the ones that overlap.
844 // First, walk both lists in older of the lower boundary of each interval.
845 // At each step, try to merge the new interval to the last one we adedd.
846 SmallVector<ConstantInt *, 4> EndPoints;
849 int AN = A->getNumOperands() / 2;
850 int BN = B->getNumOperands() / 2;
851 while (AI < AN && BI < BN) {
852 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
853 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
855 if (ALow->getValue().slt(BLow->getValue())) {
856 addRange(EndPoints, ALow,
857 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
860 addRange(EndPoints, BLow,
861 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
866 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
867 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
871 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
872 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
876 // If we have more than 2 ranges (4 endpoints) we have to try to merge
877 // the last and first ones.
878 unsigned Size = EndPoints.size();
880 ConstantInt *FB = EndPoints[0];
881 ConstantInt *FE = EndPoints[1];
882 if (tryMergeRange(EndPoints, FB, FE)) {
883 for (unsigned i = 0; i < Size - 2; ++i) {
884 EndPoints[i] = EndPoints[i + 2];
886 EndPoints.resize(Size - 2);
890 // If in the end we have a single range, it is possible that it is now the
891 // full range. Just drop the metadata in that case.
892 if (EndPoints.size() == 2) {
893 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
894 if (Range.isFullSet())
898 SmallVector<Metadata *, 4> MDs;
899 MDs.reserve(EndPoints.size());
900 for (auto *I : EndPoints)
901 MDs.push_back(ConstantAsMetadata::get(I));
902 return MDNode::get(A->getContext(), MDs);
905 //===----------------------------------------------------------------------===//
906 // NamedMDNode implementation.
909 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
910 return *(SmallVector<TrackingMDRef, 4> *)Operands;
913 NamedMDNode::NamedMDNode(const Twine &N)
914 : Name(N.str()), Parent(nullptr),
915 Operands(new SmallVector<TrackingMDRef, 4>()) {}
917 NamedMDNode::~NamedMDNode() {
919 delete &getNMDOps(Operands);
922 unsigned NamedMDNode::getNumOperands() const {
923 return (unsigned)getNMDOps(Operands).size();
926 MDNode *NamedMDNode::getOperand(unsigned i) const {
927 assert(i < getNumOperands() && "Invalid Operand number!");
928 auto *N = getNMDOps(Operands)[i].get();
929 return cast_or_null<MDNode>(N);
932 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
934 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
935 assert(I < getNumOperands() && "Invalid operand number");
936 getNMDOps(Operands)[I].reset(New);
939 void NamedMDNode::eraseFromParent() {
940 getParent()->eraseNamedMetadata(this);
943 void NamedMDNode::dropAllReferences() {
944 getNMDOps(Operands).clear();
947 StringRef NamedMDNode::getName() const {
948 return StringRef(Name);
951 //===----------------------------------------------------------------------===//
952 // Instruction Metadata method implementations.
955 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
956 if (!Node && !hasMetadata())
958 setMetadata(getContext().getMDKindID(Kind), Node);
961 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
962 return getMetadataImpl(getContext().getMDKindID(Kind));
965 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
966 SmallSet<unsigned, 5> KnownSet;
967 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
969 // Drop debug if needed
970 if (KnownSet.erase(LLVMContext::MD_dbg))
973 if (!hasMetadataHashEntry())
974 return; // Nothing to remove!
976 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
977 getContext().pImpl->MetadataStore;
979 if (KnownSet.empty()) {
980 // Just drop our entry at the store.
981 MetadataStore.erase(this);
982 setHasMetadataHashEntry(false);
986 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
989 // Walk the array and drop any metadata we don't know.
990 for (I = 0, E = Info.size(); I != E;) {
991 if (KnownSet.count(Info[I].first)) {
996 Info[I] = std::move(Info.back());
1000 assert(E == Info.size());
1003 // Drop our entry at the store.
1004 MetadataStore.erase(this);
1005 setHasMetadataHashEntry(false);
1009 /// setMetadata - Set the metadata of of the specified kind to the specified
1010 /// node. This updates/replaces metadata if already present, or removes it if
1012 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1013 if (!Node && !hasMetadata())
1016 // Handle 'dbg' as a special case since it is not stored in the hash table.
1017 if (KindID == LLVMContext::MD_dbg) {
1018 DbgLoc = DebugLoc::getFromDILocation(Node);
1022 // Handle the case when we're adding/updating metadata on an instruction.
1024 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1025 assert(!Info.empty() == hasMetadataHashEntry() &&
1026 "HasMetadata bit is wonked");
1028 setHasMetadataHashEntry(true);
1030 // Handle replacement of an existing value.
1031 for (auto &P : Info)
1032 if (P.first == KindID) {
1033 P.second.reset(Node);
1038 // No replacement, just add it to the list.
1039 Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
1040 std::make_tuple(Node));
1044 // Otherwise, we're removing metadata from an instruction.
1045 assert((hasMetadataHashEntry() ==
1046 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
1047 "HasMetadata bit out of date!");
1048 if (!hasMetadataHashEntry())
1049 return; // Nothing to remove!
1050 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1052 // Common case is removing the only entry.
1053 if (Info.size() == 1 && Info[0].first == KindID) {
1054 getContext().pImpl->MetadataStore.erase(this);
1055 setHasMetadataHashEntry(false);
1059 // Handle removal of an existing value.
1060 for (unsigned i = 0, e = Info.size(); i != e; ++i)
1061 if (Info[i].first == KindID) {
1062 Info[i] = std::move(Info.back());
1064 assert(!Info.empty() && "Removing last entry should be handled above");
1067 // Otherwise, removing an entry that doesn't exist on the instruction.
1070 void Instruction::setAAMetadata(const AAMDNodes &N) {
1071 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1072 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1073 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1076 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1077 // Handle 'dbg' as a special case since it is not stored in the hash table.
1078 if (KindID == LLVMContext::MD_dbg)
1079 return DbgLoc.getAsMDNode();
1081 if (!hasMetadataHashEntry()) return nullptr;
1083 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1084 assert(!Info.empty() && "bit out of sync with hash table");
1086 for (const auto &I : Info)
1087 if (I.first == KindID)
1092 void Instruction::getAllMetadataImpl(
1093 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1096 // Handle 'dbg' as a special case since it is not stored in the hash table.
1097 if (!DbgLoc.isUnknown()) {
1099 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1100 if (!hasMetadataHashEntry()) return;
1103 assert(hasMetadataHashEntry() &&
1104 getContext().pImpl->MetadataStore.count(this) &&
1105 "Shouldn't have called this");
1106 const LLVMContextImpl::MDMapTy &Info =
1107 getContext().pImpl->MetadataStore.find(this)->second;
1108 assert(!Info.empty() && "Shouldn't have called this");
1110 Result.reserve(Result.size() + Info.size());
1111 for (auto &I : Info)
1112 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1114 // Sort the resulting array so it is stable.
1115 if (Result.size() > 1)
1116 array_pod_sort(Result.begin(), Result.end());
1119 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1120 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1122 assert(hasMetadataHashEntry() &&
1123 getContext().pImpl->MetadataStore.count(this) &&
1124 "Shouldn't have called this");
1125 const LLVMContextImpl::MDMapTy &Info =
1126 getContext().pImpl->MetadataStore.find(this)->second;
1127 assert(!Info.empty() && "Shouldn't have called this");
1128 Result.reserve(Result.size() + Info.size());
1129 for (auto &I : Info)
1130 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1132 // Sort the resulting array so it is stable.
1133 if (Result.size() > 1)
1134 array_pod_sort(Result.begin(), Result.end());
1137 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1138 /// this instruction.
1139 void Instruction::clearMetadataHashEntries() {
1140 assert(hasMetadataHashEntry() && "Caller should check");
1141 getContext().pImpl->MetadataStore.erase(this);
1142 setHasMetadataHashEntry(false);