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->IsUsedByMD &&
260 "Expected this to be the only metadata use");
261 V->IsUsedByMD = 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->IsUsedByMD &&
306 "Expected From not to be used by metadata");
310 // Remove old entry from the map.
311 assert(From->IsUsedByMD &&
312 "Expected From to be used by metadata");
313 From->IsUsedByMD = 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->IsUsedByMD &&
350 "Expected this to be the only metadata use");
351 To->IsUsedByMD = 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 // Assert that the MDNode types will not be unaligned by the objects
385 // prepended to them.
386 #define HANDLE_MDNODE_LEAF(CLASS) \
388 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
389 "Alignment is insufficient after objects prepended to " #CLASS);
390 #include "llvm/IR/Metadata.def"
392 void *MDNode::operator new(size_t Size, unsigned NumOps) {
393 size_t OpSize = NumOps * sizeof(MDOperand);
394 // uint64_t is the most aligned type we need support (ensured by static_assert
396 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
397 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
398 MDOperand *O = static_cast<MDOperand *>(Ptr);
399 for (MDOperand *E = O - NumOps; O != E; --O)
400 (void)new (O - 1) MDOperand;
404 void MDNode::operator delete(void *Mem) {
405 MDNode *N = static_cast<MDNode *>(Mem);
406 size_t OpSize = N->NumOperands * sizeof(MDOperand);
407 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
409 MDOperand *O = static_cast<MDOperand *>(Mem);
410 for (MDOperand *E = O - N->NumOperands; O != E; --O)
411 (O - 1)->~MDOperand();
412 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
415 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
416 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
417 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
418 NumUnresolved(0), Context(Context) {
420 for (Metadata *MD : Ops1)
421 setOperand(Op++, MD);
422 for (Metadata *MD : Ops2)
423 setOperand(Op++, MD);
429 // Check whether any operands are unresolved, requiring re-uniquing. If
430 // not, don't support RAUW.
431 if (!countUnresolvedOperands())
434 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
437 TempMDNode MDNode::clone() const {
438 switch (getMetadataID()) {
440 llvm_unreachable("Invalid MDNode subclass");
441 #define HANDLE_MDNODE_LEAF(CLASS) \
443 return cast<CLASS>(this)->cloneImpl();
444 #include "llvm/IR/Metadata.def"
448 static bool isOperandUnresolved(Metadata *Op) {
449 if (auto *N = dyn_cast_or_null<MDNode>(Op))
450 return !N->isResolved();
454 unsigned MDNode::countUnresolvedOperands() {
455 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
456 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
457 return NumUnresolved;
460 void MDNode::makeUniqued() {
461 assert(isTemporary() && "Expected this to be temporary");
462 assert(!isResolved() && "Expected this to be unresolved");
464 // Enable uniquing callbacks.
465 for (auto &Op : mutable_operands())
466 Op.reset(Op.get(), this);
468 // Make this 'uniqued'.
470 if (!countUnresolvedOperands())
473 assert(isUniqued() && "Expected this to be uniqued");
476 void MDNode::makeDistinct() {
477 assert(isTemporary() && "Expected this to be temporary");
478 assert(!isResolved() && "Expected this to be unresolved");
480 // Pretend to be uniqued, resolve the node, and then store in distinct table.
483 storeDistinctInContext();
485 assert(isDistinct() && "Expected this to be distinct");
486 assert(isResolved() && "Expected this to be resolved");
489 void MDNode::resolve() {
490 assert(isUniqued() && "Expected this to be uniqued");
491 assert(!isResolved() && "Expected this to be unresolved");
493 // Move the map, so that this immediately looks resolved.
494 auto Uses = Context.takeReplaceableUses();
496 assert(isResolved() && "Expected this to be resolved");
498 // Drop RAUW support.
499 Uses->resolveAllUses();
502 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
503 assert(NumUnresolved != 0 && "Expected unresolved operands");
505 // Check if an operand was resolved.
506 if (!isOperandUnresolved(Old)) {
507 if (isOperandUnresolved(New))
508 // An operand was un-resolved!
510 } else if (!isOperandUnresolved(New))
511 decrementUnresolvedOperandCount();
514 void MDNode::decrementUnresolvedOperandCount() {
515 if (!--NumUnresolved)
516 // Last unresolved operand has just been resolved.
520 void MDNode::resolveCycles() {
524 // Resolve this node immediately.
527 // Resolve all operands.
528 for (const auto &Op : operands()) {
529 auto *N = dyn_cast_or_null<MDNode>(Op);
533 assert(!N->isTemporary() &&
534 "Expected all forward declarations to be resolved");
535 if (!N->isResolved())
540 static bool hasSelfReference(MDNode *N) {
541 for (Metadata *MD : N->operands())
547 MDNode *MDNode::replaceWithPermanentImpl() {
548 if (hasSelfReference(this))
549 return replaceWithDistinctImpl();
550 return replaceWithUniquedImpl();
553 MDNode *MDNode::replaceWithUniquedImpl() {
554 // Try to uniquify in place.
555 MDNode *UniquedNode = uniquify();
557 if (UniquedNode == this) {
562 // Collision, so RAUW instead.
563 replaceAllUsesWith(UniquedNode);
568 MDNode *MDNode::replaceWithDistinctImpl() {
573 void MDTuple::recalculateHash() {
574 setHash(MDTupleInfo::KeyTy::calculateHash(this));
577 void MDNode::dropAllReferences() {
578 for (unsigned I = 0, E = NumOperands; I != E; ++I)
579 setOperand(I, nullptr);
581 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
582 (void)Context.takeReplaceableUses();
586 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
587 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
588 assert(Op < getNumOperands() && "Expected valid operand");
591 // This node is not uniqued. Just set the operand and be done with it.
596 // This node is uniqued.
599 Metadata *Old = getOperand(Op);
602 // Drop uniquing for self-reference cycles.
606 storeDistinctInContext();
610 // Re-unique the node.
611 auto *Uniqued = uniquify();
612 if (Uniqued == this) {
614 resolveAfterOperandChange(Old, New);
620 // Still unresolved, so RAUW.
622 // First, clear out all operands to prevent any recursion (similar to
623 // dropAllReferences(), but we still need the use-list).
624 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
625 setOperand(O, nullptr);
626 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
631 // Store in non-uniqued form if RAUW isn't possible.
632 storeDistinctInContext();
635 void MDNode::deleteAsSubclass() {
636 switch (getMetadataID()) {
638 llvm_unreachable("Invalid subclass of MDNode");
639 #define HANDLE_MDNODE_LEAF(CLASS) \
641 delete cast<CLASS>(this); \
643 #include "llvm/IR/Metadata.def"
647 template <class T, class InfoT>
648 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
649 if (T *U = getUniqued(Store, N))
656 template <class NodeTy> struct MDNode::HasCachedHash {
659 template <class U, U Val> struct SFINAE {};
662 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
663 template <class U> static No &check(...);
665 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
668 MDNode *MDNode::uniquify() {
669 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
671 // Try to insert into uniquing store.
672 switch (getMetadataID()) {
674 llvm_unreachable("Invalid subclass of MDNode");
675 #define HANDLE_MDNODE_LEAF(CLASS) \
676 case CLASS##Kind: { \
677 CLASS *SubclassThis = cast<CLASS>(this); \
678 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
679 ShouldRecalculateHash; \
680 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
681 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
683 #include "llvm/IR/Metadata.def"
687 void MDNode::eraseFromStore() {
688 switch (getMetadataID()) {
690 llvm_unreachable("Invalid subclass of MDNode");
691 #define HANDLE_MDNODE_LEAF(CLASS) \
693 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
695 #include "llvm/IR/Metadata.def"
699 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
700 StorageType Storage, bool ShouldCreate) {
702 if (Storage == Uniqued) {
703 MDTupleInfo::KeyTy Key(MDs);
704 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
708 Hash = Key.getHash();
710 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
713 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
714 Storage, Context.pImpl->MDTuples);
717 void MDNode::deleteTemporary(MDNode *N) {
718 assert(N->isTemporary() && "Expected temporary node");
719 N->replaceAllUsesWith(nullptr);
720 N->deleteAsSubclass();
723 void MDNode::storeDistinctInContext() {
724 assert(isResolved() && "Expected resolved nodes");
728 switch (getMetadataID()) {
730 llvm_unreachable("Invalid subclass of MDNode");
731 #define HANDLE_MDNODE_LEAF(CLASS) \
732 case CLASS##Kind: { \
733 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
734 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
737 #include "llvm/IR/Metadata.def"
740 getContext().pImpl->DistinctMDNodes.insert(this);
743 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
744 if (getOperand(I) == New)
752 handleChangedOperand(mutable_begin() + I, New);
755 void MDNode::setOperand(unsigned I, Metadata *New) {
756 assert(I < NumOperands);
757 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
760 /// \brief Get a node, or a self-reference that looks like it.
762 /// Special handling for finding self-references, for use by \a
763 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
764 /// when self-referencing nodes were still uniqued. If the first operand has
765 /// the same operands as \c Ops, return the first operand instead.
766 static MDNode *getOrSelfReference(LLVMContext &Context,
767 ArrayRef<Metadata *> Ops) {
769 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
770 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
771 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
772 if (Ops[I] != N->getOperand(I))
773 return MDNode::get(Context, Ops);
777 return MDNode::get(Context, Ops);
780 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
786 SmallVector<Metadata *, 4> MDs;
787 MDs.reserve(A->getNumOperands() + B->getNumOperands());
788 MDs.append(A->op_begin(), A->op_end());
789 MDs.append(B->op_begin(), B->op_end());
791 // FIXME: This preserves long-standing behaviour, but is it really the right
792 // behaviour? Or was that an unintended side-effect of node uniquing?
793 return getOrSelfReference(A->getContext(), MDs);
796 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
800 SmallVector<Metadata *, 4> MDs;
801 for (Metadata *MD : A->operands())
802 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
805 // FIXME: This preserves long-standing behaviour, but is it really the right
806 // behaviour? Or was that an unintended side-effect of node uniquing?
807 return getOrSelfReference(A->getContext(), MDs);
810 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
814 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
815 for (Metadata *MD : A->operands())
816 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
819 // FIXME: This preserves long-standing behaviour, but is it really the right
820 // behaviour? Or was that an unintended side-effect of node uniquing?
821 return getOrSelfReference(A->getContext(), MDs);
824 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
828 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
829 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
830 if (AVal.compare(BVal) == APFloat::cmpLessThan)
835 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
836 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
839 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
840 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
843 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
844 ConstantInt *Low, ConstantInt *High) {
845 ConstantRange NewRange(Low->getValue(), High->getValue());
846 unsigned Size = EndPoints.size();
847 APInt LB = EndPoints[Size - 2]->getValue();
848 APInt LE = EndPoints[Size - 1]->getValue();
849 ConstantRange LastRange(LB, LE);
850 if (canBeMerged(NewRange, LastRange)) {
851 ConstantRange Union = LastRange.unionWith(NewRange);
852 Type *Ty = High->getType();
853 EndPoints[Size - 2] =
854 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
855 EndPoints[Size - 1] =
856 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
862 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
863 ConstantInt *Low, ConstantInt *High) {
864 if (!EndPoints.empty())
865 if (tryMergeRange(EndPoints, Low, High))
868 EndPoints.push_back(Low);
869 EndPoints.push_back(High);
872 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
873 // Given two ranges, we want to compute the union of the ranges. This
874 // is slightly complitade by having to combine the intervals and merge
875 // the ones that overlap.
883 // First, walk both lists in older of the lower boundary of each interval.
884 // At each step, try to merge the new interval to the last one we adedd.
885 SmallVector<ConstantInt *, 4> EndPoints;
888 int AN = A->getNumOperands() / 2;
889 int BN = B->getNumOperands() / 2;
890 while (AI < AN && BI < BN) {
891 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
892 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
894 if (ALow->getValue().slt(BLow->getValue())) {
895 addRange(EndPoints, ALow,
896 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
899 addRange(EndPoints, BLow,
900 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
905 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
906 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
910 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
911 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
915 // If we have more than 2 ranges (4 endpoints) we have to try to merge
916 // the last and first ones.
917 unsigned Size = EndPoints.size();
919 ConstantInt *FB = EndPoints[0];
920 ConstantInt *FE = EndPoints[1];
921 if (tryMergeRange(EndPoints, FB, FE)) {
922 for (unsigned i = 0; i < Size - 2; ++i) {
923 EndPoints[i] = EndPoints[i + 2];
925 EndPoints.resize(Size - 2);
929 // If in the end we have a single range, it is possible that it is now the
930 // full range. Just drop the metadata in that case.
931 if (EndPoints.size() == 2) {
932 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
933 if (Range.isFullSet())
937 SmallVector<Metadata *, 4> MDs;
938 MDs.reserve(EndPoints.size());
939 for (auto *I : EndPoints)
940 MDs.push_back(ConstantAsMetadata::get(I));
941 return MDNode::get(A->getContext(), MDs);
944 //===----------------------------------------------------------------------===//
945 // NamedMDNode implementation.
948 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
949 return *(SmallVector<TrackingMDRef, 4> *)Operands;
952 NamedMDNode::NamedMDNode(const Twine &N)
953 : Name(N.str()), Parent(nullptr),
954 Operands(new SmallVector<TrackingMDRef, 4>()) {}
956 NamedMDNode::~NamedMDNode() {
958 delete &getNMDOps(Operands);
961 unsigned NamedMDNode::getNumOperands() const {
962 return (unsigned)getNMDOps(Operands).size();
965 MDNode *NamedMDNode::getOperand(unsigned i) const {
966 assert(i < getNumOperands() && "Invalid Operand number!");
967 auto *N = getNMDOps(Operands)[i].get();
968 return cast_or_null<MDNode>(N);
971 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
973 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
974 assert(I < getNumOperands() && "Invalid operand number");
975 getNMDOps(Operands)[I].reset(New);
978 void NamedMDNode::eraseFromParent() {
979 getParent()->eraseNamedMetadata(this);
982 void NamedMDNode::dropAllReferences() {
983 getNMDOps(Operands).clear();
986 StringRef NamedMDNode::getName() const {
987 return StringRef(Name);
990 //===----------------------------------------------------------------------===//
991 // Instruction Metadata method implementations.
993 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
994 for (auto &I : Attachments)
999 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1000 std::make_tuple(&MD));
1003 void MDAttachmentMap::erase(unsigned ID) {
1007 // Common case is one/last value.
1008 if (Attachments.back().first == ID) {
1009 Attachments.pop_back();
1013 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1015 if (I->first == ID) {
1016 *I = std::move(Attachments.back());
1017 Attachments.pop_back();
1022 MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1023 for (const auto &I : Attachments)
1029 void MDAttachmentMap::getAll(
1030 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1031 Result.append(Attachments.begin(), Attachments.end());
1033 // Sort the resulting array so it is stable.
1034 if (Result.size() > 1)
1035 array_pod_sort(Result.begin(), Result.end());
1038 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1039 if (!Node && !hasMetadata())
1041 setMetadata(getContext().getMDKindID(Kind), Node);
1044 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1045 return getMetadataImpl(getContext().getMDKindID(Kind));
1048 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1049 SmallSet<unsigned, 5> KnownSet;
1050 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1052 // Drop debug if needed
1053 if (KnownSet.erase(LLVMContext::MD_dbg))
1054 DbgLoc = DebugLoc();
1056 if (!hasMetadataHashEntry())
1057 return; // Nothing to remove!
1059 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1061 if (KnownSet.empty()) {
1062 // Just drop our entry at the store.
1063 InstructionMetadata.erase(this);
1064 setHasMetadataHashEntry(false);
1068 auto &Info = InstructionMetadata[this];
1069 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1070 return !KnownSet.count(I.first);
1074 // Drop our entry at the store.
1075 InstructionMetadata.erase(this);
1076 setHasMetadataHashEntry(false);
1080 /// setMetadata - Set the metadata of of the specified kind to the specified
1081 /// node. This updates/replaces metadata if already present, or removes it if
1083 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1084 if (!Node && !hasMetadata())
1087 // Handle 'dbg' as a special case since it is not stored in the hash table.
1088 if (KindID == LLVMContext::MD_dbg) {
1089 DbgLoc = DebugLoc(Node);
1093 // Handle the case when we're adding/updating metadata on an instruction.
1095 auto &Info = getContext().pImpl->InstructionMetadata[this];
1096 assert(!Info.empty() == hasMetadataHashEntry() &&
1097 "HasMetadata bit is wonked");
1099 setHasMetadataHashEntry(true);
1100 Info.set(KindID, *Node);
1104 // Otherwise, we're removing metadata from an instruction.
1105 assert((hasMetadataHashEntry() ==
1106 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
1107 "HasMetadata bit out of date!");
1108 if (!hasMetadataHashEntry())
1109 return; // Nothing to remove!
1110 auto &Info = getContext().pImpl->InstructionMetadata[this];
1112 // Handle removal of an existing value.
1118 getContext().pImpl->InstructionMetadata.erase(this);
1119 setHasMetadataHashEntry(false);
1122 void Instruction::setAAMetadata(const AAMDNodes &N) {
1123 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1124 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1125 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1128 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1129 // Handle 'dbg' as a special case since it is not stored in the hash table.
1130 if (KindID == LLVMContext::MD_dbg)
1131 return DbgLoc.getAsMDNode();
1133 if (!hasMetadataHashEntry())
1135 auto &Info = getContext().pImpl->InstructionMetadata[this];
1136 assert(!Info.empty() && "bit out of sync with hash table");
1138 return Info.lookup(KindID);
1141 void Instruction::getAllMetadataImpl(
1142 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1145 // Handle 'dbg' as a special case since it is not stored in the hash table.
1148 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1149 if (!hasMetadataHashEntry()) return;
1152 assert(hasMetadataHashEntry() &&
1153 getContext().pImpl->InstructionMetadata.count(this) &&
1154 "Shouldn't have called this");
1155 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1156 assert(!Info.empty() && "Shouldn't have called this");
1157 Info.getAll(Result);
1160 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1161 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1163 assert(hasMetadataHashEntry() &&
1164 getContext().pImpl->InstructionMetadata.count(this) &&
1165 "Shouldn't have called this");
1166 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1167 assert(!Info.empty() && "Shouldn't have called this");
1168 Info.getAll(Result);
1171 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1172 /// this instruction.
1173 void Instruction::clearMetadataHashEntries() {
1174 assert(hasMetadataHashEntry() && "Caller should check");
1175 getContext().pImpl->InstructionMetadata.erase(this);
1176 setHasMetadataHashEntry(false);
1179 MDNode *Function::getMetadata(unsigned KindID) const {
1182 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1185 MDNode *Function::getMetadata(StringRef Kind) const {
1188 return getMetadata(getContext().getMDKindID(Kind));
1191 void Function::setMetadata(unsigned KindID, MDNode *MD) {
1194 setHasMetadataHashEntry(true);
1196 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1200 // Nothing to unset.
1204 auto &Store = getContext().pImpl->FunctionMetadata[this];
1205 Store.erase(KindID);
1210 void Function::setMetadata(StringRef Kind, MDNode *MD) {
1211 if (!MD && !hasMetadata())
1213 setMetadata(getContext().getMDKindID(Kind), MD);
1216 void Function::getAllMetadata(
1217 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1223 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1226 void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1229 if (KnownIDs.empty()) {
1234 SmallSet<unsigned, 5> KnownSet;
1235 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1237 auto &Store = getContext().pImpl->FunctionMetadata[this];
1238 assert(!Store.empty());
1240 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1241 return !KnownSet.count(I.first);
1248 void Function::clearMetadata() {
1251 getContext().pImpl->FunctionMetadata.erase(this);
1252 setHasMetadataHashEntry(false);