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,
79 DITemplateTypeParameterKind,
80 DITemplateValueParameterKind,
86 ConstantAsMetadataKind,
92 Metadata(unsigned ID, StorageType Storage)
93 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
95 ~Metadata() = default;
97 /// \brief Default handling of a changed operand, which asserts.
99 /// If subclasses pass themselves in as owners to a tracking node reference,
100 /// they must provide an implementation of this method.
101 void handleChangedOperand(void *, Metadata *) {
102 llvm_unreachable("Unimplemented in Metadata subclass");
106 unsigned getMetadataID() const { return SubclassID; }
108 /// \brief User-friendly dump.
110 /// If \c M is provided, metadata nodes will be numbered canonically;
111 /// otherwise, pointer addresses are substituted.
113 /// Note: this uses an explicit overload instead of default arguments so that
114 /// the nullptr version is easy to call from a debugger.
118 void dump(const Module *M) const;
123 /// Prints definition of \c this.
125 /// If \c M is provided, metadata nodes will be numbered canonically;
126 /// otherwise, pointer addresses are substituted.
127 void print(raw_ostream &OS, const Module *M = nullptr) const;
129 /// \brief Print as operand.
131 /// Prints reference of \c this.
133 /// If \c M is provided, metadata nodes will be numbered canonically;
134 /// otherwise, pointer addresses are substituted.
136 void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
137 void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
138 const Module *M = nullptr) const;
142 #define HANDLE_METADATA(CLASS) class CLASS;
143 #include "llvm/IR/Metadata.def"
145 // Provide specializations of isa so that we don't need definitions of
146 // subclasses to see if the metadata is a subclass.
147 #define HANDLE_METADATA_LEAF(CLASS) \
148 template <> struct isa_impl<CLASS, Metadata> { \
149 static inline bool doit(const Metadata &MD) { \
150 return MD.getMetadataID() == Metadata::CLASS##Kind; \
153 #include "llvm/IR/Metadata.def"
155 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
160 /// \brief Metadata wrapper in the Value hierarchy.
162 /// A member of the \a Value hierarchy to represent a reference to metadata.
163 /// This allows, e.g., instrinsics to have metadata as operands.
165 /// Notably, this is the only thing in either hierarchy that is allowed to
166 /// reference \a LocalAsMetadata.
167 class MetadataAsValue : public Value {
168 friend class ReplaceableMetadataImpl;
169 friend class LLVMContextImpl;
173 MetadataAsValue(Type *Ty, Metadata *MD);
174 ~MetadataAsValue() override;
176 /// \brief Drop use of metadata (during teardown).
177 void dropUse() { MD = nullptr; }
180 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
181 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
182 Metadata *getMetadata() const { return MD; }
184 static bool classof(const Value *V) {
185 return V->getValueID() == MetadataAsValueVal;
189 void handleChangedMetadata(Metadata *MD);
194 /// \brief Shared implementation of use-lists for replaceable metadata.
196 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
197 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
198 /// and \a TempMDNode).
199 class ReplaceableMetadataImpl {
200 friend class MetadataTracking;
203 typedef MetadataTracking::OwnerTy OwnerTy;
206 LLVMContext &Context;
208 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
211 ReplaceableMetadataImpl(LLVMContext &Context)
212 : Context(Context), NextIndex(0) {}
213 ~ReplaceableMetadataImpl() {
214 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
217 LLVMContext &getContext() const { return Context; }
219 /// \brief Replace all uses of this with MD.
221 /// Replace all uses of this with \c MD, which is allowed to be null.
222 void replaceAllUsesWith(Metadata *MD);
224 /// \brief Resolve all uses of this.
226 /// Resolve all uses of this, turning off RAUW permanently. If \c
227 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
229 void resolveAllUses(bool ResolveUsers = true);
232 void addRef(void *Ref, OwnerTy Owner);
233 void dropRef(void *Ref);
234 void moveRef(void *Ref, void *New, const Metadata &MD);
236 static ReplaceableMetadataImpl *get(Metadata &MD);
239 /// \brief Value wrapper in the Metadata hierarchy.
241 /// This is a custom value handle that allows other metadata to refer to
242 /// classes in the Value hierarchy.
244 /// Because of full uniquing support, each value is only wrapped by a single \a
245 /// ValueAsMetadata object, so the lookup maps are far more efficient than
246 /// those using ValueHandleBase.
247 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
248 friend class ReplaceableMetadataImpl;
249 friend class LLVMContextImpl;
253 /// \brief Drop users without RAUW (during teardown).
255 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
259 ValueAsMetadata(unsigned ID, Value *V)
260 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
261 assert(V && "Expected valid value");
263 ~ValueAsMetadata() = default;
266 static ValueAsMetadata *get(Value *V);
267 static ConstantAsMetadata *getConstant(Value *C) {
268 return cast<ConstantAsMetadata>(get(C));
270 static LocalAsMetadata *getLocal(Value *Local) {
271 return cast<LocalAsMetadata>(get(Local));
274 static ValueAsMetadata *getIfExists(Value *V);
275 static ConstantAsMetadata *getConstantIfExists(Value *C) {
276 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
278 static LocalAsMetadata *getLocalIfExists(Value *Local) {
279 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
282 Value *getValue() const { return V; }
283 Type *getType() const { return V->getType(); }
284 LLVMContext &getContext() const { return V->getContext(); }
286 static void handleDeletion(Value *V);
287 static void handleRAUW(Value *From, Value *To);
290 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
292 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
293 /// \a Value gets RAUW'ed and the target already exists, this is used to
294 /// merge the two metadata nodes.
295 void replaceAllUsesWith(Metadata *MD) {
296 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
300 static bool classof(const Metadata *MD) {
301 return MD->getMetadataID() == LocalAsMetadataKind ||
302 MD->getMetadataID() == ConstantAsMetadataKind;
306 class ConstantAsMetadata : public ValueAsMetadata {
307 friend class ValueAsMetadata;
309 ConstantAsMetadata(Constant *C)
310 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
313 static ConstantAsMetadata *get(Constant *C) {
314 return ValueAsMetadata::getConstant(C);
316 static ConstantAsMetadata *getIfExists(Constant *C) {
317 return ValueAsMetadata::getConstantIfExists(C);
320 Constant *getValue() const {
321 return cast<Constant>(ValueAsMetadata::getValue());
324 static bool classof(const Metadata *MD) {
325 return MD->getMetadataID() == ConstantAsMetadataKind;
329 class LocalAsMetadata : public ValueAsMetadata {
330 friend class ValueAsMetadata;
332 LocalAsMetadata(Value *Local)
333 : ValueAsMetadata(LocalAsMetadataKind, Local) {
334 assert(!isa<Constant>(Local) && "Expected local value");
338 static LocalAsMetadata *get(Value *Local) {
339 return ValueAsMetadata::getLocal(Local);
341 static LocalAsMetadata *getIfExists(Value *Local) {
342 return ValueAsMetadata::getLocalIfExists(Local);
345 static bool classof(const Metadata *MD) {
346 return MD->getMetadataID() == LocalAsMetadataKind;
350 /// \brief Transitional API for extracting constants from Metadata.
352 /// This namespace contains transitional functions for metadata that points to
355 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
356 /// operands could refer to any \a Value. There's was a lot of code like this:
360 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
363 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
364 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
365 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
366 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
367 /// requires subtle control flow changes.
369 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
370 /// so that metadata can refer to numbers without traversing a bridge to the \a
371 /// Value hierarchy. In this final state, the code above would look like this:
375 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
378 /// The API in this namespace supports the transition. \a MDInt doesn't exist
379 /// yet, and even once it does, changing each metadata schema to use it is its
380 /// own mini-project. In the meantime this API prevents us from introducing
381 /// complex and bug-prone control flow that will disappear in the end. In
382 /// particular, the above code looks like this:
386 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
389 /// The full set of provided functions includes:
391 /// mdconst::hasa <=> isa
392 /// mdconst::extract <=> cast
393 /// mdconst::extract_or_null <=> cast_or_null
394 /// mdconst::dyn_extract <=> dyn_cast
395 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
397 /// The target of the cast must be a subclass of \a Constant.
401 template <class T> T &make();
402 template <class T, class Result> struct HasDereference {
405 template <size_t N> struct SFINAE {};
407 template <class U, class V>
408 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
409 template <class U, class V> static No &hasDereference(...);
411 static const bool value =
412 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
414 template <class V, class M> struct IsValidPointer {
415 static const bool value = std::is_base_of<Constant, V>::value &&
416 HasDereference<M, const Metadata &>::value;
418 template <class V, class M> struct IsValidReference {
419 static const bool value = std::is_base_of<Constant, V>::value &&
420 std::is_convertible<M, const Metadata &>::value;
422 } // end namespace detail
424 /// \brief Check whether Metadata has a Value.
426 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
428 template <class X, class Y>
429 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
431 assert(MD && "Null pointer sent into hasa");
432 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
433 return isa<X>(V->getValue());
436 template <class X, class Y>
438 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
443 /// \brief Extract a Value from Metadata.
445 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
446 template <class X, class Y>
447 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
449 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
451 template <class X, class Y>
453 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
458 /// \brief Extract a Value from Metadata, allowing null.
460 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
461 /// from \c MD, allowing \c MD to be null.
462 template <class X, class Y>
463 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
464 extract_or_null(Y &&MD) {
465 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
466 return cast<X>(V->getValue());
470 /// \brief Extract a Value from Metadata, if any.
472 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
473 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
474 /// Value it does contain is of the wrong subclass.
475 template <class X, class Y>
476 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
477 dyn_extract(Y &&MD) {
478 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
479 return dyn_cast<X>(V->getValue());
483 /// \brief Extract a Value from Metadata, if any, allowing null.
485 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
486 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
487 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
488 template <class X, class Y>
489 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
490 dyn_extract_or_null(Y &&MD) {
491 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
492 return dyn_cast<X>(V->getValue());
496 } // end namespace mdconst
498 //===----------------------------------------------------------------------===//
499 /// \brief A single uniqued string.
501 /// These are used to efficiently contain a byte sequence for metadata.
502 /// MDString is always unnamed.
503 class MDString : public Metadata {
504 friend class StringMapEntry<MDString>;
506 MDString(const MDString &) = delete;
507 MDString &operator=(MDString &&) = delete;
508 MDString &operator=(const MDString &) = delete;
510 StringMapEntry<MDString> *Entry;
511 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
512 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
515 static MDString *get(LLVMContext &Context, StringRef Str);
516 static MDString *get(LLVMContext &Context, const char *Str) {
517 return get(Context, Str ? StringRef(Str) : StringRef());
520 StringRef getString() const;
522 unsigned getLength() const { return (unsigned)getString().size(); }
524 typedef StringRef::iterator iterator;
526 /// \brief Pointer to the first byte of the string.
527 iterator begin() const { return getString().begin(); }
529 /// \brief Pointer to one byte past the end of the string.
530 iterator end() const { return getString().end(); }
532 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
533 const unsigned char *bytes_end() const { return getString().bytes_end(); }
535 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
536 static bool classof(const Metadata *MD) {
537 return MD->getMetadataID() == MDStringKind;
541 /// \brief A collection of metadata nodes that might be associated with a
542 /// memory access used by the alias-analysis infrastructure.
544 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
546 : TBAA(T), Scope(S), NoAlias(N) {}
548 bool operator==(const AAMDNodes &A) const {
549 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
552 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
554 explicit operator bool() const { return TBAA || Scope || NoAlias; }
556 /// \brief The tag for type-based alias analysis.
559 /// \brief The tag for alias scope specification (used with noalias).
562 /// \brief The tag specifying the noalias scope.
566 // Specialize DenseMapInfo for AAMDNodes.
568 struct DenseMapInfo<AAMDNodes> {
569 static inline AAMDNodes getEmptyKey() {
570 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
572 static inline AAMDNodes getTombstoneKey() {
573 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
575 static unsigned getHashValue(const AAMDNodes &Val) {
576 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
577 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
578 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
580 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
585 /// \brief Tracking metadata reference owned by Metadata.
587 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
588 /// of \a Metadata, which has the option of registering itself for callbacks to
589 /// re-unique itself.
591 /// In particular, this is used by \a MDNode.
593 MDOperand(MDOperand &&) = delete;
594 MDOperand(const MDOperand &) = delete;
595 MDOperand &operator=(MDOperand &&) = delete;
596 MDOperand &operator=(const MDOperand &) = delete;
601 MDOperand() : MD(nullptr) {}
602 ~MDOperand() { untrack(); }
604 Metadata *get() const { return MD; }
605 operator Metadata *() const { return get(); }
606 Metadata *operator->() const { return get(); }
607 Metadata &operator*() const { return *get(); }
613 void reset(Metadata *MD, Metadata *Owner) {
620 void track(Metadata *Owner) {
623 MetadataTracking::track(this, *MD, *Owner);
625 MetadataTracking::track(MD);
629 assert(static_cast<void *>(this) == &MD && "Expected same address");
631 MetadataTracking::untrack(MD);
635 template <> struct simplify_type<MDOperand> {
636 typedef Metadata *SimpleType;
637 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
640 template <> struct simplify_type<const MDOperand> {
641 typedef Metadata *SimpleType;
642 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
645 /// \brief Pointer to the context, with optional RAUW support.
647 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
648 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
649 class ContextAndReplaceableUses {
650 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
652 ContextAndReplaceableUses() = delete;
653 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
654 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
655 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
656 ContextAndReplaceableUses &
657 operator=(const ContextAndReplaceableUses &) = delete;
660 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
661 ContextAndReplaceableUses(
662 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
663 : Ptr(ReplaceableUses.release()) {
664 assert(getReplaceableUses() && "Expected non-null replaceable uses");
666 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
668 operator LLVMContext &() { return getContext(); }
670 /// \brief Whether this contains RAUW support.
671 bool hasReplaceableUses() const {
672 return Ptr.is<ReplaceableMetadataImpl *>();
674 LLVMContext &getContext() const {
675 if (hasReplaceableUses())
676 return getReplaceableUses()->getContext();
677 return *Ptr.get<LLVMContext *>();
679 ReplaceableMetadataImpl *getReplaceableUses() const {
680 if (hasReplaceableUses())
681 return Ptr.get<ReplaceableMetadataImpl *>();
685 /// \brief Assign RAUW support to this.
687 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
690 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
691 assert(ReplaceableUses && "Expected non-null replaceable uses");
692 assert(&ReplaceableUses->getContext() == &getContext() &&
693 "Expected same context");
694 delete getReplaceableUses();
695 Ptr = ReplaceableUses.release();
698 /// \brief Drop RAUW support.
700 /// Cede ownership of RAUW support, returning it.
701 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
702 assert(hasReplaceableUses() && "Expected to own replaceable uses");
703 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
704 getReplaceableUses());
705 Ptr = &ReplaceableUses->getContext();
706 return ReplaceableUses;
710 struct TempMDNodeDeleter {
711 inline void operator()(MDNode *Node) const;
714 #define HANDLE_MDNODE_LEAF(CLASS) \
715 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
716 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
717 #include "llvm/IR/Metadata.def"
719 /// \brief Metadata node.
721 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
722 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
723 /// until forward references are known. The basic metadata node is an \a
726 /// There is limited support for RAUW at construction time. At construction
727 /// time, if any operand is a temporary node (or an unresolved uniqued node,
728 /// which indicates a transitive temporary operand), the node itself will be
729 /// unresolved. As soon as all operands become resolved, it will drop RAUW
730 /// support permanently.
732 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
733 /// to be called on some member of the cycle once all temporary nodes have been
735 class MDNode : public Metadata {
736 friend class ReplaceableMetadataImpl;
737 friend class LLVMContextImpl;
739 MDNode(const MDNode &) = delete;
740 void operator=(const MDNode &) = delete;
741 void *operator new(size_t) = delete;
743 unsigned NumOperands;
744 unsigned NumUnresolved;
747 ContextAndReplaceableUses Context;
749 void *operator new(size_t Size, unsigned NumOps);
750 void operator delete(void *Mem);
752 /// \brief Required by std, but never called.
753 void operator delete(void *, unsigned) {
754 llvm_unreachable("Constructor throws?");
757 /// \brief Required by std, but never called.
758 void operator delete(void *, unsigned, bool) {
759 llvm_unreachable("Constructor throws?");
762 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
763 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
766 void dropAllReferences();
768 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
769 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
771 typedef iterator_range<MDOperand *> mutable_op_range;
772 mutable_op_range mutable_operands() {
773 return mutable_op_range(mutable_begin(), mutable_end());
777 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
778 static inline MDTuple *getIfExists(LLVMContext &Context,
779 ArrayRef<Metadata *> MDs);
780 static inline MDTuple *getDistinct(LLVMContext &Context,
781 ArrayRef<Metadata *> MDs);
782 static inline TempMDTuple getTemporary(LLVMContext &Context,
783 ArrayRef<Metadata *> MDs);
785 /// \brief Create a (temporary) clone of this.
786 TempMDNode clone() const;
788 /// \brief Deallocate a node created by getTemporary.
790 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
791 /// references will be reset.
792 static void deleteTemporary(MDNode *N);
794 LLVMContext &getContext() const { return Context.getContext(); }
796 /// \brief Replace a specific operand.
797 void replaceOperandWith(unsigned I, Metadata *New);
799 /// \brief Check if node is fully resolved.
801 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
802 /// this always returns \c true.
804 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
805 /// support (because all operands are resolved).
807 /// As forward declarations are resolved, their containers should get
808 /// resolved automatically. However, if this (or one of its operands) is
809 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
810 bool isResolved() const { return !Context.hasReplaceableUses(); }
812 bool isUniqued() const { return Storage == Uniqued; }
813 bool isDistinct() const { return Storage == Distinct; }
814 bool isTemporary() const { return Storage == Temporary; }
816 /// \brief RAUW a temporary.
818 /// \pre \a isTemporary() must be \c true.
819 void replaceAllUsesWith(Metadata *MD) {
820 assert(isTemporary() && "Expected temporary node");
821 assert(!isResolved() && "Expected RAUW support");
822 Context.getReplaceableUses()->replaceAllUsesWith(MD);
825 /// \brief Resolve cycles.
827 /// Once all forward declarations have been resolved, force cycles to be
830 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
831 void resolveCycles();
833 /// \brief Replace a temporary node with a permanent one.
835 /// Try to create a uniqued version of \c N -- in place, if possible -- and
836 /// return it. If \c N cannot be uniqued, return a distinct node instead.
838 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
839 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
840 return cast<T>(N.release()->replaceWithPermanentImpl());
843 /// \brief Replace a temporary node with a uniqued one.
845 /// Create a uniqued version of \c N -- in place, if possible -- and return
846 /// it. Takes ownership of the temporary node.
848 /// \pre N does not self-reference.
850 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
851 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
852 return cast<T>(N.release()->replaceWithUniquedImpl());
855 /// \brief Replace a temporary node with a distinct one.
857 /// Create a distinct version of \c N -- in place, if possible -- and return
858 /// it. Takes ownership of the temporary node.
860 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
861 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
862 return cast<T>(N.release()->replaceWithDistinctImpl());
866 MDNode *replaceWithPermanentImpl();
867 MDNode *replaceWithUniquedImpl();
868 MDNode *replaceWithDistinctImpl();
871 /// \brief Set an operand.
873 /// Sets the operand directly, without worrying about uniquing.
874 void setOperand(unsigned I, Metadata *New);
876 void storeDistinctInContext();
877 template <class T, class StoreT>
878 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
881 void handleChangedOperand(void *Ref, Metadata *New);
884 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
885 void decrementUnresolvedOperandCount();
886 unsigned countUnresolvedOperands();
888 /// \brief Mutate this to be "uniqued".
890 /// Mutate this so that \a isUniqued().
891 /// \pre \a isTemporary().
892 /// \pre already added to uniquing set.
895 /// \brief Mutate this to be "distinct".
897 /// Mutate this so that \a isDistinct().
898 /// \pre \a isTemporary().
901 void deleteAsSubclass();
903 void eraseFromStore();
905 template <class NodeTy> struct HasCachedHash;
906 template <class NodeTy>
907 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
908 N->recalculateHash();
910 template <class NodeTy>
911 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
912 template <class NodeTy>
913 static void dispatchResetHash(NodeTy *N, std::true_type) {
916 template <class NodeTy>
917 static void dispatchResetHash(NodeTy *N, std::false_type) {}
920 typedef const MDOperand *op_iterator;
921 typedef iterator_range<op_iterator> op_range;
923 op_iterator op_begin() const {
924 return const_cast<MDNode *>(this)->mutable_begin();
926 op_iterator op_end() const {
927 return const_cast<MDNode *>(this)->mutable_end();
929 op_range operands() const { return op_range(op_begin(), op_end()); }
931 const MDOperand &getOperand(unsigned I) const {
932 assert(I < NumOperands && "Out of range");
933 return op_begin()[I];
936 /// \brief Return number of MDNode operands.
937 unsigned getNumOperands() const { return NumOperands; }
939 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
940 static bool classof(const Metadata *MD) {
941 switch (MD->getMetadataID()) {
944 #define HANDLE_MDNODE_LEAF(CLASS) \
947 #include "llvm/IR/Metadata.def"
951 /// \brief Check whether MDNode is a vtable access.
952 bool isTBAAVtableAccess() const;
954 /// \brief Methods for metadata merging.
955 static MDNode *concatenate(MDNode *A, MDNode *B);
956 static MDNode *intersect(MDNode *A, MDNode *B);
957 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
958 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
959 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
960 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
963 /// \brief Tuple of metadata.
965 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
966 /// default based on their operands.
967 class MDTuple : public MDNode {
968 friend class LLVMContextImpl;
971 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
972 ArrayRef<Metadata *> Vals)
973 : MDNode(C, MDTupleKind, Storage, Vals) {
976 ~MDTuple() { dropAllReferences(); }
978 void setHash(unsigned Hash) { SubclassData32 = Hash; }
979 void recalculateHash();
981 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
982 StorageType Storage, bool ShouldCreate = true);
984 TempMDTuple cloneImpl() const {
985 return getTemporary(getContext(),
986 SmallVector<Metadata *, 4>(op_begin(), op_end()));
990 /// \brief Get the hash, if any.
991 unsigned getHash() const { return SubclassData32; }
993 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
994 return getImpl(Context, MDs, Uniqued);
996 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
997 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1000 /// \brief Return a distinct node.
1002 /// Return a distinct node -- i.e., a node that is not uniqued.
1003 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1004 return getImpl(Context, MDs, Distinct);
1007 /// \brief Return a temporary node.
1009 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1010 /// not uniqued, may be RAUW'd, and must be manually deleted with
1011 /// deleteTemporary.
1012 static TempMDTuple getTemporary(LLVMContext &Context,
1013 ArrayRef<Metadata *> MDs) {
1014 return TempMDTuple(getImpl(Context, MDs, Temporary));
1017 /// \brief Return a (temporary) clone of this.
1018 TempMDTuple clone() const { return cloneImpl(); }
1020 static bool classof(const Metadata *MD) {
1021 return MD->getMetadataID() == MDTupleKind;
1025 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1026 return MDTuple::get(Context, MDs);
1028 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1029 return MDTuple::getIfExists(Context, MDs);
1031 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1032 return MDTuple::getDistinct(Context, MDs);
1034 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1035 ArrayRef<Metadata *> MDs) {
1036 return MDTuple::getTemporary(Context, MDs);
1039 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1040 MDNode::deleteTemporary(Node);
1043 /// \brief Typed iterator through MDNode operands.
1045 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1046 /// particular Metadata subclass.
1048 class TypedMDOperandIterator
1049 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1050 MDNode::op_iterator I = nullptr;
1053 TypedMDOperandIterator() = default;
1054 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1055 T *operator*() const { return cast_or_null<T>(*I); }
1056 TypedMDOperandIterator &operator++() {
1060 TypedMDOperandIterator operator++(int) {
1061 TypedMDOperandIterator Temp(*this);
1065 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1066 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1069 /// \brief Typed, array-like tuple of metadata.
1071 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1072 /// particular type of metadata.
1073 template <class T> class MDTupleTypedArrayWrapper {
1074 const MDTuple *N = nullptr;
1077 MDTupleTypedArrayWrapper() = default;
1078 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1081 MDTupleTypedArrayWrapper(
1082 const MDTupleTypedArrayWrapper<U> &Other,
1083 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1088 explicit MDTupleTypedArrayWrapper(
1089 const MDTupleTypedArrayWrapper<U> &Other,
1090 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1094 explicit operator bool() const { return get(); }
1095 explicit operator MDTuple *() const { return get(); }
1097 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1098 MDTuple *operator->() const { return get(); }
1099 MDTuple &operator*() const { return *get(); }
1101 // FIXME: Fix callers and remove condition on N.
1102 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1103 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1105 // FIXME: Fix callers and remove condition on N.
1106 typedef TypedMDOperandIterator<T> iterator;
1107 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1108 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1111 #define HANDLE_METADATA(CLASS) \
1112 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1113 #include "llvm/IR/Metadata.def"
1115 //===----------------------------------------------------------------------===//
1116 /// \brief A tuple of MDNodes.
1118 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1119 /// to modules, have names, and contain lists of MDNodes.
1121 /// TODO: Inherit from Metadata.
1122 class NamedMDNode : public ilist_node<NamedMDNode> {
1123 friend class SymbolTableListTraits<NamedMDNode, Module>;
1124 friend struct ilist_traits<NamedMDNode>;
1125 friend class LLVMContextImpl;
1126 friend class Module;
1127 NamedMDNode(const NamedMDNode &) = delete;
1131 void *Operands; // SmallVector<TrackingMDRef, 4>
1133 void setParent(Module *M) { Parent = M; }
1135 explicit NamedMDNode(const Twine &N);
1137 template<class T1, class T2>
1138 class op_iterator_impl :
1139 public std::iterator<std::bidirectional_iterator_tag, T2> {
1140 const NamedMDNode *Node;
1142 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1144 friend class NamedMDNode;
1147 op_iterator_impl() : Node(nullptr), Idx(0) { }
1149 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1150 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1151 op_iterator_impl &operator++() {
1155 op_iterator_impl operator++(int) {
1156 op_iterator_impl tmp(*this);
1160 op_iterator_impl &operator--() {
1164 op_iterator_impl operator--(int) {
1165 op_iterator_impl tmp(*this);
1170 T1 operator*() const { return Node->getOperand(Idx); }
1174 /// \brief Drop all references and remove the node from parent module.
1175 void eraseFromParent();
1177 /// \brief Remove all uses and clear node vector.
1178 void dropAllReferences();
1182 /// \brief Get the module that holds this named metadata collection.
1183 inline Module *getParent() { return Parent; }
1184 inline const Module *getParent() const { return Parent; }
1186 MDNode *getOperand(unsigned i) const;
1187 unsigned getNumOperands() const;
1188 void addOperand(MDNode *M);
1189 void setOperand(unsigned I, MDNode *New);
1190 StringRef getName() const;
1191 void print(raw_ostream &ROS) const;
1194 // ---------------------------------------------------------------------------
1195 // Operand Iterator interface...
1197 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1198 op_iterator op_begin() { return op_iterator(this, 0); }
1199 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1201 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1202 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1203 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1205 inline iterator_range<op_iterator> operands() {
1206 return iterator_range<op_iterator>(op_begin(), op_end());
1208 inline iterator_range<const_op_iterator> operands() const {
1209 return iterator_range<const_op_iterator>(op_begin(), op_end());
1213 } // end llvm namespace