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>
33 class ModuleSlotTracker;
35 template<typename ValueSubClass, typename ItemParentClass>
36 class SymbolTableListTraits;
38 enum LLVMConstants : uint32_t {
39 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
42 /// \brief Root of the metadata hierarchy.
44 /// This is a root class for typeless data in the IR.
46 friend class ReplaceableMetadataImpl;
49 const unsigned char SubclassID;
52 /// \brief Active type of storage.
53 enum StorageType { Uniqued, Distinct, Temporary };
55 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
57 // TODO: expose remaining bits to subclasses.
59 unsigned short SubclassData16;
60 unsigned SubclassData32;
77 DILexicalBlockFileKind,
80 DITemplateTypeParameterKind,
81 DITemplateValueParameterKind,
87 ConstantAsMetadataKind,
93 Metadata(unsigned ID, StorageType Storage)
94 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
96 ~Metadata() = default;
98 /// \brief Default handling of a changed operand, which asserts.
100 /// If subclasses pass themselves in as owners to a tracking node reference,
101 /// they must provide an implementation of this method.
102 void handleChangedOperand(void *, Metadata *) {
103 llvm_unreachable("Unimplemented in Metadata subclass");
107 unsigned getMetadataID() const { return SubclassID; }
109 /// \brief User-friendly dump.
111 /// If \c M is provided, metadata nodes will be numbered canonically;
112 /// otherwise, pointer addresses are substituted.
114 /// Note: this uses an explicit overload instead of default arguments so that
115 /// the nullptr version is easy to call from a debugger.
119 void dump(const Module *M) const;
124 /// Prints definition of \c this.
126 /// If \c M is provided, metadata nodes will be numbered canonically;
127 /// otherwise, pointer addresses are substituted.
129 void print(raw_ostream &OS, const Module *M = nullptr,
130 bool IsForDebug = false) const;
131 void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
132 bool IsForDebug = false) const;
135 /// \brief Print as operand.
137 /// Prints reference of \c this.
139 /// If \c M is provided, metadata nodes will be numbered canonically;
140 /// otherwise, pointer addresses are substituted.
142 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
143 void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
144 const Module *M = nullptr) const;
148 #define HANDLE_METADATA(CLASS) class CLASS;
149 #include "llvm/IR/Metadata.def"
151 // Provide specializations of isa so that we don't need definitions of
152 // subclasses to see if the metadata is a subclass.
153 #define HANDLE_METADATA_LEAF(CLASS) \
154 template <> struct isa_impl<CLASS, Metadata> { \
155 static inline bool doit(const Metadata &MD) { \
156 return MD.getMetadataID() == Metadata::CLASS##Kind; \
159 #include "llvm/IR/Metadata.def"
161 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
166 /// \brief Metadata wrapper in the Value hierarchy.
168 /// A member of the \a Value hierarchy to represent a reference to metadata.
169 /// This allows, e.g., instrinsics to have metadata as operands.
171 /// Notably, this is the only thing in either hierarchy that is allowed to
172 /// reference \a LocalAsMetadata.
173 class MetadataAsValue : public Value {
174 friend class ReplaceableMetadataImpl;
175 friend class LLVMContextImpl;
179 MetadataAsValue(Type *Ty, Metadata *MD);
180 ~MetadataAsValue() override;
182 /// \brief Drop use of metadata (during teardown).
183 void dropUse() { MD = nullptr; }
186 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
187 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
188 Metadata *getMetadata() const { return MD; }
190 static bool classof(const Value *V) {
191 return V->getValueID() == MetadataAsValueVal;
195 void handleChangedMetadata(Metadata *MD);
200 /// \brief Shared implementation of use-lists for replaceable metadata.
202 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
203 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
204 /// and \a TempMDNode).
205 class ReplaceableMetadataImpl {
206 friend class MetadataTracking;
209 typedef MetadataTracking::OwnerTy OwnerTy;
212 LLVMContext &Context;
214 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
217 ReplaceableMetadataImpl(LLVMContext &Context)
218 : Context(Context), NextIndex(0) {}
219 ~ReplaceableMetadataImpl() {
220 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
223 LLVMContext &getContext() const { return Context; }
225 /// \brief Replace all uses of this with MD.
227 /// Replace all uses of this with \c MD, which is allowed to be null.
228 void replaceAllUsesWith(Metadata *MD);
230 /// \brief Resolve all uses of this.
232 /// Resolve all uses of this, turning off RAUW permanently. If \c
233 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
235 void resolveAllUses(bool ResolveUsers = true);
238 void addRef(void *Ref, OwnerTy Owner);
239 void dropRef(void *Ref);
240 void moveRef(void *Ref, void *New, const Metadata &MD);
242 static ReplaceableMetadataImpl *get(Metadata &MD);
245 /// \brief Value wrapper in the Metadata hierarchy.
247 /// This is a custom value handle that allows other metadata to refer to
248 /// classes in the Value hierarchy.
250 /// Because of full uniquing support, each value is only wrapped by a single \a
251 /// ValueAsMetadata object, so the lookup maps are far more efficient than
252 /// those using ValueHandleBase.
253 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
254 friend class ReplaceableMetadataImpl;
255 friend class LLVMContextImpl;
259 /// \brief Drop users without RAUW (during teardown).
261 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
265 ValueAsMetadata(unsigned ID, Value *V)
266 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
267 assert(V && "Expected valid value");
269 ~ValueAsMetadata() = default;
272 static ValueAsMetadata *get(Value *V);
273 static ConstantAsMetadata *getConstant(Value *C) {
274 return cast<ConstantAsMetadata>(get(C));
276 static LocalAsMetadata *getLocal(Value *Local) {
277 return cast<LocalAsMetadata>(get(Local));
280 static ValueAsMetadata *getIfExists(Value *V);
281 static ConstantAsMetadata *getConstantIfExists(Value *C) {
282 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
284 static LocalAsMetadata *getLocalIfExists(Value *Local) {
285 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
288 Value *getValue() const { return V; }
289 Type *getType() const { return V->getType(); }
290 LLVMContext &getContext() const { return V->getContext(); }
292 static void handleDeletion(Value *V);
293 static void handleRAUW(Value *From, Value *To);
296 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
298 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
299 /// \a Value gets RAUW'ed and the target already exists, this is used to
300 /// merge the two metadata nodes.
301 void replaceAllUsesWith(Metadata *MD) {
302 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
306 static bool classof(const Metadata *MD) {
307 return MD->getMetadataID() == LocalAsMetadataKind ||
308 MD->getMetadataID() == ConstantAsMetadataKind;
312 class ConstantAsMetadata : public ValueAsMetadata {
313 friend class ValueAsMetadata;
315 ConstantAsMetadata(Constant *C)
316 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
319 static ConstantAsMetadata *get(Constant *C) {
320 return ValueAsMetadata::getConstant(C);
322 static ConstantAsMetadata *getIfExists(Constant *C) {
323 return ValueAsMetadata::getConstantIfExists(C);
326 Constant *getValue() const {
327 return cast<Constant>(ValueAsMetadata::getValue());
330 static bool classof(const Metadata *MD) {
331 return MD->getMetadataID() == ConstantAsMetadataKind;
335 class LocalAsMetadata : public ValueAsMetadata {
336 friend class ValueAsMetadata;
338 LocalAsMetadata(Value *Local)
339 : ValueAsMetadata(LocalAsMetadataKind, Local) {
340 assert(!isa<Constant>(Local) && "Expected local value");
344 static LocalAsMetadata *get(Value *Local) {
345 return ValueAsMetadata::getLocal(Local);
347 static LocalAsMetadata *getIfExists(Value *Local) {
348 return ValueAsMetadata::getLocalIfExists(Local);
351 static bool classof(const Metadata *MD) {
352 return MD->getMetadataID() == LocalAsMetadataKind;
356 /// \brief Transitional API for extracting constants from Metadata.
358 /// This namespace contains transitional functions for metadata that points to
361 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
362 /// operands could refer to any \a Value. There's was a lot of code like this:
366 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
369 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
370 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
371 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
372 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
373 /// requires subtle control flow changes.
375 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
376 /// so that metadata can refer to numbers without traversing a bridge to the \a
377 /// Value hierarchy. In this final state, the code above would look like this:
381 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
384 /// The API in this namespace supports the transition. \a MDInt doesn't exist
385 /// yet, and even once it does, changing each metadata schema to use it is its
386 /// own mini-project. In the meantime this API prevents us from introducing
387 /// complex and bug-prone control flow that will disappear in the end. In
388 /// particular, the above code looks like this:
392 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
395 /// The full set of provided functions includes:
397 /// mdconst::hasa <=> isa
398 /// mdconst::extract <=> cast
399 /// mdconst::extract_or_null <=> cast_or_null
400 /// mdconst::dyn_extract <=> dyn_cast
401 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
403 /// The target of the cast must be a subclass of \a Constant.
407 template <class T> T &make();
408 template <class T, class Result> struct HasDereference {
411 template <size_t N> struct SFINAE {};
413 template <class U, class V>
414 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
415 template <class U, class V> static No &hasDereference(...);
417 static const bool value =
418 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
420 template <class V, class M> struct IsValidPointer {
421 static const bool value = std::is_base_of<Constant, V>::value &&
422 HasDereference<M, const Metadata &>::value;
424 template <class V, class M> struct IsValidReference {
425 static const bool value = std::is_base_of<Constant, V>::value &&
426 std::is_convertible<M, const Metadata &>::value;
428 } // end namespace detail
430 /// \brief Check whether Metadata has a Value.
432 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
434 template <class X, class Y>
435 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
437 assert(MD && "Null pointer sent into hasa");
438 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
439 return isa<X>(V->getValue());
442 template <class X, class Y>
444 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
449 /// \brief Extract a Value from Metadata.
451 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
452 template <class X, class Y>
453 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
455 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
457 template <class X, class Y>
459 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
464 /// \brief Extract a Value from Metadata, allowing null.
466 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
467 /// from \c MD, allowing \c MD to be null.
468 template <class X, class Y>
469 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
470 extract_or_null(Y &&MD) {
471 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
472 return cast<X>(V->getValue());
476 /// \brief Extract a Value from Metadata, if any.
478 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
479 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
480 /// Value it does contain is of the wrong subclass.
481 template <class X, class Y>
482 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
483 dyn_extract(Y &&MD) {
484 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
485 return dyn_cast<X>(V->getValue());
489 /// \brief Extract a Value from Metadata, if any, allowing null.
491 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
492 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
493 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
494 template <class X, class Y>
495 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
496 dyn_extract_or_null(Y &&MD) {
497 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
498 return dyn_cast<X>(V->getValue());
502 } // end namespace mdconst
504 //===----------------------------------------------------------------------===//
505 /// \brief A single uniqued string.
507 /// These are used to efficiently contain a byte sequence for metadata.
508 /// MDString is always unnamed.
509 class MDString : public Metadata {
510 friend class StringMapEntry<MDString>;
512 MDString(const MDString &) = delete;
513 MDString &operator=(MDString &&) = delete;
514 MDString &operator=(const MDString &) = delete;
516 StringMapEntry<MDString> *Entry;
517 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
518 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
521 static MDString *get(LLVMContext &Context, StringRef Str);
522 static MDString *get(LLVMContext &Context, const char *Str) {
523 return get(Context, Str ? StringRef(Str) : StringRef());
526 StringRef getString() const;
528 unsigned getLength() const { return (unsigned)getString().size(); }
530 typedef StringRef::iterator iterator;
532 /// \brief Pointer to the first byte of the string.
533 iterator begin() const { return getString().begin(); }
535 /// \brief Pointer to one byte past the end of the string.
536 iterator end() const { return getString().end(); }
538 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
539 const unsigned char *bytes_end() const { return getString().bytes_end(); }
541 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
542 static bool classof(const Metadata *MD) {
543 return MD->getMetadataID() == MDStringKind;
547 /// \brief A collection of metadata nodes that might be associated with a
548 /// memory access used by the alias-analysis infrastructure.
550 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
552 : TBAA(T), Scope(S), NoAlias(N) {}
554 bool operator==(const AAMDNodes &A) const {
555 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
558 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
560 explicit operator bool() const { return TBAA || Scope || NoAlias; }
562 /// \brief The tag for type-based alias analysis.
565 /// \brief The tag for alias scope specification (used with noalias).
568 /// \brief The tag specifying the noalias scope.
572 // Specialize DenseMapInfo for AAMDNodes.
574 struct DenseMapInfo<AAMDNodes> {
575 static inline AAMDNodes getEmptyKey() {
576 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
579 static inline AAMDNodes getTombstoneKey() {
580 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
583 static unsigned getHashValue(const AAMDNodes &Val) {
584 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
585 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
586 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
588 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
593 /// \brief Tracking metadata reference owned by Metadata.
595 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
596 /// of \a Metadata, which has the option of registering itself for callbacks to
597 /// re-unique itself.
599 /// In particular, this is used by \a MDNode.
601 MDOperand(MDOperand &&) = delete;
602 MDOperand(const MDOperand &) = delete;
603 MDOperand &operator=(MDOperand &&) = delete;
604 MDOperand &operator=(const MDOperand &) = delete;
609 MDOperand() : MD(nullptr) {}
610 ~MDOperand() { untrack(); }
612 Metadata *get() const { return MD; }
613 operator Metadata *() const { return get(); }
614 Metadata *operator->() const { return get(); }
615 Metadata &operator*() const { return *get(); }
621 void reset(Metadata *MD, Metadata *Owner) {
628 void track(Metadata *Owner) {
631 MetadataTracking::track(this, *MD, *Owner);
633 MetadataTracking::track(MD);
637 assert(static_cast<void *>(this) == &MD && "Expected same address");
639 MetadataTracking::untrack(MD);
643 template <> struct simplify_type<MDOperand> {
644 typedef Metadata *SimpleType;
645 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
648 template <> struct simplify_type<const MDOperand> {
649 typedef Metadata *SimpleType;
650 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
653 /// \brief Pointer to the context, with optional RAUW support.
655 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
656 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
657 class ContextAndReplaceableUses {
658 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
660 ContextAndReplaceableUses() = delete;
661 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
662 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
663 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
664 ContextAndReplaceableUses &
665 operator=(const ContextAndReplaceableUses &) = delete;
668 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
669 ContextAndReplaceableUses(
670 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
671 : Ptr(ReplaceableUses.release()) {
672 assert(getReplaceableUses() && "Expected non-null replaceable uses");
674 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
676 operator LLVMContext &() { return getContext(); }
678 /// \brief Whether this contains RAUW support.
679 bool hasReplaceableUses() const {
680 return Ptr.is<ReplaceableMetadataImpl *>();
682 LLVMContext &getContext() const {
683 if (hasReplaceableUses())
684 return getReplaceableUses()->getContext();
685 return *Ptr.get<LLVMContext *>();
687 ReplaceableMetadataImpl *getReplaceableUses() const {
688 if (hasReplaceableUses())
689 return Ptr.get<ReplaceableMetadataImpl *>();
693 /// \brief Assign RAUW support to this.
695 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
698 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
699 assert(ReplaceableUses && "Expected non-null replaceable uses");
700 assert(&ReplaceableUses->getContext() == &getContext() &&
701 "Expected same context");
702 delete getReplaceableUses();
703 Ptr = ReplaceableUses.release();
706 /// \brief Drop RAUW support.
708 /// Cede ownership of RAUW support, returning it.
709 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
710 assert(hasReplaceableUses() && "Expected to own replaceable uses");
711 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
712 getReplaceableUses());
713 Ptr = &ReplaceableUses->getContext();
714 return ReplaceableUses;
718 struct TempMDNodeDeleter {
719 inline void operator()(MDNode *Node) const;
722 #define HANDLE_MDNODE_LEAF(CLASS) \
723 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
724 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
725 #include "llvm/IR/Metadata.def"
727 /// \brief Metadata node.
729 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
730 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
731 /// until forward references are known. The basic metadata node is an \a
734 /// There is limited support for RAUW at construction time. At construction
735 /// time, if any operand is a temporary node (or an unresolved uniqued node,
736 /// which indicates a transitive temporary operand), the node itself will be
737 /// unresolved. As soon as all operands become resolved, it will drop RAUW
738 /// support permanently.
740 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
741 /// to be called on some member of the cycle once all temporary nodes have been
743 class MDNode : public Metadata {
744 friend class ReplaceableMetadataImpl;
745 friend class LLVMContextImpl;
747 MDNode(const MDNode &) = delete;
748 void operator=(const MDNode &) = delete;
749 void *operator new(size_t) = delete;
751 unsigned NumOperands;
752 unsigned NumUnresolved;
755 ContextAndReplaceableUses Context;
757 void *operator new(size_t Size, unsigned NumOps);
758 void operator delete(void *Mem);
760 /// \brief Required by std, but never called.
761 void operator delete(void *, unsigned) {
762 llvm_unreachable("Constructor throws?");
765 /// \brief Required by std, but never called.
766 void operator delete(void *, unsigned, bool) {
767 llvm_unreachable("Constructor throws?");
770 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
771 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
774 void dropAllReferences();
776 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
777 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
779 typedef iterator_range<MDOperand *> mutable_op_range;
780 mutable_op_range mutable_operands() {
781 return mutable_op_range(mutable_begin(), mutable_end());
785 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
786 static inline MDTuple *getIfExists(LLVMContext &Context,
787 ArrayRef<Metadata *> MDs);
788 static inline MDTuple *getDistinct(LLVMContext &Context,
789 ArrayRef<Metadata *> MDs);
790 static inline TempMDTuple getTemporary(LLVMContext &Context,
791 ArrayRef<Metadata *> MDs);
793 /// \brief Create a (temporary) clone of this.
794 TempMDNode clone() const;
796 /// \brief Deallocate a node created by getTemporary.
798 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
799 /// references will be reset.
800 static void deleteTemporary(MDNode *N);
802 LLVMContext &getContext() const { return Context.getContext(); }
804 /// \brief Replace a specific operand.
805 void replaceOperandWith(unsigned I, Metadata *New);
807 /// \brief Check if node is fully resolved.
809 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
810 /// this always returns \c true.
812 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
813 /// support (because all operands are resolved).
815 /// As forward declarations are resolved, their containers should get
816 /// resolved automatically. However, if this (or one of its operands) is
817 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
818 bool isResolved() const { return !Context.hasReplaceableUses(); }
820 bool isUniqued() const { return Storage == Uniqued; }
821 bool isDistinct() const { return Storage == Distinct; }
822 bool isTemporary() const { return Storage == Temporary; }
824 /// \brief RAUW a temporary.
826 /// \pre \a isTemporary() must be \c true.
827 void replaceAllUsesWith(Metadata *MD) {
828 assert(isTemporary() && "Expected temporary node");
829 assert(!isResolved() && "Expected RAUW support");
830 Context.getReplaceableUses()->replaceAllUsesWith(MD);
833 /// \brief Resolve cycles.
835 /// Once all forward declarations have been resolved, force cycles to be
838 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
839 void resolveCycles();
841 /// \brief Replace a temporary node with a permanent one.
843 /// Try to create a uniqued version of \c N -- in place, if possible -- and
844 /// return it. If \c N cannot be uniqued, return a distinct node instead.
846 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
847 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
848 return cast<T>(N.release()->replaceWithPermanentImpl());
851 /// \brief Replace a temporary node with a uniqued one.
853 /// Create a uniqued version of \c N -- in place, if possible -- and return
854 /// it. Takes ownership of the temporary node.
856 /// \pre N does not self-reference.
858 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
859 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
860 return cast<T>(N.release()->replaceWithUniquedImpl());
863 /// \brief Replace a temporary node with a distinct one.
865 /// Create a distinct version of \c N -- in place, if possible -- and return
866 /// it. Takes ownership of the temporary node.
868 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
869 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
870 return cast<T>(N.release()->replaceWithDistinctImpl());
874 MDNode *replaceWithPermanentImpl();
875 MDNode *replaceWithUniquedImpl();
876 MDNode *replaceWithDistinctImpl();
879 /// \brief Set an operand.
881 /// Sets the operand directly, without worrying about uniquing.
882 void setOperand(unsigned I, Metadata *New);
884 void storeDistinctInContext();
885 template <class T, class StoreT>
886 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
887 template <class T> static T *storeImpl(T *N, StorageType Storage);
890 void handleChangedOperand(void *Ref, Metadata *New);
893 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
894 void decrementUnresolvedOperandCount();
895 unsigned countUnresolvedOperands();
897 /// \brief Mutate this to be "uniqued".
899 /// Mutate this so that \a isUniqued().
900 /// \pre \a isTemporary().
901 /// \pre already added to uniquing set.
904 /// \brief Mutate this to be "distinct".
906 /// Mutate this so that \a isDistinct().
907 /// \pre \a isTemporary().
910 void deleteAsSubclass();
912 void eraseFromStore();
914 template <class NodeTy> struct HasCachedHash;
915 template <class NodeTy>
916 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
917 N->recalculateHash();
919 template <class NodeTy>
920 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
921 template <class NodeTy>
922 static void dispatchResetHash(NodeTy *N, std::true_type) {
925 template <class NodeTy>
926 static void dispatchResetHash(NodeTy *N, std::false_type) {}
929 typedef const MDOperand *op_iterator;
930 typedef iterator_range<op_iterator> op_range;
932 op_iterator op_begin() const {
933 return const_cast<MDNode *>(this)->mutable_begin();
935 op_iterator op_end() const {
936 return const_cast<MDNode *>(this)->mutable_end();
938 op_range operands() const { return op_range(op_begin(), op_end()); }
940 const MDOperand &getOperand(unsigned I) const {
941 assert(I < NumOperands && "Out of range");
942 return op_begin()[I];
945 /// \brief Return number of MDNode operands.
946 unsigned getNumOperands() const { return NumOperands; }
948 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
949 static bool classof(const Metadata *MD) {
950 switch (MD->getMetadataID()) {
953 #define HANDLE_MDNODE_LEAF(CLASS) \
956 #include "llvm/IR/Metadata.def"
960 /// \brief Check whether MDNode is a vtable access.
961 bool isTBAAVtableAccess() const;
963 /// \brief Methods for metadata merging.
964 static MDNode *concatenate(MDNode *A, MDNode *B);
965 static MDNode *intersect(MDNode *A, MDNode *B);
966 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
967 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
968 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
969 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
972 /// \brief Tuple of metadata.
974 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
975 /// default based on their operands.
976 class MDTuple : public MDNode {
977 friend class LLVMContextImpl;
980 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
981 ArrayRef<Metadata *> Vals)
982 : MDNode(C, MDTupleKind, Storage, Vals) {
985 ~MDTuple() { dropAllReferences(); }
987 void setHash(unsigned Hash) { SubclassData32 = Hash; }
988 void recalculateHash();
990 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
991 StorageType Storage, bool ShouldCreate = true);
993 TempMDTuple cloneImpl() const {
994 return getTemporary(getContext(),
995 SmallVector<Metadata *, 4>(op_begin(), op_end()));
999 /// \brief Get the hash, if any.
1000 unsigned getHash() const { return SubclassData32; }
1002 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1003 return getImpl(Context, MDs, Uniqued);
1005 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1006 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1009 /// \brief Return a distinct node.
1011 /// Return a distinct node -- i.e., a node that is not uniqued.
1012 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1013 return getImpl(Context, MDs, Distinct);
1016 /// \brief Return a temporary node.
1018 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1019 /// not uniqued, may be RAUW'd, and must be manually deleted with
1020 /// deleteTemporary.
1021 static TempMDTuple getTemporary(LLVMContext &Context,
1022 ArrayRef<Metadata *> MDs) {
1023 return TempMDTuple(getImpl(Context, MDs, Temporary));
1026 /// \brief Return a (temporary) clone of this.
1027 TempMDTuple clone() const { return cloneImpl(); }
1029 static bool classof(const Metadata *MD) {
1030 return MD->getMetadataID() == MDTupleKind;
1034 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1035 return MDTuple::get(Context, MDs);
1037 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1038 return MDTuple::getIfExists(Context, MDs);
1040 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1041 return MDTuple::getDistinct(Context, MDs);
1043 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1044 ArrayRef<Metadata *> MDs) {
1045 return MDTuple::getTemporary(Context, MDs);
1048 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1049 MDNode::deleteTemporary(Node);
1052 /// \brief Typed iterator through MDNode operands.
1054 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1055 /// particular Metadata subclass.
1057 class TypedMDOperandIterator
1058 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1059 MDNode::op_iterator I = nullptr;
1062 TypedMDOperandIterator() = default;
1063 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1064 T *operator*() const { return cast_or_null<T>(*I); }
1065 TypedMDOperandIterator &operator++() {
1069 TypedMDOperandIterator operator++(int) {
1070 TypedMDOperandIterator Temp(*this);
1074 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1075 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1078 /// \brief Typed, array-like tuple of metadata.
1080 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1081 /// particular type of metadata.
1082 template <class T> class MDTupleTypedArrayWrapper {
1083 const MDTuple *N = nullptr;
1086 MDTupleTypedArrayWrapper() = default;
1087 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1090 MDTupleTypedArrayWrapper(
1091 const MDTupleTypedArrayWrapper<U> &Other,
1092 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1097 explicit MDTupleTypedArrayWrapper(
1098 const MDTupleTypedArrayWrapper<U> &Other,
1099 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1103 explicit operator bool() const { return get(); }
1104 explicit operator MDTuple *() const { return get(); }
1106 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1107 MDTuple *operator->() const { return get(); }
1108 MDTuple &operator*() const { return *get(); }
1110 // FIXME: Fix callers and remove condition on N.
1111 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1112 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1114 // FIXME: Fix callers and remove condition on N.
1115 typedef TypedMDOperandIterator<T> iterator;
1116 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1117 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1120 #define HANDLE_METADATA(CLASS) \
1121 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1122 #include "llvm/IR/Metadata.def"
1124 //===----------------------------------------------------------------------===//
1125 /// \brief A tuple of MDNodes.
1127 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1128 /// to modules, have names, and contain lists of MDNodes.
1130 /// TODO: Inherit from Metadata.
1131 class NamedMDNode : public ilist_node<NamedMDNode> {
1132 friend class SymbolTableListTraits<NamedMDNode, Module>;
1133 friend struct ilist_traits<NamedMDNode>;
1134 friend class LLVMContextImpl;
1135 friend class Module;
1136 NamedMDNode(const NamedMDNode &) = delete;
1140 void *Operands; // SmallVector<TrackingMDRef, 4>
1142 void setParent(Module *M) { Parent = M; }
1144 explicit NamedMDNode(const Twine &N);
1146 template<class T1, class T2>
1147 class op_iterator_impl :
1148 public std::iterator<std::bidirectional_iterator_tag, T2> {
1149 const NamedMDNode *Node;
1151 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1153 friend class NamedMDNode;
1156 op_iterator_impl() : Node(nullptr), Idx(0) { }
1158 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1159 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1160 op_iterator_impl &operator++() {
1164 op_iterator_impl operator++(int) {
1165 op_iterator_impl tmp(*this);
1169 op_iterator_impl &operator--() {
1173 op_iterator_impl operator--(int) {
1174 op_iterator_impl tmp(*this);
1179 T1 operator*() const { return Node->getOperand(Idx); }
1183 /// \brief Drop all references and remove the node from parent module.
1184 void eraseFromParent();
1186 /// \brief Remove all uses and clear node vector.
1187 void dropAllReferences();
1191 /// \brief Get the module that holds this named metadata collection.
1192 inline Module *getParent() { return Parent; }
1193 inline const Module *getParent() const { return Parent; }
1195 MDNode *getOperand(unsigned i) const;
1196 unsigned getNumOperands() const;
1197 void addOperand(MDNode *M);
1198 void setOperand(unsigned I, MDNode *New);
1199 StringRef getName() const;
1200 void print(raw_ostream &ROS, bool IsForDebug = false) const;
1203 // ---------------------------------------------------------------------------
1204 // Operand Iterator interface...
1206 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1207 op_iterator op_begin() { return op_iterator(this, 0); }
1208 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1210 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1211 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1212 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1214 inline iterator_range<op_iterator> operands() {
1215 return iterator_range<op_iterator>(op_begin(), op_end());
1217 inline iterator_range<const_op_iterator> operands() const {
1218 return iterator_range<const_op_iterator>(op_begin(), op_end());
1222 } // end llvm namespace
1224 #endif // LLVM_IR_METADATA_H