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::getMostGenericAliasScope(MDNode *A, MDNode *B) {
789 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
790 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
791 Metadata *MD = A->getOperand(i);
793 for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
794 if (MD == B->getOperand(j)) {
802 // FIXME: This preserves long-standing behaviour, but is it really the right
803 // behaviour? Or was that an unintended side-effect of node uniquing?
804 return getOrSelfReference(A->getContext(), MDs);
807 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
811 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
812 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
813 if (AVal.compare(BVal) == APFloat::cmpLessThan)
818 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
819 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
822 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
823 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
826 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
827 ConstantInt *Low, ConstantInt *High) {
828 ConstantRange NewRange(Low->getValue(), High->getValue());
829 unsigned Size = EndPoints.size();
830 APInt LB = EndPoints[Size - 2]->getValue();
831 APInt LE = EndPoints[Size - 1]->getValue();
832 ConstantRange LastRange(LB, LE);
833 if (canBeMerged(NewRange, LastRange)) {
834 ConstantRange Union = LastRange.unionWith(NewRange);
835 Type *Ty = High->getType();
836 EndPoints[Size - 2] =
837 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
838 EndPoints[Size - 1] =
839 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
845 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
846 ConstantInt *Low, ConstantInt *High) {
847 if (!EndPoints.empty())
848 if (tryMergeRange(EndPoints, Low, High))
851 EndPoints.push_back(Low);
852 EndPoints.push_back(High);
855 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
856 // Given two ranges, we want to compute the union of the ranges. This
857 // is slightly complitade by having to combine the intervals and merge
858 // the ones that overlap.
866 // First, walk both lists in older of the lower boundary of each interval.
867 // At each step, try to merge the new interval to the last one we adedd.
868 SmallVector<ConstantInt *, 4> EndPoints;
871 int AN = A->getNumOperands() / 2;
872 int BN = B->getNumOperands() / 2;
873 while (AI < AN && BI < BN) {
874 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
875 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
877 if (ALow->getValue().slt(BLow->getValue())) {
878 addRange(EndPoints, ALow,
879 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
882 addRange(EndPoints, BLow,
883 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
888 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
889 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
893 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
894 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
898 // If we have more than 2 ranges (4 endpoints) we have to try to merge
899 // the last and first ones.
900 unsigned Size = EndPoints.size();
902 ConstantInt *FB = EndPoints[0];
903 ConstantInt *FE = EndPoints[1];
904 if (tryMergeRange(EndPoints, FB, FE)) {
905 for (unsigned i = 0; i < Size - 2; ++i) {
906 EndPoints[i] = EndPoints[i + 2];
908 EndPoints.resize(Size - 2);
912 // If in the end we have a single range, it is possible that it is now the
913 // full range. Just drop the metadata in that case.
914 if (EndPoints.size() == 2) {
915 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
916 if (Range.isFullSet())
920 SmallVector<Metadata *, 4> MDs;
921 MDs.reserve(EndPoints.size());
922 for (auto *I : EndPoints)
923 MDs.push_back(ConstantAsMetadata::get(I));
924 return MDNode::get(A->getContext(), MDs);
927 //===----------------------------------------------------------------------===//
928 // NamedMDNode implementation.
931 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
932 return *(SmallVector<TrackingMDRef, 4> *)Operands;
935 NamedMDNode::NamedMDNode(const Twine &N)
936 : Name(N.str()), Parent(nullptr),
937 Operands(new SmallVector<TrackingMDRef, 4>()) {}
939 NamedMDNode::~NamedMDNode() {
941 delete &getNMDOps(Operands);
944 unsigned NamedMDNode::getNumOperands() const {
945 return (unsigned)getNMDOps(Operands).size();
948 MDNode *NamedMDNode::getOperand(unsigned i) const {
949 assert(i < getNumOperands() && "Invalid Operand number!");
950 auto *N = getNMDOps(Operands)[i].get();
951 return cast_or_null<MDNode>(N);
954 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
956 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
957 assert(I < getNumOperands() && "Invalid operand number");
958 getNMDOps(Operands)[I].reset(New);
961 void NamedMDNode::eraseFromParent() {
962 getParent()->eraseNamedMetadata(this);
965 void NamedMDNode::dropAllReferences() {
966 getNMDOps(Operands).clear();
969 StringRef NamedMDNode::getName() const {
970 return StringRef(Name);
973 //===----------------------------------------------------------------------===//
974 // Instruction Metadata method implementations.
977 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
978 if (!Node && !hasMetadata())
980 setMetadata(getContext().getMDKindID(Kind), Node);
983 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
984 return getMetadataImpl(getContext().getMDKindID(Kind));
987 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
988 SmallSet<unsigned, 5> KnownSet;
989 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
991 // Drop debug if needed
992 if (KnownSet.erase(LLVMContext::MD_dbg))
995 if (!hasMetadataHashEntry())
996 return; // Nothing to remove!
998 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
999 getContext().pImpl->MetadataStore;
1001 if (KnownSet.empty()) {
1002 // Just drop our entry at the store.
1003 MetadataStore.erase(this);
1004 setHasMetadataHashEntry(false);
1008 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
1011 // Walk the array and drop any metadata we don't know.
1012 for (I = 0, E = Info.size(); I != E;) {
1013 if (KnownSet.count(Info[I].first)) {
1018 Info[I] = std::move(Info.back());
1022 assert(E == Info.size());
1025 // Drop our entry at the store.
1026 MetadataStore.erase(this);
1027 setHasMetadataHashEntry(false);
1031 /// setMetadata - Set the metadata of of the specified kind to the specified
1032 /// node. This updates/replaces metadata if already present, or removes it if
1034 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1035 if (!Node && !hasMetadata())
1038 // Handle 'dbg' as a special case since it is not stored in the hash table.
1039 if (KindID == LLVMContext::MD_dbg) {
1040 DbgLoc = DebugLoc::getFromDILocation(Node);
1044 // Handle the case when we're adding/updating metadata on an instruction.
1046 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1047 assert(!Info.empty() == hasMetadataHashEntry() &&
1048 "HasMetadata bit is wonked");
1050 setHasMetadataHashEntry(true);
1052 // Handle replacement of an existing value.
1053 for (auto &P : Info)
1054 if (P.first == KindID) {
1055 P.second.reset(Node);
1060 // No replacement, just add it to the list.
1061 Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
1062 std::make_tuple(Node));
1066 // Otherwise, we're removing metadata from an instruction.
1067 assert((hasMetadataHashEntry() ==
1068 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
1069 "HasMetadata bit out of date!");
1070 if (!hasMetadataHashEntry())
1071 return; // Nothing to remove!
1072 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1074 // Common case is removing the only entry.
1075 if (Info.size() == 1 && Info[0].first == KindID) {
1076 getContext().pImpl->MetadataStore.erase(this);
1077 setHasMetadataHashEntry(false);
1081 // Handle removal of an existing value.
1082 for (unsigned i = 0, e = Info.size(); i != e; ++i)
1083 if (Info[i].first == KindID) {
1084 Info[i] = std::move(Info.back());
1086 assert(!Info.empty() && "Removing last entry should be handled above");
1089 // Otherwise, removing an entry that doesn't exist on the instruction.
1092 void Instruction::setAAMetadata(const AAMDNodes &N) {
1093 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1094 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1095 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1098 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1099 // Handle 'dbg' as a special case since it is not stored in the hash table.
1100 if (KindID == LLVMContext::MD_dbg)
1101 return DbgLoc.getAsMDNode();
1103 if (!hasMetadataHashEntry()) return nullptr;
1105 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1106 assert(!Info.empty() && "bit out of sync with hash table");
1108 for (const auto &I : Info)
1109 if (I.first == KindID)
1114 void Instruction::getAllMetadataImpl(
1115 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1118 // Handle 'dbg' as a special case since it is not stored in the hash table.
1119 if (!DbgLoc.isUnknown()) {
1121 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1122 if (!hasMetadataHashEntry()) return;
1125 assert(hasMetadataHashEntry() &&
1126 getContext().pImpl->MetadataStore.count(this) &&
1127 "Shouldn't have called this");
1128 const LLVMContextImpl::MDMapTy &Info =
1129 getContext().pImpl->MetadataStore.find(this)->second;
1130 assert(!Info.empty() && "Shouldn't have called this");
1132 Result.reserve(Result.size() + Info.size());
1133 for (auto &I : Info)
1134 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1136 // Sort the resulting array so it is stable.
1137 if (Result.size() > 1)
1138 array_pod_sort(Result.begin(), Result.end());
1141 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1142 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1144 assert(hasMetadataHashEntry() &&
1145 getContext().pImpl->MetadataStore.count(this) &&
1146 "Shouldn't have called this");
1147 const LLVMContextImpl::MDMapTy &Info =
1148 getContext().pImpl->MetadataStore.find(this)->second;
1149 assert(!Info.empty() && "Shouldn't have called this");
1150 Result.reserve(Result.size() + Info.size());
1151 for (auto &I : Info)
1152 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1154 // Sort the resulting array so it is stable.
1155 if (Result.size() > 1)
1156 array_pod_sort(Result.begin(), Result.end());
1159 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1160 /// this instruction.
1161 void Instruction::clearMetadataHashEntries() {
1162 assert(hasMetadataHashEntry() && "Caller should check");
1163 getContext().pImpl->MetadataStore.erase(this);
1164 setHasMetadataHashEntry(false);