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;
36 enum LLVMConstants : uint32_t {
37 DEBUG_METADATA_VERSION = 2 // Current debug info version number.
40 /// \brief Root of the metadata hierarchy.
42 /// This is a root class for typeless data in the IR.
44 friend class ReplaceableMetadataImpl;
47 const unsigned char SubclassID;
50 /// \brief Active type of storage.
51 enum StorageType { Uniqued, Distinct, Temporary };
53 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
55 // TODO: expose remaining bits to subclasses.
57 unsigned short SubclassData16;
58 unsigned SubclassData32;
75 MDLexicalBlockFileKind,
77 MDTemplateTypeParameterKind,
78 MDTemplateValueParameterKind,
84 ConstantAsMetadataKind,
90 Metadata(unsigned ID, StorageType Storage)
91 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
95 /// \brief Default handling of a changed operand, which asserts.
97 /// If subclasses pass themselves in as owners to a tracking node reference,
98 /// they must provide an implementation of this method.
99 void handleChangedOperand(void *, Metadata *) {
100 llvm_unreachable("Unimplemented in Metadata subclass");
104 unsigned getMetadataID() const { return SubclassID; }
106 /// \brief User-friendly dump.
108 void print(raw_ostream &OS) const;
109 void printAsOperand(raw_ostream &OS, bool PrintType = true,
110 const Module *M = nullptr) const;
113 #define HANDLE_METADATA(CLASS) class CLASS;
114 #include "llvm/IR/Metadata.def"
116 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
121 /// \brief Metadata wrapper in the Value hierarchy.
123 /// A member of the \a Value hierarchy to represent a reference to metadata.
124 /// This allows, e.g., instrinsics to have metadata as operands.
126 /// Notably, this is the only thing in either hierarchy that is allowed to
127 /// reference \a LocalAsMetadata.
128 class MetadataAsValue : public Value {
129 friend class ReplaceableMetadataImpl;
130 friend class LLVMContextImpl;
134 MetadataAsValue(Type *Ty, Metadata *MD);
137 /// \brief Drop use of metadata (during teardown).
138 void dropUse() { MD = nullptr; }
141 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
142 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
143 Metadata *getMetadata() const { return MD; }
145 static bool classof(const Value *V) {
146 return V->getValueID() == MetadataAsValueVal;
150 void handleChangedMetadata(Metadata *MD);
155 /// \brief Shared implementation of use-lists for replaceable metadata.
157 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
158 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
159 /// and \a TempMDNode).
160 class ReplaceableMetadataImpl {
161 friend class MetadataTracking;
164 typedef MetadataTracking::OwnerTy OwnerTy;
167 LLVMContext &Context;
169 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
172 ReplaceableMetadataImpl(LLVMContext &Context)
173 : Context(Context), NextIndex(0) {}
174 ~ReplaceableMetadataImpl() {
175 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
178 LLVMContext &getContext() const { return Context; }
180 /// \brief Replace all uses of this with MD.
182 /// Replace all uses of this with \c MD, which is allowed to be null.
183 void replaceAllUsesWith(Metadata *MD);
185 /// \brief Resolve all uses of this.
187 /// Resolve all uses of this, turning off RAUW permanently. If \c
188 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
190 void resolveAllUses(bool ResolveUsers = true);
193 void addRef(void *Ref, OwnerTy Owner);
194 void dropRef(void *Ref);
195 void moveRef(void *Ref, void *New, const Metadata &MD);
197 static ReplaceableMetadataImpl *get(Metadata &MD);
200 /// \brief Value wrapper in the Metadata hierarchy.
202 /// This is a custom value handle that allows other metadata to refer to
203 /// classes in the Value hierarchy.
205 /// Because of full uniquing support, each value is only wrapped by a single \a
206 /// ValueAsMetadata object, so the lookup maps are far more efficient than
207 /// those using ValueHandleBase.
208 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
209 friend class ReplaceableMetadataImpl;
210 friend class LLVMContextImpl;
214 /// \brief Drop users without RAUW (during teardown).
216 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
220 ValueAsMetadata(unsigned ID, Value *V)
221 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
222 assert(V && "Expected valid value");
224 ~ValueAsMetadata() {}
227 static ValueAsMetadata *get(Value *V);
228 static ConstantAsMetadata *getConstant(Value *C) {
229 return cast<ConstantAsMetadata>(get(C));
231 static LocalAsMetadata *getLocal(Value *Local) {
232 return cast<LocalAsMetadata>(get(Local));
235 static ValueAsMetadata *getIfExists(Value *V);
236 static ConstantAsMetadata *getConstantIfExists(Value *C) {
237 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
239 static LocalAsMetadata *getLocalIfExists(Value *Local) {
240 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
243 Value *getValue() const { return V; }
244 Type *getType() const { return V->getType(); }
245 LLVMContext &getContext() const { return V->getContext(); }
247 static void handleDeletion(Value *V);
248 static void handleRAUW(Value *From, Value *To);
251 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
253 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
254 /// \a Value gets RAUW'ed and the target already exists, this is used to
255 /// merge the two metadata nodes.
256 void replaceAllUsesWith(Metadata *MD) {
257 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
261 static bool classof(const Metadata *MD) {
262 return MD->getMetadataID() == LocalAsMetadataKind ||
263 MD->getMetadataID() == ConstantAsMetadataKind;
267 class ConstantAsMetadata : public ValueAsMetadata {
268 friend class ValueAsMetadata;
270 ConstantAsMetadata(Constant *C)
271 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
274 static ConstantAsMetadata *get(Constant *C) {
275 return ValueAsMetadata::getConstant(C);
277 static ConstantAsMetadata *getIfExists(Constant *C) {
278 return ValueAsMetadata::getConstantIfExists(C);
281 Constant *getValue() const {
282 return cast<Constant>(ValueAsMetadata::getValue());
285 static bool classof(const Metadata *MD) {
286 return MD->getMetadataID() == ConstantAsMetadataKind;
290 class LocalAsMetadata : public ValueAsMetadata {
291 friend class ValueAsMetadata;
293 LocalAsMetadata(Value *Local)
294 : ValueAsMetadata(LocalAsMetadataKind, Local) {
295 assert(!isa<Constant>(Local) && "Expected local value");
299 static LocalAsMetadata *get(Value *Local) {
300 return ValueAsMetadata::getLocal(Local);
302 static LocalAsMetadata *getIfExists(Value *Local) {
303 return ValueAsMetadata::getLocalIfExists(Local);
306 static bool classof(const Metadata *MD) {
307 return MD->getMetadataID() == LocalAsMetadataKind;
311 /// \brief Transitional API for extracting constants from Metadata.
313 /// This namespace contains transitional functions for metadata that points to
316 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
317 /// operands could refer to any \a Value. There's was a lot of code like this:
321 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
324 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
325 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
326 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
327 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
328 /// requires subtle control flow changes.
330 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
331 /// so that metadata can refer to numbers without traversing a bridge to the \a
332 /// Value hierarchy. In this final state, the code above would look like this:
336 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
339 /// The API in this namespace supports the transition. \a MDInt doesn't exist
340 /// yet, and even once it does, changing each metadata schema to use it is its
341 /// own mini-project. In the meantime this API prevents us from introducing
342 /// complex and bug-prone control flow that will disappear in the end. In
343 /// particular, the above code looks like this:
347 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
350 /// The full set of provided functions includes:
352 /// mdconst::hasa <=> isa
353 /// mdconst::extract <=> cast
354 /// mdconst::extract_or_null <=> cast_or_null
355 /// mdconst::dyn_extract <=> dyn_cast
356 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
358 /// The target of the cast must be a subclass of \a Constant.
362 template <class T> T &make();
363 template <class T, class Result> struct HasDereference {
366 template <size_t N> struct SFINAE {};
368 template <class U, class V>
369 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
370 template <class U, class V> static No &hasDereference(...);
372 static const bool value =
373 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
375 template <class V, class M> struct IsValidPointer {
376 static const bool value = std::is_base_of<Constant, V>::value &&
377 HasDereference<M, const Metadata &>::value;
379 template <class V, class M> struct IsValidReference {
380 static const bool value = std::is_base_of<Constant, V>::value &&
381 std::is_convertible<M, const Metadata &>::value;
383 } // end namespace detail
385 /// \brief Check whether Metadata has a Value.
387 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
389 template <class X, class Y>
390 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
392 assert(MD && "Null pointer sent into hasa");
393 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
394 return isa<X>(V->getValue());
397 template <class X, class Y>
399 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
404 /// \brief Extract a Value from Metadata.
406 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
407 template <class X, class Y>
408 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
410 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
412 template <class X, class Y>
414 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
419 /// \brief Extract a Value from Metadata, allowing null.
421 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
422 /// from \c MD, allowing \c MD to be null.
423 template <class X, class Y>
424 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
425 extract_or_null(Y &&MD) {
426 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
427 return cast<X>(V->getValue());
431 /// \brief Extract a Value from Metadata, if any.
433 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
434 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
435 /// Value it does contain is of the wrong subclass.
436 template <class X, class Y>
437 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
438 dyn_extract(Y &&MD) {
439 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
440 return dyn_cast<X>(V->getValue());
444 /// \brief Extract a Value from Metadata, if any, allowing null.
446 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
447 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
448 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
449 template <class X, class Y>
450 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
451 dyn_extract_or_null(Y &&MD) {
452 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
453 return dyn_cast<X>(V->getValue());
457 } // end namespace mdconst
459 //===----------------------------------------------------------------------===//
460 /// \brief A single uniqued string.
462 /// These are used to efficiently contain a byte sequence for metadata.
463 /// MDString is always unnamed.
464 class MDString : public Metadata {
465 friend class StringMapEntry<MDString>;
467 MDString(const MDString &) LLVM_DELETED_FUNCTION;
468 MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
469 MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
471 StringMapEntry<MDString> *Entry;
472 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
473 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
476 static MDString *get(LLVMContext &Context, StringRef Str);
477 static MDString *get(LLVMContext &Context, const char *Str) {
478 return get(Context, Str ? StringRef(Str) : StringRef());
481 StringRef getString() const;
483 unsigned getLength() const { return (unsigned)getString().size(); }
485 typedef StringRef::iterator iterator;
487 /// \brief Pointer to the first byte of the string.
488 iterator begin() const { return getString().begin(); }
490 /// \brief Pointer to one byte past the end of the string.
491 iterator end() const { return getString().end(); }
493 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
494 const unsigned char *bytes_end() const { return getString().bytes_end(); }
496 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
497 static bool classof(const Metadata *MD) {
498 return MD->getMetadataID() == MDStringKind;
502 /// \brief A collection of metadata nodes that might be associated with a
503 /// memory access used by the alias-analysis infrastructure.
505 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
507 : TBAA(T), Scope(S), NoAlias(N) {}
509 bool operator==(const AAMDNodes &A) const {
510 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
513 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
515 LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
517 /// \brief The tag for type-based alias analysis.
520 /// \brief The tag for alias scope specification (used with noalias).
523 /// \brief The tag specifying the noalias scope.
527 // Specialize DenseMapInfo for AAMDNodes.
529 struct DenseMapInfo<AAMDNodes> {
530 static inline AAMDNodes getEmptyKey() {
531 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
533 static inline AAMDNodes getTombstoneKey() {
534 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
536 static unsigned getHashValue(const AAMDNodes &Val) {
537 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
538 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
539 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
541 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
546 /// \brief Tracking metadata reference owned by Metadata.
548 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
549 /// of \a Metadata, which has the option of registering itself for callbacks to
550 /// re-unique itself.
552 /// In particular, this is used by \a MDNode.
554 MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
555 MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
556 MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
557 MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
562 MDOperand() : MD(nullptr) {}
563 ~MDOperand() { untrack(); }
565 Metadata *get() const { return MD; }
566 operator Metadata *() const { return get(); }
567 Metadata *operator->() const { return get(); }
568 Metadata &operator*() const { return *get(); }
574 void reset(Metadata *MD, Metadata *Owner) {
581 void track(Metadata *Owner) {
584 MetadataTracking::track(this, *MD, *Owner);
586 MetadataTracking::track(MD);
590 assert(static_cast<void *>(this) == &MD && "Expected same address");
592 MetadataTracking::untrack(MD);
596 template <> struct simplify_type<MDOperand> {
597 typedef Metadata *SimpleType;
598 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
601 template <> struct simplify_type<const MDOperand> {
602 typedef Metadata *SimpleType;
603 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
606 /// \brief Pointer to the context, with optional RAUW support.
608 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
609 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
610 class ContextAndReplaceableUses {
611 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
613 ContextAndReplaceableUses() LLVM_DELETED_FUNCTION;
614 ContextAndReplaceableUses(ContextAndReplaceableUses &&)
615 LLVM_DELETED_FUNCTION;
616 ContextAndReplaceableUses(const ContextAndReplaceableUses &)
617 LLVM_DELETED_FUNCTION;
618 ContextAndReplaceableUses &
619 operator=(ContextAndReplaceableUses &&) LLVM_DELETED_FUNCTION;
620 ContextAndReplaceableUses &
621 operator=(const ContextAndReplaceableUses &) LLVM_DELETED_FUNCTION;
624 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
625 ContextAndReplaceableUses(
626 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
627 : Ptr(ReplaceableUses.release()) {
628 assert(getReplaceableUses() && "Expected non-null replaceable uses");
630 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
632 operator LLVMContext &() { return getContext(); }
634 /// \brief Whether this contains RAUW support.
635 bool hasReplaceableUses() const {
636 return Ptr.is<ReplaceableMetadataImpl *>();
638 LLVMContext &getContext() const {
639 if (hasReplaceableUses())
640 return getReplaceableUses()->getContext();
641 return *Ptr.get<LLVMContext *>();
643 ReplaceableMetadataImpl *getReplaceableUses() const {
644 if (hasReplaceableUses())
645 return Ptr.get<ReplaceableMetadataImpl *>();
649 /// \brief Assign RAUW support to this.
651 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
654 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
655 assert(ReplaceableUses && "Expected non-null replaceable uses");
656 assert(&ReplaceableUses->getContext() == &getContext() &&
657 "Expected same context");
658 delete getReplaceableUses();
659 Ptr = ReplaceableUses.release();
662 /// \brief Drop RAUW support.
664 /// Cede ownership of RAUW support, returning it.
665 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
666 assert(hasReplaceableUses() && "Expected to own replaceable uses");
667 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
668 getReplaceableUses());
669 Ptr = &ReplaceableUses->getContext();
670 return ReplaceableUses;
674 struct TempMDNodeDeleter {
675 inline void operator()(MDNode *Node) const;
678 #define HANDLE_MDNODE_LEAF(CLASS) \
679 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
680 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
681 #include "llvm/IR/Metadata.def"
683 /// \brief Metadata node.
685 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
686 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
687 /// until forward references are known. The basic metadata node is an \a
690 /// There is limited support for RAUW at construction time. At construction
691 /// time, if any operand is a temporary node (or an unresolved uniqued node,
692 /// which indicates a transitive temporary operand), the node itself will be
693 /// unresolved. As soon as all operands become resolved, it will drop RAUW
694 /// support permanently.
696 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
697 /// to be called on some member of the cycle once all temporary nodes have been
699 class MDNode : public Metadata {
700 friend class ReplaceableMetadataImpl;
701 friend class LLVMContextImpl;
703 MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
704 void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
705 void *operator new(size_t) LLVM_DELETED_FUNCTION;
707 unsigned NumOperands;
708 unsigned NumUnresolved;
711 ContextAndReplaceableUses Context;
713 void *operator new(size_t Size, unsigned NumOps);
714 void operator delete(void *Mem);
716 /// \brief Required by std, but never called.
717 void operator delete(void *, unsigned) {
718 llvm_unreachable("Constructor throws?");
721 /// \brief Required by std, but never called.
722 void operator delete(void *, unsigned, bool) {
723 llvm_unreachable("Constructor throws?");
726 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
727 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
730 void dropAllReferences();
732 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
733 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
736 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
737 static inline MDTuple *getIfExists(LLVMContext &Context,
738 ArrayRef<Metadata *> MDs);
739 static inline MDTuple *getDistinct(LLVMContext &Context,
740 ArrayRef<Metadata *> MDs);
741 static inline TempMDTuple getTemporary(LLVMContext &Context,
742 ArrayRef<Metadata *> MDs);
744 /// \brief Create a (temporary) clone of this.
745 TempMDNode clone() const;
747 /// \brief Deallocate a node created by getTemporary.
749 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
750 /// references will be reset.
751 static void deleteTemporary(MDNode *N);
753 LLVMContext &getContext() const { return Context.getContext(); }
755 /// \brief Replace a specific operand.
756 void replaceOperandWith(unsigned I, Metadata *New);
758 /// \brief Check if node is fully resolved.
760 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
761 /// this always returns \c true.
763 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
764 /// support (because all operands are resolved).
766 /// As forward declarations are resolved, their containers should get
767 /// resolved automatically. However, if this (or one of its operands) is
768 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
769 bool isResolved() const { return !Context.hasReplaceableUses(); }
771 bool isUniqued() const { return Storage == Uniqued; }
772 bool isDistinct() const { return Storage == Distinct; }
773 bool isTemporary() const { return Storage == Temporary; }
775 /// \brief RAUW a temporary.
777 /// \pre \a isTemporary() must be \c true.
778 void replaceAllUsesWith(Metadata *MD) {
779 assert(isTemporary() && "Expected temporary node");
780 assert(!isResolved() && "Expected RAUW support");
781 Context.getReplaceableUses()->replaceAllUsesWith(MD);
784 /// \brief Resolve cycles.
786 /// Once all forward declarations have been resolved, force cycles to be
789 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
790 void resolveCycles();
792 /// \brief Replace a temporary node with a uniqued one.
794 /// Create a uniqued version of \c N -- in place, if possible -- and return
795 /// it. Takes ownership of the temporary node.
797 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
798 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
799 return cast<T>(N.release()->replaceWithUniquedImpl());
802 /// \brief Replace a temporary node with a distinct one.
804 /// Create a distinct version of \c N -- in place, if possible -- and return
805 /// it. Takes ownership of the temporary node.
807 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
808 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
809 return cast<T>(N.release()->replaceWithDistinctImpl());
813 MDNode *replaceWithUniquedImpl();
814 MDNode *replaceWithDistinctImpl();
817 /// \brief Set an operand.
819 /// Sets the operand directly, without worrying about uniquing.
820 void setOperand(unsigned I, Metadata *New);
822 void storeDistinctInContext();
823 template <class T, class StoreT>
824 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
827 void handleChangedOperand(void *Ref, Metadata *New);
830 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
831 void decrementUnresolvedOperandCount();
832 unsigned countUnresolvedOperands();
834 /// \brief Mutate this to be "uniqued".
836 /// Mutate this so that \a isUniqued().
837 /// \pre \a isTemporary().
838 /// \pre already added to uniquing set.
841 /// \brief Mutate this to be "distinct".
843 /// Mutate this so that \a isDistinct().
844 /// \pre \a isTemporary().
847 void deleteAsSubclass();
849 void eraseFromStore();
851 template <class NodeTy> struct HasCachedHash;
852 template <class NodeTy>
853 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
854 N->recalculateHash();
856 template <class NodeTy>
857 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
858 template <class NodeTy>
859 static void dispatchResetHash(NodeTy *N, std::true_type) {
862 template <class NodeTy>
863 static void dispatchResetHash(NodeTy *N, std::false_type) {}
866 typedef const MDOperand *op_iterator;
867 typedef iterator_range<op_iterator> op_range;
869 op_iterator op_begin() const {
870 return const_cast<MDNode *>(this)->mutable_begin();
872 op_iterator op_end() const {
873 return const_cast<MDNode *>(this)->mutable_end();
875 op_range operands() const { return op_range(op_begin(), op_end()); }
877 const MDOperand &getOperand(unsigned I) const {
878 assert(I < NumOperands && "Out of range");
879 return op_begin()[I];
882 /// \brief Return number of MDNode operands.
883 unsigned getNumOperands() const { return NumOperands; }
885 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
886 static bool classof(const Metadata *MD) {
887 switch (MD->getMetadataID()) {
890 #define HANDLE_MDNODE_LEAF(CLASS) \
893 #include "llvm/IR/Metadata.def"
897 /// \brief Check whether MDNode is a vtable access.
898 bool isTBAAVtableAccess() const;
900 /// \brief Methods for metadata merging.
901 static MDNode *concatenate(MDNode *A, MDNode *B);
902 static MDNode *intersect(MDNode *A, MDNode *B);
903 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
904 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
905 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
906 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
909 /// \brief Tuple of metadata.
911 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
912 /// default based on their operands.
913 class MDTuple : public MDNode {
914 friend class LLVMContextImpl;
917 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
918 ArrayRef<Metadata *> Vals)
919 : MDNode(C, MDTupleKind, Storage, Vals) {
922 ~MDTuple() { dropAllReferences(); }
924 void setHash(unsigned Hash) { SubclassData32 = Hash; }
925 void recalculateHash();
927 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
928 StorageType Storage, bool ShouldCreate = true);
930 TempMDTuple cloneImpl() const {
931 return getTemporary(getContext(),
932 SmallVector<Metadata *, 4>(op_begin(), op_end()));
936 /// \brief Get the hash, if any.
937 unsigned getHash() const { return SubclassData32; }
939 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
940 return getImpl(Context, MDs, Uniqued);
942 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
943 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
946 /// \brief Return a distinct node.
948 /// Return a distinct node -- i.e., a node that is not uniqued.
949 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
950 return getImpl(Context, MDs, Distinct);
953 /// \brief Return a temporary node.
955 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
956 /// not uniqued, may be RAUW'd, and must be manually deleted with
958 static TempMDTuple getTemporary(LLVMContext &Context,
959 ArrayRef<Metadata *> MDs) {
960 return TempMDTuple(getImpl(Context, MDs, Temporary));
963 /// \brief Return a (temporary) clone of this.
964 TempMDTuple clone() const { return cloneImpl(); }
966 static bool classof(const Metadata *MD) {
967 return MD->getMetadataID() == MDTupleKind;
971 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
972 return MDTuple::get(Context, MDs);
974 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
975 return MDTuple::getIfExists(Context, MDs);
977 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
978 return MDTuple::getDistinct(Context, MDs);
980 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
981 ArrayRef<Metadata *> MDs) {
982 return MDTuple::getTemporary(Context, MDs);
985 void TempMDNodeDeleter::operator()(MDNode *Node) const {
986 MDNode::deleteTemporary(Node);
989 //===----------------------------------------------------------------------===//
990 /// \brief A tuple of MDNodes.
992 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
993 /// to modules, have names, and contain lists of MDNodes.
995 /// TODO: Inherit from Metadata.
996 class NamedMDNode : public ilist_node<NamedMDNode> {
997 friend class SymbolTableListTraits<NamedMDNode, Module>;
998 friend struct ilist_traits<NamedMDNode>;
999 friend class LLVMContextImpl;
1000 friend class Module;
1001 NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
1005 void *Operands; // SmallVector<TrackingMDRef, 4>
1007 void setParent(Module *M) { Parent = M; }
1009 explicit NamedMDNode(const Twine &N);
1011 template<class T1, class T2>
1012 class op_iterator_impl :
1013 public std::iterator<std::bidirectional_iterator_tag, T2> {
1014 const NamedMDNode *Node;
1016 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1018 friend class NamedMDNode;
1021 op_iterator_impl() : Node(nullptr), Idx(0) { }
1023 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1024 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1025 op_iterator_impl &operator++() {
1029 op_iterator_impl operator++(int) {
1030 op_iterator_impl tmp(*this);
1034 op_iterator_impl &operator--() {
1038 op_iterator_impl operator--(int) {
1039 op_iterator_impl tmp(*this);
1044 T1 operator*() const { return Node->getOperand(Idx); }
1048 /// \brief Drop all references and remove the node from parent module.
1049 void eraseFromParent();
1051 /// \brief Remove all uses and clear node vector.
1052 void dropAllReferences();
1056 /// \brief Get the module that holds this named metadata collection.
1057 inline Module *getParent() { return Parent; }
1058 inline const Module *getParent() const { return Parent; }
1060 MDNode *getOperand(unsigned i) const;
1061 unsigned getNumOperands() const;
1062 void addOperand(MDNode *M);
1063 void setOperand(unsigned I, MDNode *New);
1064 StringRef getName() const;
1065 void print(raw_ostream &ROS) const;
1068 // ---------------------------------------------------------------------------
1069 // Operand Iterator interface...
1071 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1072 op_iterator op_begin() { return op_iterator(this, 0); }
1073 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1075 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1076 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1077 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1079 inline iterator_range<op_iterator> operands() {
1080 return iterator_range<op_iterator>(op_begin(), op_end());
1082 inline iterator_range<const_op_iterator> operands() const {
1083 return iterator_range<const_op_iterator>(op_begin(), op_end());
1087 } // end llvm namespace