1 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/MetadataTracking.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <type_traits>
32 template<typename ValueSubClass, typename ItemParentClass>
33 class SymbolTableListTraits;
35 enum LLVMConstants : uint32_t {
36 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
39 /// \brief Root of the metadata hierarchy.
41 /// This is a root class for typeless data in the IR.
43 friend class ReplaceableMetadataImpl;
46 const unsigned char SubclassID;
49 /// \brief Active type of storage.
50 enum StorageType { Uniqued, Distinct, Temporary };
52 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
54 // TODO: expose remaining bits to subclasses.
56 unsigned short SubclassData16;
57 unsigned SubclassData32;
74 MDLexicalBlockFileKind,
76 MDTemplateTypeParameterKind,
77 MDTemplateValueParameterKind,
83 ConstantAsMetadataKind,
89 Metadata(unsigned ID, StorageType Storage)
90 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
94 /// \brief Default handling of a changed operand, which asserts.
96 /// If subclasses pass themselves in as owners to a tracking node reference,
97 /// they must provide an implementation of this method.
98 void handleChangedOperand(void *, Metadata *) {
99 llvm_unreachable("Unimplemented in Metadata subclass");
103 unsigned getMetadataID() const { return SubclassID; }
105 /// \brief User-friendly dump.
107 /// If \c M is provided, metadata nodes will be numbered canonically;
108 /// otherwise, pointer addresses are substituted.
109 void dump(const Module *M = nullptr) const;
113 /// Prints definition of \c this.
115 /// If \c M is provided, metadata nodes will be numbered canonically;
116 /// otherwise, pointer addresses are substituted.
117 void print(raw_ostream &OS, const Module *M = nullptr) const;
119 /// \brief Print as operand.
121 /// Prints reference of \c this.
123 /// If \c M is provided, metadata nodes will be numbered canonically;
124 /// otherwise, pointer addresses are substituted.
125 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
128 #define HANDLE_METADATA(CLASS) class CLASS;
129 #include "llvm/IR/Metadata.def"
131 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
136 /// \brief Metadata wrapper in the Value hierarchy.
138 /// A member of the \a Value hierarchy to represent a reference to metadata.
139 /// This allows, e.g., instrinsics to have metadata as operands.
141 /// Notably, this is the only thing in either hierarchy that is allowed to
142 /// reference \a LocalAsMetadata.
143 class MetadataAsValue : public Value {
144 friend class ReplaceableMetadataImpl;
145 friend class LLVMContextImpl;
149 MetadataAsValue(Type *Ty, Metadata *MD);
152 /// \brief Drop use of metadata (during teardown).
153 void dropUse() { MD = nullptr; }
156 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
157 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
158 Metadata *getMetadata() const { return MD; }
160 static bool classof(const Value *V) {
161 return V->getValueID() == MetadataAsValueVal;
165 void handleChangedMetadata(Metadata *MD);
170 /// \brief Shared implementation of use-lists for replaceable metadata.
172 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
173 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
174 /// and \a TempMDNode).
175 class ReplaceableMetadataImpl {
176 friend class MetadataTracking;
179 typedef MetadataTracking::OwnerTy OwnerTy;
182 LLVMContext &Context;
184 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
187 ReplaceableMetadataImpl(LLVMContext &Context)
188 : Context(Context), NextIndex(0) {}
189 ~ReplaceableMetadataImpl() {
190 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
193 LLVMContext &getContext() const { return Context; }
195 /// \brief Replace all uses of this with MD.
197 /// Replace all uses of this with \c MD, which is allowed to be null.
198 void replaceAllUsesWith(Metadata *MD);
200 /// \brief Resolve all uses of this.
202 /// Resolve all uses of this, turning off RAUW permanently. If \c
203 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
205 void resolveAllUses(bool ResolveUsers = true);
208 void addRef(void *Ref, OwnerTy Owner);
209 void dropRef(void *Ref);
210 void moveRef(void *Ref, void *New, const Metadata &MD);
212 static ReplaceableMetadataImpl *get(Metadata &MD);
215 /// \brief Value wrapper in the Metadata hierarchy.
217 /// This is a custom value handle that allows other metadata to refer to
218 /// classes in the Value hierarchy.
220 /// Because of full uniquing support, each value is only wrapped by a single \a
221 /// ValueAsMetadata object, so the lookup maps are far more efficient than
222 /// those using ValueHandleBase.
223 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
224 friend class ReplaceableMetadataImpl;
225 friend class LLVMContextImpl;
229 /// \brief Drop users without RAUW (during teardown).
231 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
235 ValueAsMetadata(unsigned ID, Value *V)
236 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
237 assert(V && "Expected valid value");
239 ~ValueAsMetadata() {}
242 static ValueAsMetadata *get(Value *V);
243 static ConstantAsMetadata *getConstant(Value *C) {
244 return cast<ConstantAsMetadata>(get(C));
246 static LocalAsMetadata *getLocal(Value *Local) {
247 return cast<LocalAsMetadata>(get(Local));
250 static ValueAsMetadata *getIfExists(Value *V);
251 static ConstantAsMetadata *getConstantIfExists(Value *C) {
252 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
254 static LocalAsMetadata *getLocalIfExists(Value *Local) {
255 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
258 Value *getValue() const { return V; }
259 Type *getType() const { return V->getType(); }
260 LLVMContext &getContext() const { return V->getContext(); }
262 static void handleDeletion(Value *V);
263 static void handleRAUW(Value *From, Value *To);
266 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
268 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
269 /// \a Value gets RAUW'ed and the target already exists, this is used to
270 /// merge the two metadata nodes.
271 void replaceAllUsesWith(Metadata *MD) {
272 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
276 static bool classof(const Metadata *MD) {
277 return MD->getMetadataID() == LocalAsMetadataKind ||
278 MD->getMetadataID() == ConstantAsMetadataKind;
282 class ConstantAsMetadata : public ValueAsMetadata {
283 friend class ValueAsMetadata;
285 ConstantAsMetadata(Constant *C)
286 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
289 static ConstantAsMetadata *get(Constant *C) {
290 return ValueAsMetadata::getConstant(C);
292 static ConstantAsMetadata *getIfExists(Constant *C) {
293 return ValueAsMetadata::getConstantIfExists(C);
296 Constant *getValue() const {
297 return cast<Constant>(ValueAsMetadata::getValue());
300 static bool classof(const Metadata *MD) {
301 return MD->getMetadataID() == ConstantAsMetadataKind;
305 class LocalAsMetadata : public ValueAsMetadata {
306 friend class ValueAsMetadata;
308 LocalAsMetadata(Value *Local)
309 : ValueAsMetadata(LocalAsMetadataKind, Local) {
310 assert(!isa<Constant>(Local) && "Expected local value");
314 static LocalAsMetadata *get(Value *Local) {
315 return ValueAsMetadata::getLocal(Local);
317 static LocalAsMetadata *getIfExists(Value *Local) {
318 return ValueAsMetadata::getLocalIfExists(Local);
321 static bool classof(const Metadata *MD) {
322 return MD->getMetadataID() == LocalAsMetadataKind;
326 /// \brief Transitional API for extracting constants from Metadata.
328 /// This namespace contains transitional functions for metadata that points to
331 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
332 /// operands could refer to any \a Value. There's was a lot of code like this:
336 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
339 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
340 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
341 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
342 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
343 /// requires subtle control flow changes.
345 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
346 /// so that metadata can refer to numbers without traversing a bridge to the \a
347 /// Value hierarchy. In this final state, the code above would look like this:
351 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
354 /// The API in this namespace supports the transition. \a MDInt doesn't exist
355 /// yet, and even once it does, changing each metadata schema to use it is its
356 /// own mini-project. In the meantime this API prevents us from introducing
357 /// complex and bug-prone control flow that will disappear in the end. In
358 /// particular, the above code looks like this:
362 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
365 /// The full set of provided functions includes:
367 /// mdconst::hasa <=> isa
368 /// mdconst::extract <=> cast
369 /// mdconst::extract_or_null <=> cast_or_null
370 /// mdconst::dyn_extract <=> dyn_cast
371 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
373 /// The target of the cast must be a subclass of \a Constant.
377 template <class T> T &make();
378 template <class T, class Result> struct HasDereference {
381 template <size_t N> struct SFINAE {};
383 template <class U, class V>
384 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
385 template <class U, class V> static No &hasDereference(...);
387 static const bool value =
388 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
390 template <class V, class M> struct IsValidPointer {
391 static const bool value = std::is_base_of<Constant, V>::value &&
392 HasDereference<M, const Metadata &>::value;
394 template <class V, class M> struct IsValidReference {
395 static const bool value = std::is_base_of<Constant, V>::value &&
396 std::is_convertible<M, const Metadata &>::value;
398 } // end namespace detail
400 /// \brief Check whether Metadata has a Value.
402 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
404 template <class X, class Y>
405 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
407 assert(MD && "Null pointer sent into hasa");
408 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
409 return isa<X>(V->getValue());
412 template <class X, class Y>
414 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
419 /// \brief Extract a Value from Metadata.
421 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
422 template <class X, class Y>
423 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
425 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
427 template <class X, class Y>
429 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
434 /// \brief Extract a Value from Metadata, allowing null.
436 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
437 /// from \c MD, allowing \c MD to be null.
438 template <class X, class Y>
439 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
440 extract_or_null(Y &&MD) {
441 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
442 return cast<X>(V->getValue());
446 /// \brief Extract a Value from Metadata, if any.
448 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
449 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
450 /// Value it does contain is of the wrong subclass.
451 template <class X, class Y>
452 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
453 dyn_extract(Y &&MD) {
454 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
455 return dyn_cast<X>(V->getValue());
459 /// \brief Extract a Value from Metadata, if any, allowing null.
461 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
462 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
463 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
464 template <class X, class Y>
465 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
466 dyn_extract_or_null(Y &&MD) {
467 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
468 return dyn_cast<X>(V->getValue());
472 } // end namespace mdconst
474 //===----------------------------------------------------------------------===//
475 /// \brief A single uniqued string.
477 /// These are used to efficiently contain a byte sequence for metadata.
478 /// MDString is always unnamed.
479 class MDString : public Metadata {
480 friend class StringMapEntry<MDString>;
482 MDString(const MDString &) = delete;
483 MDString &operator=(MDString &&) = delete;
484 MDString &operator=(const MDString &) = delete;
486 StringMapEntry<MDString> *Entry;
487 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
488 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
491 static MDString *get(LLVMContext &Context, StringRef Str);
492 static MDString *get(LLVMContext &Context, const char *Str) {
493 return get(Context, Str ? StringRef(Str) : StringRef());
496 StringRef getString() const;
498 unsigned getLength() const { return (unsigned)getString().size(); }
500 typedef StringRef::iterator iterator;
502 /// \brief Pointer to the first byte of the string.
503 iterator begin() const { return getString().begin(); }
505 /// \brief Pointer to one byte past the end of the string.
506 iterator end() const { return getString().end(); }
508 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
509 const unsigned char *bytes_end() const { return getString().bytes_end(); }
511 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
512 static bool classof(const Metadata *MD) {
513 return MD->getMetadataID() == MDStringKind;
517 /// \brief A collection of metadata nodes that might be associated with a
518 /// memory access used by the alias-analysis infrastructure.
520 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
522 : TBAA(T), Scope(S), NoAlias(N) {}
524 bool operator==(const AAMDNodes &A) const {
525 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
528 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
530 explicit operator bool() const { return TBAA || Scope || NoAlias; }
532 /// \brief The tag for type-based alias analysis.
535 /// \brief The tag for alias scope specification (used with noalias).
538 /// \brief The tag specifying the noalias scope.
542 // Specialize DenseMapInfo for AAMDNodes.
544 struct DenseMapInfo<AAMDNodes> {
545 static inline AAMDNodes getEmptyKey() {
546 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
548 static inline AAMDNodes getTombstoneKey() {
549 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
551 static unsigned getHashValue(const AAMDNodes &Val) {
552 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
553 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
554 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
556 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
561 /// \brief Tracking metadata reference owned by Metadata.
563 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
564 /// of \a Metadata, which has the option of registering itself for callbacks to
565 /// re-unique itself.
567 /// In particular, this is used by \a MDNode.
569 MDOperand(MDOperand &&) = delete;
570 MDOperand(const MDOperand &) = delete;
571 MDOperand &operator=(MDOperand &&) = delete;
572 MDOperand &operator=(const MDOperand &) = delete;
577 MDOperand() : MD(nullptr) {}
578 ~MDOperand() { untrack(); }
580 Metadata *get() const { return MD; }
581 operator Metadata *() const { return get(); }
582 Metadata *operator->() const { return get(); }
583 Metadata &operator*() const { return *get(); }
589 void reset(Metadata *MD, Metadata *Owner) {
596 void track(Metadata *Owner) {
599 MetadataTracking::track(this, *MD, *Owner);
601 MetadataTracking::track(MD);
605 assert(static_cast<void *>(this) == &MD && "Expected same address");
607 MetadataTracking::untrack(MD);
611 template <> struct simplify_type<MDOperand> {
612 typedef Metadata *SimpleType;
613 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
616 template <> struct simplify_type<const MDOperand> {
617 typedef Metadata *SimpleType;
618 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
621 /// \brief Pointer to the context, with optional RAUW support.
623 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
624 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
625 class ContextAndReplaceableUses {
626 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
628 ContextAndReplaceableUses() = delete;
629 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
630 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
631 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
632 ContextAndReplaceableUses &
633 operator=(const ContextAndReplaceableUses &) = delete;
636 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
637 ContextAndReplaceableUses(
638 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
639 : Ptr(ReplaceableUses.release()) {
640 assert(getReplaceableUses() && "Expected non-null replaceable uses");
642 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
644 operator LLVMContext &() { return getContext(); }
646 /// \brief Whether this contains RAUW support.
647 bool hasReplaceableUses() const {
648 return Ptr.is<ReplaceableMetadataImpl *>();
650 LLVMContext &getContext() const {
651 if (hasReplaceableUses())
652 return getReplaceableUses()->getContext();
653 return *Ptr.get<LLVMContext *>();
655 ReplaceableMetadataImpl *getReplaceableUses() const {
656 if (hasReplaceableUses())
657 return Ptr.get<ReplaceableMetadataImpl *>();
661 /// \brief Assign RAUW support to this.
663 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
666 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
667 assert(ReplaceableUses && "Expected non-null replaceable uses");
668 assert(&ReplaceableUses->getContext() == &getContext() &&
669 "Expected same context");
670 delete getReplaceableUses();
671 Ptr = ReplaceableUses.release();
674 /// \brief Drop RAUW support.
676 /// Cede ownership of RAUW support, returning it.
677 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
678 assert(hasReplaceableUses() && "Expected to own replaceable uses");
679 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
680 getReplaceableUses());
681 Ptr = &ReplaceableUses->getContext();
682 return ReplaceableUses;
686 struct TempMDNodeDeleter {
687 inline void operator()(MDNode *Node) const;
690 #define HANDLE_MDNODE_LEAF(CLASS) \
691 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
692 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
693 #include "llvm/IR/Metadata.def"
695 /// \brief Metadata node.
697 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
698 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
699 /// until forward references are known. The basic metadata node is an \a
702 /// There is limited support for RAUW at construction time. At construction
703 /// time, if any operand is a temporary node (or an unresolved uniqued node,
704 /// which indicates a transitive temporary operand), the node itself will be
705 /// unresolved. As soon as all operands become resolved, it will drop RAUW
706 /// support permanently.
708 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
709 /// to be called on some member of the cycle once all temporary nodes have been
711 class MDNode : public Metadata {
712 friend class ReplaceableMetadataImpl;
713 friend class LLVMContextImpl;
715 MDNode(const MDNode &) = delete;
716 void operator=(const MDNode &) = delete;
717 void *operator new(size_t) = delete;
719 unsigned NumOperands;
720 unsigned NumUnresolved;
723 ContextAndReplaceableUses Context;
725 void *operator new(size_t Size, unsigned NumOps);
726 void operator delete(void *Mem);
728 /// \brief Required by std, but never called.
729 void operator delete(void *, unsigned) {
730 llvm_unreachable("Constructor throws?");
733 /// \brief Required by std, but never called.
734 void operator delete(void *, unsigned, bool) {
735 llvm_unreachable("Constructor throws?");
738 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
739 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
742 void dropAllReferences();
744 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
745 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
748 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
749 static inline MDTuple *getIfExists(LLVMContext &Context,
750 ArrayRef<Metadata *> MDs);
751 static inline MDTuple *getDistinct(LLVMContext &Context,
752 ArrayRef<Metadata *> MDs);
753 static inline TempMDTuple getTemporary(LLVMContext &Context,
754 ArrayRef<Metadata *> MDs);
756 /// \brief Create a (temporary) clone of this.
757 TempMDNode clone() const;
759 /// \brief Deallocate a node created by getTemporary.
761 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
762 /// references will be reset.
763 static void deleteTemporary(MDNode *N);
765 LLVMContext &getContext() const { return Context.getContext(); }
767 /// \brief Replace a specific operand.
768 void replaceOperandWith(unsigned I, Metadata *New);
770 /// \brief Check if node is fully resolved.
772 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
773 /// this always returns \c true.
775 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
776 /// support (because all operands are resolved).
778 /// As forward declarations are resolved, their containers should get
779 /// resolved automatically. However, if this (or one of its operands) is
780 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
781 bool isResolved() const { return !Context.hasReplaceableUses(); }
783 bool isUniqued() const { return Storage == Uniqued; }
784 bool isDistinct() const { return Storage == Distinct; }
785 bool isTemporary() const { return Storage == Temporary; }
787 /// \brief RAUW a temporary.
789 /// \pre \a isTemporary() must be \c true.
790 void replaceAllUsesWith(Metadata *MD) {
791 assert(isTemporary() && "Expected temporary node");
792 assert(!isResolved() && "Expected RAUW support");
793 Context.getReplaceableUses()->replaceAllUsesWith(MD);
796 /// \brief Resolve cycles.
798 /// Once all forward declarations have been resolved, force cycles to be
801 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
802 void resolveCycles();
804 /// \brief Replace a temporary node with a permanent one.
806 /// Try to create a uniqued version of \c N -- in place, if possible -- and
807 /// return it. If \c N cannot be uniqued, return a distinct node instead.
809 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
810 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
811 return cast<T>(N.release()->replaceWithPermanentImpl());
814 /// \brief Replace a temporary node with a uniqued one.
816 /// Create a uniqued version of \c N -- in place, if possible -- and return
817 /// it. Takes ownership of the temporary node.
819 /// \pre N does not self-reference.
821 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
822 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
823 return cast<T>(N.release()->replaceWithUniquedImpl());
826 /// \brief Replace a temporary node with a distinct one.
828 /// Create a distinct version of \c N -- in place, if possible -- and return
829 /// it. Takes ownership of the temporary node.
831 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
832 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
833 return cast<T>(N.release()->replaceWithDistinctImpl());
837 MDNode *replaceWithPermanentImpl();
838 MDNode *replaceWithUniquedImpl();
839 MDNode *replaceWithDistinctImpl();
842 /// \brief Set an operand.
844 /// Sets the operand directly, without worrying about uniquing.
845 void setOperand(unsigned I, Metadata *New);
847 void storeDistinctInContext();
848 template <class T, class StoreT>
849 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
852 void handleChangedOperand(void *Ref, Metadata *New);
855 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
856 void decrementUnresolvedOperandCount();
857 unsigned countUnresolvedOperands();
859 /// \brief Mutate this to be "uniqued".
861 /// Mutate this so that \a isUniqued().
862 /// \pre \a isTemporary().
863 /// \pre already added to uniquing set.
866 /// \brief Mutate this to be "distinct".
868 /// Mutate this so that \a isDistinct().
869 /// \pre \a isTemporary().
872 void deleteAsSubclass();
874 void eraseFromStore();
876 template <class NodeTy> struct HasCachedHash;
877 template <class NodeTy>
878 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
879 N->recalculateHash();
881 template <class NodeTy>
882 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
883 template <class NodeTy>
884 static void dispatchResetHash(NodeTy *N, std::true_type) {
887 template <class NodeTy>
888 static void dispatchResetHash(NodeTy *N, std::false_type) {}
891 typedef const MDOperand *op_iterator;
892 typedef iterator_range<op_iterator> op_range;
894 op_iterator op_begin() const {
895 return const_cast<MDNode *>(this)->mutable_begin();
897 op_iterator op_end() const {
898 return const_cast<MDNode *>(this)->mutable_end();
900 op_range operands() const { return op_range(op_begin(), op_end()); }
902 const MDOperand &getOperand(unsigned I) const {
903 assert(I < NumOperands && "Out of range");
904 return op_begin()[I];
907 /// \brief Return number of MDNode operands.
908 unsigned getNumOperands() const { return NumOperands; }
910 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
911 static bool classof(const Metadata *MD) {
912 switch (MD->getMetadataID()) {
915 #define HANDLE_MDNODE_LEAF(CLASS) \
918 #include "llvm/IR/Metadata.def"
922 /// \brief Check whether MDNode is a vtable access.
923 bool isTBAAVtableAccess() const;
925 /// \brief Methods for metadata merging.
926 static MDNode *concatenate(MDNode *A, MDNode *B);
927 static MDNode *intersect(MDNode *A, MDNode *B);
928 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
929 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
930 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
931 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
934 /// \brief Tuple of metadata.
936 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
937 /// default based on their operands.
938 class MDTuple : public MDNode {
939 friend class LLVMContextImpl;
942 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
943 ArrayRef<Metadata *> Vals)
944 : MDNode(C, MDTupleKind, Storage, Vals) {
947 ~MDTuple() { dropAllReferences(); }
949 void setHash(unsigned Hash) { SubclassData32 = Hash; }
950 void recalculateHash();
952 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
953 StorageType Storage, bool ShouldCreate = true);
955 TempMDTuple cloneImpl() const {
956 return getTemporary(getContext(),
957 SmallVector<Metadata *, 4>(op_begin(), op_end()));
961 /// \brief Get the hash, if any.
962 unsigned getHash() const { return SubclassData32; }
964 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
965 return getImpl(Context, MDs, Uniqued);
967 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
968 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
971 /// \brief Return a distinct node.
973 /// Return a distinct node -- i.e., a node that is not uniqued.
974 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
975 return getImpl(Context, MDs, Distinct);
978 /// \brief Return a temporary node.
980 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
981 /// not uniqued, may be RAUW'd, and must be manually deleted with
983 static TempMDTuple getTemporary(LLVMContext &Context,
984 ArrayRef<Metadata *> MDs) {
985 return TempMDTuple(getImpl(Context, MDs, Temporary));
988 /// \brief Return a (temporary) clone of this.
989 TempMDTuple clone() const { return cloneImpl(); }
991 static bool classof(const Metadata *MD) {
992 return MD->getMetadataID() == MDTupleKind;
996 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
997 return MDTuple::get(Context, MDs);
999 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1000 return MDTuple::getIfExists(Context, MDs);
1002 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1003 return MDTuple::getDistinct(Context, MDs);
1005 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1006 ArrayRef<Metadata *> MDs) {
1007 return MDTuple::getTemporary(Context, MDs);
1010 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1011 MDNode::deleteTemporary(Node);
1014 //===----------------------------------------------------------------------===//
1015 /// \brief A tuple of MDNodes.
1017 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1018 /// to modules, have names, and contain lists of MDNodes.
1020 /// TODO: Inherit from Metadata.
1021 class NamedMDNode : public ilist_node<NamedMDNode> {
1022 friend class SymbolTableListTraits<NamedMDNode, Module>;
1023 friend struct ilist_traits<NamedMDNode>;
1024 friend class LLVMContextImpl;
1025 friend class Module;
1026 NamedMDNode(const NamedMDNode &) = delete;
1030 void *Operands; // SmallVector<TrackingMDRef, 4>
1032 void setParent(Module *M) { Parent = M; }
1034 explicit NamedMDNode(const Twine &N);
1036 template<class T1, class T2>
1037 class op_iterator_impl :
1038 public std::iterator<std::bidirectional_iterator_tag, T2> {
1039 const NamedMDNode *Node;
1041 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1043 friend class NamedMDNode;
1046 op_iterator_impl() : Node(nullptr), Idx(0) { }
1048 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1049 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1050 op_iterator_impl &operator++() {
1054 op_iterator_impl operator++(int) {
1055 op_iterator_impl tmp(*this);
1059 op_iterator_impl &operator--() {
1063 op_iterator_impl operator--(int) {
1064 op_iterator_impl tmp(*this);
1069 T1 operator*() const { return Node->getOperand(Idx); }
1073 /// \brief Drop all references and remove the node from parent module.
1074 void eraseFromParent();
1076 /// \brief Remove all uses and clear node vector.
1077 void dropAllReferences();
1081 /// \brief Get the module that holds this named metadata collection.
1082 inline Module *getParent() { return Parent; }
1083 inline const Module *getParent() const { return Parent; }
1085 MDNode *getOperand(unsigned i) const;
1086 unsigned getNumOperands() const;
1087 void addOperand(MDNode *M);
1088 void setOperand(unsigned I, MDNode *New);
1089 StringRef getName() const;
1090 void print(raw_ostream &ROS) const;
1093 // ---------------------------------------------------------------------------
1094 // Operand Iterator interface...
1096 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1097 op_iterator op_begin() { return op_iterator(this, 0); }
1098 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1100 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1101 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1102 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1104 inline iterator_range<op_iterator> operands() {
1105 return iterator_range<op_iterator>(op_begin(), op_end());
1107 inline iterator_range<const_op_iterator> operands() const {
1108 return iterator_range<const_op_iterator>(op_begin(), op_end());
1112 } // end llvm namespace