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 return Store.lookup(MD);
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) {
125 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
128 assert(WasInserted && "Expected to add a reference");
131 assert(NextIndex != 0 && "Unexpected overflow");
134 void ReplaceableMetadataImpl::dropRef(void *Ref) {
135 bool WasErased = UseMap.erase(Ref);
137 assert(WasErased && "Expected to drop a reference");
140 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
141 const Metadata &MD) {
142 auto I = UseMap.find(Ref);
143 assert(I != UseMap.end() && "Expected to move a reference");
144 auto OwnerAndIndex = I->second;
146 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
148 assert(WasInserted && "Expected to add a reference");
150 // Check that the references are direct if there's no owner.
152 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
153 "Reference without owner must be direct");
154 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
155 "Reference without owner must be direct");
158 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
159 assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
160 "Expected non-temp node");
165 // Copy out uses since UseMap will get touched below.
166 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
167 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
168 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
169 return L.second.second < R.second.second;
171 for (const auto &Pair : Uses) {
172 // Check that this Ref hasn't disappeared after RAUW (when updating a
174 if (!UseMap.count(Pair.first))
177 OwnerTy Owner = Pair.second.first;
179 // Update unowned tracking references directly.
180 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
183 MetadataTracking::track(Ref);
184 UseMap.erase(Pair.first);
188 // Check for MetadataAsValue.
189 if (Owner.is<MetadataAsValue *>()) {
190 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
194 // There's a Metadata owner -- dispatch.
195 Metadata *OwnerMD = Owner.get<Metadata *>();
196 switch (OwnerMD->getMetadataID()) {
197 #define HANDLE_METADATA_LEAF(CLASS) \
198 case Metadata::CLASS##Kind: \
199 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
201 #include "llvm/IR/Metadata.def"
203 llvm_unreachable("Invalid metadata subclass");
206 assert(UseMap.empty() && "Expected all uses to be replaced");
209 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
218 // Copy out uses since UseMap could get touched below.
219 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
220 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
221 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
222 return L.second.second < R.second.second;
225 for (const auto &Pair : Uses) {
226 auto Owner = Pair.second.first;
229 if (Owner.is<MetadataAsValue *>())
232 // Resolve MDNodes that point at this.
233 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
236 if (OwnerMD->isResolved())
238 OwnerMD->decrementUnresolvedOperandCount();
242 static Function *getLocalFunction(Value *V) {
243 assert(V && "Expected value");
244 if (auto *A = dyn_cast<Argument>(V))
245 return A->getParent();
246 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
247 return BB->getParent();
251 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
252 assert(V && "Unexpected null Value");
254 auto &Context = V->getContext();
255 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
257 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
258 "Expected constant or function-local value");
259 assert(!V->NameAndIsUsedByMD.getInt() &&
260 "Expected this to be the only metadata use");
261 V->NameAndIsUsedByMD.setInt(true);
262 if (auto *C = dyn_cast<Constant>(V))
263 Entry = new ConstantAsMetadata(C);
265 Entry = new LocalAsMetadata(V);
271 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
272 assert(V && "Unexpected null Value");
273 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
276 void ValueAsMetadata::handleDeletion(Value *V) {
277 assert(V && "Expected valid value");
279 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
280 auto I = Store.find(V);
281 if (I == Store.end())
284 // Remove old entry from the map.
285 ValueAsMetadata *MD = I->second;
286 assert(MD && "Expected valid metadata");
287 assert(MD->getValue() == V && "Expected valid mapping");
290 // Delete the metadata.
291 MD->replaceAllUsesWith(nullptr);
295 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
296 assert(From && "Expected valid value");
297 assert(To && "Expected valid value");
298 assert(From != To && "Expected changed value");
299 assert(From->getType() == To->getType() && "Unexpected type change");
301 LLVMContext &Context = From->getType()->getContext();
302 auto &Store = Context.pImpl->ValuesAsMetadata;
303 auto I = Store.find(From);
304 if (I == Store.end()) {
305 assert(!From->NameAndIsUsedByMD.getInt() &&
306 "Expected From not to be used by metadata");
310 // Remove old entry from the map.
311 assert(From->NameAndIsUsedByMD.getInt() &&
312 "Expected From to be used by metadata");
313 From->NameAndIsUsedByMD.setInt(false);
314 ValueAsMetadata *MD = I->second;
315 assert(MD && "Expected valid metadata");
316 assert(MD->getValue() == From && "Expected valid mapping");
319 if (isa<LocalAsMetadata>(MD)) {
320 if (auto *C = dyn_cast<Constant>(To)) {
321 // Local became a constant.
322 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
326 if (getLocalFunction(From) && getLocalFunction(To) &&
327 getLocalFunction(From) != getLocalFunction(To)) {
329 MD->replaceAllUsesWith(nullptr);
333 } else if (!isa<Constant>(To)) {
334 // Changed to function-local value.
335 MD->replaceAllUsesWith(nullptr);
340 auto *&Entry = Store[To];
342 // The target already exists.
343 MD->replaceAllUsesWith(Entry);
348 // Update MD in place (and update the map entry).
349 assert(!To->NameAndIsUsedByMD.getInt() &&
350 "Expected this to be the only metadata use");
351 To->NameAndIsUsedByMD.setInt(true);
356 //===----------------------------------------------------------------------===//
357 // MDString implementation.
360 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
361 auto &Store = Context.pImpl->MDStringCache;
362 auto I = Store.find(Str);
363 if (I != Store.end())
367 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
368 bool WasInserted = Store.insert(Entry);
370 assert(WasInserted && "Expected entry to be inserted");
371 Entry->second.Entry = Entry;
372 return &Entry->second;
375 StringRef MDString::getString() const {
376 assert(Entry && "Expected to find string map entry");
377 return Entry->first();
380 //===----------------------------------------------------------------------===//
381 // MDNode implementation.
384 void *MDNode::operator new(size_t Size, unsigned NumOps) {
385 void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
386 MDOperand *O = static_cast<MDOperand *>(Ptr);
387 for (MDOperand *E = O + NumOps; O != E; ++O)
388 (void)new (O) MDOperand;
392 void MDNode::operator delete(void *Mem) {
393 MDNode *N = static_cast<MDNode *>(Mem);
394 MDOperand *O = static_cast<MDOperand *>(Mem);
395 for (MDOperand *E = O - N->NumOperands; O != E; --O)
396 (O - 1)->~MDOperand();
397 ::operator delete(O);
400 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
401 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
402 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
403 NumUnresolved(0), Context(Context) {
405 for (Metadata *MD : Ops1)
406 setOperand(Op++, MD);
407 for (Metadata *MD : Ops2)
408 setOperand(Op++, MD);
414 // Check whether any operands are unresolved, requiring re-uniquing. If
415 // not, don't support RAUW.
416 if (!countUnresolvedOperands())
419 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
422 TempMDNode MDNode::clone() const {
423 switch (getMetadataID()) {
425 llvm_unreachable("Invalid MDNode subclass");
426 #define HANDLE_MDNODE_LEAF(CLASS) \
428 return cast<CLASS>(this)->cloneImpl();
429 #include "llvm/IR/Metadata.def"
433 static bool isOperandUnresolved(Metadata *Op) {
434 if (auto *N = dyn_cast_or_null<MDNode>(Op))
435 return !N->isResolved();
439 unsigned MDNode::countUnresolvedOperands() {
440 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
441 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
442 return NumUnresolved;
445 void MDNode::makeUniqued() {
446 assert(isTemporary() && "Expected this to be temporary");
447 assert(!isResolved() && "Expected this to be unresolved");
449 // Make this 'uniqued'.
451 if (!countUnresolvedOperands())
454 assert(isUniqued() && "Expected this to be uniqued");
457 void MDNode::makeDistinct() {
458 assert(isTemporary() && "Expected this to be temporary");
459 assert(!isResolved() && "Expected this to be unresolved");
461 // Pretend to be uniqued, resolve the node, and then store in distinct table.
464 storeDistinctInContext();
466 assert(isDistinct() && "Expected this to be distinct");
467 assert(isResolved() && "Expected this to be resolved");
470 void MDNode::resolve() {
471 assert(isUniqued() && "Expected this to be uniqued");
472 assert(!isResolved() && "Expected this to be unresolved");
474 // Move the map, so that this immediately looks resolved.
475 auto Uses = Context.takeReplaceableUses();
477 assert(isResolved() && "Expected this to be resolved");
479 // Drop RAUW support.
480 Uses->resolveAllUses();
483 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
484 assert(NumUnresolved != 0 && "Expected unresolved operands");
486 // Check if an operand was resolved.
487 if (!isOperandUnresolved(Old)) {
488 if (isOperandUnresolved(New))
489 // An operand was un-resolved!
491 } else if (!isOperandUnresolved(New))
492 decrementUnresolvedOperandCount();
495 void MDNode::decrementUnresolvedOperandCount() {
496 if (!--NumUnresolved)
497 // Last unresolved operand has just been resolved.
501 void MDNode::resolveCycles() {
505 // Resolve this node immediately.
508 // Resolve all operands.
509 for (const auto &Op : operands()) {
510 auto *N = dyn_cast_or_null<MDNode>(Op);
514 assert(!N->isTemporary() &&
515 "Expected all forward declarations to be resolved");
516 if (!N->isResolved())
521 static bool hasSelfReference(MDNode *N) {
522 for (Metadata *MD : N->operands())
528 MDNode *MDNode::replaceWithPermanentImpl() {
529 if (hasSelfReference(this))
530 return replaceWithDistinctImpl();
531 return replaceWithUniquedImpl();
534 MDNode *MDNode::replaceWithUniquedImpl() {
535 // Try to uniquify in place.
536 MDNode *UniquedNode = uniquify();
538 if (UniquedNode == this) {
543 // Collision, so RAUW instead.
544 replaceAllUsesWith(UniquedNode);
549 MDNode *MDNode::replaceWithDistinctImpl() {
554 void MDTuple::recalculateHash() {
555 setHash(MDTupleInfo::KeyTy::calculateHash(this));
558 void MDNode::dropAllReferences() {
559 for (unsigned I = 0, E = NumOperands; I != E; ++I)
560 setOperand(I, nullptr);
562 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
563 (void)Context.takeReplaceableUses();
567 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
568 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
569 assert(Op < getNumOperands() && "Expected valid operand");
572 // This node is not uniqued. Just set the operand and be done with it.
577 // This node is uniqued.
580 Metadata *Old = getOperand(Op);
583 // Drop uniquing for self-reference cycles.
587 storeDistinctInContext();
591 // Re-unique the node.
592 auto *Uniqued = uniquify();
593 if (Uniqued == this) {
595 resolveAfterOperandChange(Old, New);
601 // Still unresolved, so RAUW.
603 // First, clear out all operands to prevent any recursion (similar to
604 // dropAllReferences(), but we still need the use-list).
605 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
606 setOperand(O, nullptr);
607 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
612 // Store in non-uniqued form if RAUW isn't possible.
613 storeDistinctInContext();
616 void MDNode::deleteAsSubclass() {
617 switch (getMetadataID()) {
619 llvm_unreachable("Invalid subclass of MDNode");
620 #define HANDLE_MDNODE_LEAF(CLASS) \
622 delete cast<CLASS>(this); \
624 #include "llvm/IR/Metadata.def"
628 template <class T, class InfoT>
629 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
630 if (T *U = getUniqued(Store, N))
637 template <class NodeTy> struct MDNode::HasCachedHash {
640 template <class U, U Val> struct SFINAE {};
643 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
644 template <class U> static No &check(...);
646 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
649 MDNode *MDNode::uniquify() {
650 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
652 // Try to insert into uniquing store.
653 switch (getMetadataID()) {
655 llvm_unreachable("Invalid subclass of MDNode");
656 #define HANDLE_MDNODE_LEAF(CLASS) \
657 case CLASS##Kind: { \
658 CLASS *SubclassThis = cast<CLASS>(this); \
659 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
660 ShouldRecalculateHash; \
661 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
662 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
664 #include "llvm/IR/Metadata.def"
668 void MDNode::eraseFromStore() {
669 switch (getMetadataID()) {
671 llvm_unreachable("Invalid subclass of MDNode");
672 #define HANDLE_MDNODE_LEAF(CLASS) \
674 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
676 #include "llvm/IR/Metadata.def"
680 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
681 StorageType Storage, bool ShouldCreate) {
683 if (Storage == Uniqued) {
684 MDTupleInfo::KeyTy Key(MDs);
685 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
689 Hash = Key.getHash();
691 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
694 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
695 Storage, Context.pImpl->MDTuples);
698 void MDNode::deleteTemporary(MDNode *N) {
699 assert(N->isTemporary() && "Expected temporary node");
700 N->replaceAllUsesWith(nullptr);
701 N->deleteAsSubclass();
704 void MDNode::storeDistinctInContext() {
705 assert(isResolved() && "Expected resolved nodes");
709 switch (getMetadataID()) {
711 llvm_unreachable("Invalid subclass of MDNode");
712 #define HANDLE_MDNODE_LEAF(CLASS) \
713 case CLASS##Kind: { \
714 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
715 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
718 #include "llvm/IR/Metadata.def"
721 getContext().pImpl->DistinctMDNodes.insert(this);
724 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
725 if (getOperand(I) == New)
733 handleChangedOperand(mutable_begin() + I, New);
736 void MDNode::setOperand(unsigned I, Metadata *New) {
737 assert(I < NumOperands);
738 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
741 /// \brief Get a node, or a self-reference that looks like it.
743 /// Special handling for finding self-references, for use by \a
744 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
745 /// when self-referencing nodes were still uniqued. If the first operand has
746 /// the same operands as \c Ops, return the first operand instead.
747 static MDNode *getOrSelfReference(LLVMContext &Context,
748 ArrayRef<Metadata *> Ops) {
750 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
751 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
752 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
753 if (Ops[I] != N->getOperand(I))
754 return MDNode::get(Context, Ops);
758 return MDNode::get(Context, Ops);
761 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
767 SmallVector<Metadata *, 4> MDs;
768 MDs.reserve(A->getNumOperands() + B->getNumOperands());
769 MDs.append(A->op_begin(), A->op_end());
770 MDs.append(B->op_begin(), B->op_end());
772 // FIXME: This preserves long-standing behaviour, but is it really the right
773 // behaviour? Or was that an unintended side-effect of node uniquing?
774 return getOrSelfReference(A->getContext(), MDs);
777 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
781 SmallVector<Metadata *, 4> MDs;
782 for (Metadata *MD : A->operands())
783 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
786 // FIXME: This preserves long-standing behaviour, but is it really the right
787 // behaviour? Or was that an unintended side-effect of node uniquing?
788 return getOrSelfReference(A->getContext(), MDs);
791 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
795 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
796 for (Metadata *MD : A->operands())
797 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
800 // FIXME: This preserves long-standing behaviour, but is it really the right
801 // behaviour? Or was that an unintended side-effect of node uniquing?
802 return getOrSelfReference(A->getContext(), MDs);
805 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
809 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
810 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
811 if (AVal.compare(BVal) == APFloat::cmpLessThan)
816 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
817 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
820 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
821 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
824 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
825 ConstantInt *Low, ConstantInt *High) {
826 ConstantRange NewRange(Low->getValue(), High->getValue());
827 unsigned Size = EndPoints.size();
828 APInt LB = EndPoints[Size - 2]->getValue();
829 APInt LE = EndPoints[Size - 1]->getValue();
830 ConstantRange LastRange(LB, LE);
831 if (canBeMerged(NewRange, LastRange)) {
832 ConstantRange Union = LastRange.unionWith(NewRange);
833 Type *Ty = High->getType();
834 EndPoints[Size - 2] =
835 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
836 EndPoints[Size - 1] =
837 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
843 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
844 ConstantInt *Low, ConstantInt *High) {
845 if (!EndPoints.empty())
846 if (tryMergeRange(EndPoints, Low, High))
849 EndPoints.push_back(Low);
850 EndPoints.push_back(High);
853 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
854 // Given two ranges, we want to compute the union of the ranges. This
855 // is slightly complitade by having to combine the intervals and merge
856 // the ones that overlap.
864 // First, walk both lists in older of the lower boundary of each interval.
865 // At each step, try to merge the new interval to the last one we adedd.
866 SmallVector<ConstantInt *, 4> EndPoints;
869 int AN = A->getNumOperands() / 2;
870 int BN = B->getNumOperands() / 2;
871 while (AI < AN && BI < BN) {
872 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
873 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
875 if (ALow->getValue().slt(BLow->getValue())) {
876 addRange(EndPoints, ALow,
877 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
880 addRange(EndPoints, BLow,
881 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
886 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
887 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
891 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
892 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
896 // If we have more than 2 ranges (4 endpoints) we have to try to merge
897 // the last and first ones.
898 unsigned Size = EndPoints.size();
900 ConstantInt *FB = EndPoints[0];
901 ConstantInt *FE = EndPoints[1];
902 if (tryMergeRange(EndPoints, FB, FE)) {
903 for (unsigned i = 0; i < Size - 2; ++i) {
904 EndPoints[i] = EndPoints[i + 2];
906 EndPoints.resize(Size - 2);
910 // If in the end we have a single range, it is possible that it is now the
911 // full range. Just drop the metadata in that case.
912 if (EndPoints.size() == 2) {
913 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
914 if (Range.isFullSet())
918 SmallVector<Metadata *, 4> MDs;
919 MDs.reserve(EndPoints.size());
920 for (auto *I : EndPoints)
921 MDs.push_back(ConstantAsMetadata::get(I));
922 return MDNode::get(A->getContext(), MDs);
925 //===----------------------------------------------------------------------===//
926 // NamedMDNode implementation.
929 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
930 return *(SmallVector<TrackingMDRef, 4> *)Operands;
933 NamedMDNode::NamedMDNode(const Twine &N)
934 : Name(N.str()), Parent(nullptr),
935 Operands(new SmallVector<TrackingMDRef, 4>()) {}
937 NamedMDNode::~NamedMDNode() {
939 delete &getNMDOps(Operands);
942 unsigned NamedMDNode::getNumOperands() const {
943 return (unsigned)getNMDOps(Operands).size();
946 MDNode *NamedMDNode::getOperand(unsigned i) const {
947 assert(i < getNumOperands() && "Invalid Operand number!");
948 auto *N = getNMDOps(Operands)[i].get();
949 return cast_or_null<MDNode>(N);
952 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
954 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
955 assert(I < getNumOperands() && "Invalid operand number");
956 getNMDOps(Operands)[I].reset(New);
959 void NamedMDNode::eraseFromParent() {
960 getParent()->eraseNamedMetadata(this);
963 void NamedMDNode::dropAllReferences() {
964 getNMDOps(Operands).clear();
967 StringRef NamedMDNode::getName() const {
968 return StringRef(Name);
971 //===----------------------------------------------------------------------===//
972 // Instruction Metadata method implementations.
975 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
976 if (!Node && !hasMetadata())
978 setMetadata(getContext().getMDKindID(Kind), Node);
981 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
982 return getMetadataImpl(getContext().getMDKindID(Kind));
985 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
986 SmallSet<unsigned, 5> KnownSet;
987 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
989 // Drop debug if needed
990 if (KnownSet.erase(LLVMContext::MD_dbg))
993 if (!hasMetadataHashEntry())
994 return; // Nothing to remove!
996 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
997 getContext().pImpl->MetadataStore;
999 if (KnownSet.empty()) {
1000 // Just drop our entry at the store.
1001 MetadataStore.erase(this);
1002 setHasMetadataHashEntry(false);
1006 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
1009 // Walk the array and drop any metadata we don't know.
1010 for (I = 0, E = Info.size(); I != E;) {
1011 if (KnownSet.count(Info[I].first)) {
1016 Info[I] = std::move(Info.back());
1020 assert(E == Info.size());
1023 // Drop our entry at the store.
1024 MetadataStore.erase(this);
1025 setHasMetadataHashEntry(false);
1029 /// setMetadata - Set the metadata of of the specified kind to the specified
1030 /// node. This updates/replaces metadata if already present, or removes it if
1032 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1033 if (!Node && !hasMetadata())
1036 // Handle 'dbg' as a special case since it is not stored in the hash table.
1037 if (KindID == LLVMContext::MD_dbg) {
1038 DbgLoc = DebugLoc::getFromDILocation(Node);
1042 // Handle the case when we're adding/updating metadata on an instruction.
1044 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1045 assert(!Info.empty() == hasMetadataHashEntry() &&
1046 "HasMetadata bit is wonked");
1048 setHasMetadataHashEntry(true);
1050 // Handle replacement of an existing value.
1051 for (auto &P : Info)
1052 if (P.first == KindID) {
1053 P.second.reset(Node);
1058 // No replacement, just add it to the list.
1059 Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
1060 std::make_tuple(Node));
1064 // Otherwise, we're removing metadata from an instruction.
1065 assert((hasMetadataHashEntry() ==
1066 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
1067 "HasMetadata bit out of date!");
1068 if (!hasMetadataHashEntry())
1069 return; // Nothing to remove!
1070 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1072 // Common case is removing the only entry.
1073 if (Info.size() == 1 && Info[0].first == KindID) {
1074 getContext().pImpl->MetadataStore.erase(this);
1075 setHasMetadataHashEntry(false);
1079 // Handle removal of an existing value.
1080 for (unsigned i = 0, e = Info.size(); i != e; ++i)
1081 if (Info[i].first == KindID) {
1082 Info[i] = std::move(Info.back());
1084 assert(!Info.empty() && "Removing last entry should be handled above");
1087 // Otherwise, removing an entry that doesn't exist on the instruction.
1090 void Instruction::setAAMetadata(const AAMDNodes &N) {
1091 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1092 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1093 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1096 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1097 // Handle 'dbg' as a special case since it is not stored in the hash table.
1098 if (KindID == LLVMContext::MD_dbg)
1099 return DbgLoc.getAsMDNode();
1101 if (!hasMetadataHashEntry()) return nullptr;
1103 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1104 assert(!Info.empty() && "bit out of sync with hash table");
1106 for (const auto &I : Info)
1107 if (I.first == KindID)
1112 void Instruction::getAllMetadataImpl(
1113 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1116 // Handle 'dbg' as a special case since it is not stored in the hash table.
1117 if (!DbgLoc.isUnknown()) {
1119 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1120 if (!hasMetadataHashEntry()) return;
1123 assert(hasMetadataHashEntry() &&
1124 getContext().pImpl->MetadataStore.count(this) &&
1125 "Shouldn't have called this");
1126 const LLVMContextImpl::MDMapTy &Info =
1127 getContext().pImpl->MetadataStore.find(this)->second;
1128 assert(!Info.empty() && "Shouldn't have called this");
1130 Result.reserve(Result.size() + Info.size());
1131 for (auto &I : Info)
1132 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1134 // Sort the resulting array so it is stable.
1135 if (Result.size() > 1)
1136 array_pod_sort(Result.begin(), Result.end());
1139 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1140 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1142 assert(hasMetadataHashEntry() &&
1143 getContext().pImpl->MetadataStore.count(this) &&
1144 "Shouldn't have called this");
1145 const LLVMContextImpl::MDMapTy &Info =
1146 getContext().pImpl->MetadataStore.find(this)->second;
1147 assert(!Info.empty() && "Shouldn't have called this");
1148 Result.reserve(Result.size() + Info.size());
1149 for (auto &I : Info)
1150 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1152 // Sort the resulting array so it is stable.
1153 if (Result.size() > 1)
1154 array_pod_sort(Result.begin(), Result.end());
1157 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1158 /// this instruction.
1159 void Instruction::clearMetadataHashEntries() {
1160 assert(hasMetadataHashEntry() && "Caller should check");
1161 getContext().pImpl->MetadataStore.erase(this);
1162 setHasMetadataHashEntry(false);