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/PointerUnion.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Value.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include <type_traits>
34 class ModuleSlotTracker;
36 enum LLVMConstants : uint32_t {
37 DEBUG_METADATA_VERSION = 3 // 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 DILexicalBlockFileKind,
78 DITemplateTypeParameterKind,
79 DITemplateValueParameterKind,
85 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 API for tracking metadata references through RAUW and deletion.
202 /// Shared API for updating \a Metadata pointers in subclasses that support
205 /// This API is not meant to be used directly. See \a TrackingMDRef for a
206 /// user-friendly tracking reference.
207 class MetadataTracking {
209 /// \brief Track the reference to metadata.
211 /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
212 /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
213 /// deleted, \c MD will be set to \c nullptr.
215 /// If tracking isn't supported, \c *MD will not change.
217 /// \return true iff tracking is supported by \c MD.
218 static bool track(Metadata *&MD) {
219 return track(&MD, *MD, static_cast<Metadata *>(nullptr));
222 /// \brief Track the reference to metadata for \a Metadata.
224 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
225 /// tell it that its operand changed. This could trigger \c Owner being
227 static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
228 return track(Ref, MD, &Owner);
231 /// \brief Track the reference to metadata for \a MetadataAsValue.
233 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
234 /// tell it that its operand changed. This could trigger \c Owner being
236 static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
237 return track(Ref, MD, &Owner);
240 /// \brief Stop tracking a reference to metadata.
242 /// Stops \c *MD from tracking \c MD.
243 static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
244 static void untrack(void *Ref, Metadata &MD);
246 /// \brief Move tracking from one reference to another.
248 /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
249 /// except that ownership callbacks are maintained.
251 /// Note: it is an error if \c *MD does not equal \c New.
253 /// \return true iff tracking is supported by \c MD.
254 static bool retrack(Metadata *&MD, Metadata *&New) {
255 return retrack(&MD, *MD, &New);
257 static bool retrack(void *Ref, Metadata &MD, void *New);
259 /// \brief Check whether metadata is replaceable.
260 static bool isReplaceable(const Metadata &MD);
262 typedef PointerUnion<MetadataAsValue *, Metadata *> OwnerTy;
265 /// \brief Track a reference to metadata for an owner.
267 /// Generalized version of tracking.
268 static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
271 /// \brief Shared implementation of use-lists for replaceable metadata.
273 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
274 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
275 /// and \a TempMDNode).
276 class ReplaceableMetadataImpl {
277 friend class MetadataTracking;
280 typedef MetadataTracking::OwnerTy OwnerTy;
283 LLVMContext &Context;
285 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
288 ReplaceableMetadataImpl(LLVMContext &Context)
289 : Context(Context), NextIndex(0) {}
290 ~ReplaceableMetadataImpl() {
291 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
294 LLVMContext &getContext() const { return Context; }
296 /// \brief Replace all uses of this with MD.
298 /// Replace all uses of this with \c MD, which is allowed to be null.
299 void replaceAllUsesWith(Metadata *MD);
301 /// \brief Resolve all uses of this.
303 /// Resolve all uses of this, turning off RAUW permanently. If \c
304 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
306 void resolveAllUses(bool ResolveUsers = true);
309 void addRef(void *Ref, OwnerTy Owner);
310 void dropRef(void *Ref);
311 void moveRef(void *Ref, void *New, const Metadata &MD);
313 static ReplaceableMetadataImpl *get(Metadata &MD);
316 /// \brief Value wrapper in the Metadata hierarchy.
318 /// This is a custom value handle that allows other metadata to refer to
319 /// classes in the Value hierarchy.
321 /// Because of full uniquing support, each value is only wrapped by a single \a
322 /// ValueAsMetadata object, so the lookup maps are far more efficient than
323 /// those using ValueHandleBase.
324 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
325 friend class ReplaceableMetadataImpl;
326 friend class LLVMContextImpl;
330 /// \brief Drop users without RAUW (during teardown).
332 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
336 ValueAsMetadata(unsigned ID, Value *V)
337 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
338 assert(V && "Expected valid value");
340 ~ValueAsMetadata() = default;
343 static ValueAsMetadata *get(Value *V);
344 static ConstantAsMetadata *getConstant(Value *C) {
345 return cast<ConstantAsMetadata>(get(C));
347 static LocalAsMetadata *getLocal(Value *Local) {
348 return cast<LocalAsMetadata>(get(Local));
351 static ValueAsMetadata *getIfExists(Value *V);
352 static ConstantAsMetadata *getConstantIfExists(Value *C) {
353 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
355 static LocalAsMetadata *getLocalIfExists(Value *Local) {
356 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
359 Value *getValue() const { return V; }
360 Type *getType() const { return V->getType(); }
361 LLVMContext &getContext() const { return V->getContext(); }
363 static void handleDeletion(Value *V);
364 static void handleRAUW(Value *From, Value *To);
367 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
369 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
370 /// \a Value gets RAUW'ed and the target already exists, this is used to
371 /// merge the two metadata nodes.
372 void replaceAllUsesWith(Metadata *MD) {
373 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
377 static bool classof(const Metadata *MD) {
378 return MD->getMetadataID() == LocalAsMetadataKind ||
379 MD->getMetadataID() == ConstantAsMetadataKind;
383 class ConstantAsMetadata : public ValueAsMetadata {
384 friend class ValueAsMetadata;
386 ConstantAsMetadata(Constant *C)
387 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
390 static ConstantAsMetadata *get(Constant *C) {
391 return ValueAsMetadata::getConstant(C);
393 static ConstantAsMetadata *getIfExists(Constant *C) {
394 return ValueAsMetadata::getConstantIfExists(C);
397 Constant *getValue() const {
398 return cast<Constant>(ValueAsMetadata::getValue());
401 static bool classof(const Metadata *MD) {
402 return MD->getMetadataID() == ConstantAsMetadataKind;
406 class LocalAsMetadata : public ValueAsMetadata {
407 friend class ValueAsMetadata;
409 LocalAsMetadata(Value *Local)
410 : ValueAsMetadata(LocalAsMetadataKind, Local) {
411 assert(!isa<Constant>(Local) && "Expected local value");
415 static LocalAsMetadata *get(Value *Local) {
416 return ValueAsMetadata::getLocal(Local);
418 static LocalAsMetadata *getIfExists(Value *Local) {
419 return ValueAsMetadata::getLocalIfExists(Local);
422 static bool classof(const Metadata *MD) {
423 return MD->getMetadataID() == LocalAsMetadataKind;
427 /// \brief Transitional API for extracting constants from Metadata.
429 /// This namespace contains transitional functions for metadata that points to
432 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
433 /// operands could refer to any \a Value. There's was a lot of code like this:
437 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
440 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
441 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
442 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
443 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
444 /// requires subtle control flow changes.
446 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
447 /// so that metadata can refer to numbers without traversing a bridge to the \a
448 /// Value hierarchy. In this final state, the code above would look like this:
452 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
455 /// The API in this namespace supports the transition. \a MDInt doesn't exist
456 /// yet, and even once it does, changing each metadata schema to use it is its
457 /// own mini-project. In the meantime this API prevents us from introducing
458 /// complex and bug-prone control flow that will disappear in the end. In
459 /// particular, the above code looks like this:
463 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
466 /// The full set of provided functions includes:
468 /// mdconst::hasa <=> isa
469 /// mdconst::extract <=> cast
470 /// mdconst::extract_or_null <=> cast_or_null
471 /// mdconst::dyn_extract <=> dyn_cast
472 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
474 /// The target of the cast must be a subclass of \a Constant.
478 template <class T> T &make();
479 template <class T, class Result> struct HasDereference {
482 template <size_t N> struct SFINAE {};
484 template <class U, class V>
485 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
486 template <class U, class V> static No &hasDereference(...);
488 static const bool value =
489 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
491 template <class V, class M> struct IsValidPointer {
492 static const bool value = std::is_base_of<Constant, V>::value &&
493 HasDereference<M, const Metadata &>::value;
495 template <class V, class M> struct IsValidReference {
496 static const bool value = std::is_base_of<Constant, V>::value &&
497 std::is_convertible<M, const Metadata &>::value;
499 } // end namespace detail
501 /// \brief Check whether Metadata has a Value.
503 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
505 template <class X, class Y>
506 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
508 assert(MD && "Null pointer sent into hasa");
509 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
510 return isa<X>(V->getValue());
513 template <class X, class Y>
515 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
520 /// \brief Extract a Value from Metadata.
522 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
523 template <class X, class Y>
524 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
526 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
528 template <class X, class Y>
530 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
535 /// \brief Extract a Value from Metadata, allowing null.
537 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
538 /// from \c MD, allowing \c MD to be null.
539 template <class X, class Y>
540 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
541 extract_or_null(Y &&MD) {
542 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
543 return cast<X>(V->getValue());
547 /// \brief Extract a Value from Metadata, if any.
549 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
550 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
551 /// Value it does contain is of the wrong subclass.
552 template <class X, class Y>
553 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
554 dyn_extract(Y &&MD) {
555 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
556 return dyn_cast<X>(V->getValue());
560 /// \brief Extract a Value from Metadata, if any, allowing null.
562 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
563 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
564 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
565 template <class X, class Y>
566 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
567 dyn_extract_or_null(Y &&MD) {
568 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
569 return dyn_cast<X>(V->getValue());
573 } // end namespace mdconst
575 //===----------------------------------------------------------------------===//
576 /// \brief A single uniqued string.
578 /// These are used to efficiently contain a byte sequence for metadata.
579 /// MDString is always unnamed.
580 class MDString : public Metadata {
581 friend class StringMapEntry<MDString>;
583 MDString(const MDString &) = delete;
584 MDString &operator=(MDString &&) = delete;
585 MDString &operator=(const MDString &) = delete;
587 StringMapEntry<MDString> *Entry;
588 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
589 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
592 static MDString *get(LLVMContext &Context, StringRef Str);
593 static MDString *get(LLVMContext &Context, const char *Str) {
594 return get(Context, Str ? StringRef(Str) : StringRef());
597 StringRef getString() const;
599 unsigned getLength() const { return (unsigned)getString().size(); }
601 typedef StringRef::iterator iterator;
603 /// \brief Pointer to the first byte of the string.
604 iterator begin() const { return getString().begin(); }
606 /// \brief Pointer to one byte past the end of the string.
607 iterator end() const { return getString().end(); }
609 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
610 const unsigned char *bytes_end() const { return getString().bytes_end(); }
612 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
613 static bool classof(const Metadata *MD) {
614 return MD->getMetadataID() == MDStringKind;
618 /// \brief A collection of metadata nodes that might be associated with a
619 /// memory access used by the alias-analysis infrastructure.
621 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
623 : TBAA(T), Scope(S), NoAlias(N) {}
625 bool operator==(const AAMDNodes &A) const {
626 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
629 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
631 explicit operator bool() const { return TBAA || Scope || NoAlias; }
633 /// \brief The tag for type-based alias analysis.
636 /// \brief The tag for alias scope specification (used with noalias).
639 /// \brief The tag specifying the noalias scope.
643 // Specialize DenseMapInfo for AAMDNodes.
645 struct DenseMapInfo<AAMDNodes> {
646 static inline AAMDNodes getEmptyKey() {
647 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
650 static inline AAMDNodes getTombstoneKey() {
651 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
654 static unsigned getHashValue(const AAMDNodes &Val) {
655 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
656 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
657 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
659 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
664 /// \brief Tracking metadata reference owned by Metadata.
666 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
667 /// of \a Metadata, which has the option of registering itself for callbacks to
668 /// re-unique itself.
670 /// In particular, this is used by \a MDNode.
672 MDOperand(MDOperand &&) = delete;
673 MDOperand(const MDOperand &) = delete;
674 MDOperand &operator=(MDOperand &&) = delete;
675 MDOperand &operator=(const MDOperand &) = delete;
680 MDOperand() : MD(nullptr) {}
681 ~MDOperand() { untrack(); }
683 Metadata *get() const { return MD; }
684 operator Metadata *() const { return get(); }
685 Metadata *operator->() const { return get(); }
686 Metadata &operator*() const { return *get(); }
692 void reset(Metadata *MD, Metadata *Owner) {
699 void track(Metadata *Owner) {
702 MetadataTracking::track(this, *MD, *Owner);
704 MetadataTracking::track(MD);
708 assert(static_cast<void *>(this) == &MD && "Expected same address");
710 MetadataTracking::untrack(MD);
714 template <> struct simplify_type<MDOperand> {
715 typedef Metadata *SimpleType;
716 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
719 template <> struct simplify_type<const MDOperand> {
720 typedef Metadata *SimpleType;
721 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
724 /// \brief Pointer to the context, with optional RAUW support.
726 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
727 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
728 class ContextAndReplaceableUses {
729 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
731 ContextAndReplaceableUses() = delete;
732 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
733 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
734 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
735 ContextAndReplaceableUses &
736 operator=(const ContextAndReplaceableUses &) = delete;
739 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
740 ContextAndReplaceableUses(
741 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
742 : Ptr(ReplaceableUses.release()) {
743 assert(getReplaceableUses() && "Expected non-null replaceable uses");
745 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
747 operator LLVMContext &() { return getContext(); }
749 /// \brief Whether this contains RAUW support.
750 bool hasReplaceableUses() const {
751 return Ptr.is<ReplaceableMetadataImpl *>();
753 LLVMContext &getContext() const {
754 if (hasReplaceableUses())
755 return getReplaceableUses()->getContext();
756 return *Ptr.get<LLVMContext *>();
758 ReplaceableMetadataImpl *getReplaceableUses() const {
759 if (hasReplaceableUses())
760 return Ptr.get<ReplaceableMetadataImpl *>();
764 /// \brief Assign RAUW support to this.
766 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
769 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
770 assert(ReplaceableUses && "Expected non-null replaceable uses");
771 assert(&ReplaceableUses->getContext() == &getContext() &&
772 "Expected same context");
773 delete getReplaceableUses();
774 Ptr = ReplaceableUses.release();
777 /// \brief Drop RAUW support.
779 /// Cede ownership of RAUW support, returning it.
780 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
781 assert(hasReplaceableUses() && "Expected to own replaceable uses");
782 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
783 getReplaceableUses());
784 Ptr = &ReplaceableUses->getContext();
785 return ReplaceableUses;
789 struct TempMDNodeDeleter {
790 inline void operator()(MDNode *Node) const;
793 #define HANDLE_MDNODE_LEAF(CLASS) \
794 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
795 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
796 #include "llvm/IR/Metadata.def"
798 /// \brief Metadata node.
800 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
801 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
802 /// until forward references are known. The basic metadata node is an \a
805 /// There is limited support for RAUW at construction time. At construction
806 /// time, if any operand is a temporary node (or an unresolved uniqued node,
807 /// which indicates a transitive temporary operand), the node itself will be
808 /// unresolved. As soon as all operands become resolved, it will drop RAUW
809 /// support permanently.
811 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
812 /// to be called on some member of the cycle once all temporary nodes have been
814 class MDNode : public Metadata {
815 friend class ReplaceableMetadataImpl;
816 friend class LLVMContextImpl;
818 MDNode(const MDNode &) = delete;
819 void operator=(const MDNode &) = delete;
820 void *operator new(size_t) = delete;
822 unsigned NumOperands;
823 unsigned NumUnresolved;
826 ContextAndReplaceableUses Context;
828 void *operator new(size_t Size, unsigned NumOps);
829 void operator delete(void *Mem);
831 /// \brief Required by std, but never called.
832 void operator delete(void *, unsigned) {
833 llvm_unreachable("Constructor throws?");
836 /// \brief Required by std, but never called.
837 void operator delete(void *, unsigned, bool) {
838 llvm_unreachable("Constructor throws?");
841 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
842 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
845 void dropAllReferences();
847 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
848 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
850 typedef iterator_range<MDOperand *> mutable_op_range;
851 mutable_op_range mutable_operands() {
852 return mutable_op_range(mutable_begin(), mutable_end());
856 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
857 static inline MDTuple *getIfExists(LLVMContext &Context,
858 ArrayRef<Metadata *> MDs);
859 static inline MDTuple *getDistinct(LLVMContext &Context,
860 ArrayRef<Metadata *> MDs);
861 static inline TempMDTuple getTemporary(LLVMContext &Context,
862 ArrayRef<Metadata *> MDs);
864 /// \brief Create a (temporary) clone of this.
865 TempMDNode clone() const;
867 /// \brief Deallocate a node created by getTemporary.
869 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
870 /// references will be reset.
871 static void deleteTemporary(MDNode *N);
873 LLVMContext &getContext() const { return Context.getContext(); }
875 /// \brief Replace a specific operand.
876 void replaceOperandWith(unsigned I, Metadata *New);
878 /// \brief Check if node is fully resolved.
880 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
881 /// this always returns \c true.
883 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
884 /// support (because all operands are resolved).
886 /// As forward declarations are resolved, their containers should get
887 /// resolved automatically. However, if this (or one of its operands) is
888 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
889 bool isResolved() const { return !Context.hasReplaceableUses(); }
891 bool isUniqued() const { return Storage == Uniqued; }
892 bool isDistinct() const { return Storage == Distinct; }
893 bool isTemporary() const { return Storage == Temporary; }
895 /// \brief RAUW a temporary.
897 /// \pre \a isTemporary() must be \c true.
898 void replaceAllUsesWith(Metadata *MD) {
899 assert(isTemporary() && "Expected temporary node");
900 assert(!isResolved() && "Expected RAUW support");
901 Context.getReplaceableUses()->replaceAllUsesWith(MD);
904 /// \brief Resolve cycles.
906 /// Once all forward declarations have been resolved, force cycles to be
907 /// resolved. If \p MDMaterialized is true, then any temporary metadata
908 /// is ignored, otherwise it asserts when encountering temporary metadata.
910 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
911 void resolveCycles(bool MDMaterialized = true);
913 /// \brief Replace a temporary node with a permanent one.
915 /// Try to create a uniqued version of \c N -- in place, if possible -- and
916 /// return it. If \c N cannot be uniqued, return a distinct node instead.
918 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
919 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
920 return cast<T>(N.release()->replaceWithPermanentImpl());
923 /// \brief Replace a temporary node with a uniqued one.
925 /// Create a uniqued version of \c N -- in place, if possible -- and return
926 /// it. Takes ownership of the temporary node.
928 /// \pre N does not self-reference.
930 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
931 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
932 return cast<T>(N.release()->replaceWithUniquedImpl());
935 /// \brief Replace a temporary node with a distinct one.
937 /// Create a distinct version of \c N -- in place, if possible -- and return
938 /// it. Takes ownership of the temporary node.
940 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
941 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
942 return cast<T>(N.release()->replaceWithDistinctImpl());
946 MDNode *replaceWithPermanentImpl();
947 MDNode *replaceWithUniquedImpl();
948 MDNode *replaceWithDistinctImpl();
951 /// \brief Set an operand.
953 /// Sets the operand directly, without worrying about uniquing.
954 void setOperand(unsigned I, Metadata *New);
956 void storeDistinctInContext();
957 template <class T, class StoreT>
958 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
959 template <class T> static T *storeImpl(T *N, StorageType Storage);
962 void handleChangedOperand(void *Ref, Metadata *New);
965 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
966 void decrementUnresolvedOperandCount();
967 unsigned countUnresolvedOperands();
969 /// \brief Mutate this to be "uniqued".
971 /// Mutate this so that \a isUniqued().
972 /// \pre \a isTemporary().
973 /// \pre already added to uniquing set.
976 /// \brief Mutate this to be "distinct".
978 /// Mutate this so that \a isDistinct().
979 /// \pre \a isTemporary().
982 void deleteAsSubclass();
984 void eraseFromStore();
986 template <class NodeTy> struct HasCachedHash;
987 template <class NodeTy>
988 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
989 N->recalculateHash();
991 template <class NodeTy>
992 static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
993 template <class NodeTy>
994 static void dispatchResetHash(NodeTy *N, std::true_type) {
997 template <class NodeTy>
998 static void dispatchResetHash(NodeTy *, std::false_type) {}
1001 typedef const MDOperand *op_iterator;
1002 typedef iterator_range<op_iterator> op_range;
1004 op_iterator op_begin() const {
1005 return const_cast<MDNode *>(this)->mutable_begin();
1007 op_iterator op_end() const {
1008 return const_cast<MDNode *>(this)->mutable_end();
1010 op_range operands() const { return op_range(op_begin(), op_end()); }
1012 const MDOperand &getOperand(unsigned I) const {
1013 assert(I < NumOperands && "Out of range");
1014 return op_begin()[I];
1017 /// \brief Return number of MDNode operands.
1018 unsigned getNumOperands() const { return NumOperands; }
1020 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1021 static bool classof(const Metadata *MD) {
1022 switch (MD->getMetadataID()) {
1025 #define HANDLE_MDNODE_LEAF(CLASS) \
1028 #include "llvm/IR/Metadata.def"
1032 /// \brief Check whether MDNode is a vtable access.
1033 bool isTBAAVtableAccess() const;
1035 /// \brief Methods for metadata merging.
1036 static MDNode *concatenate(MDNode *A, MDNode *B);
1037 static MDNode *intersect(MDNode *A, MDNode *B);
1038 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1039 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1040 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1041 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1042 static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1046 /// \brief Tuple of metadata.
1048 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1049 /// default based on their operands.
1050 class MDTuple : public MDNode {
1051 friend class LLVMContextImpl;
1052 friend class MDNode;
1054 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1055 ArrayRef<Metadata *> Vals)
1056 : MDNode(C, MDTupleKind, Storage, Vals) {
1059 ~MDTuple() { dropAllReferences(); }
1061 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1062 void recalculateHash();
1064 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1065 StorageType Storage, bool ShouldCreate = true);
1067 TempMDTuple cloneImpl() const {
1068 return getTemporary(getContext(),
1069 SmallVector<Metadata *, 4>(op_begin(), op_end()));
1073 /// \brief Get the hash, if any.
1074 unsigned getHash() const { return SubclassData32; }
1076 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1077 return getImpl(Context, MDs, Uniqued);
1079 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1080 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1083 /// \brief Return a distinct node.
1085 /// Return a distinct node -- i.e., a node that is not uniqued.
1086 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1087 return getImpl(Context, MDs, Distinct);
1090 /// \brief Return a temporary node.
1092 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1093 /// not uniqued, may be RAUW'd, and must be manually deleted with
1094 /// deleteTemporary.
1095 static TempMDTuple getTemporary(LLVMContext &Context,
1096 ArrayRef<Metadata *> MDs) {
1097 return TempMDTuple(getImpl(Context, MDs, Temporary));
1100 /// \brief Return a (temporary) clone of this.
1101 TempMDTuple clone() const { return cloneImpl(); }
1103 static bool classof(const Metadata *MD) {
1104 return MD->getMetadataID() == MDTupleKind;
1108 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1109 return MDTuple::get(Context, MDs);
1111 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1112 return MDTuple::getIfExists(Context, MDs);
1114 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1115 return MDTuple::getDistinct(Context, MDs);
1117 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1118 ArrayRef<Metadata *> MDs) {
1119 return MDTuple::getTemporary(Context, MDs);
1122 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1123 MDNode::deleteTemporary(Node);
1126 /// \brief Typed iterator through MDNode operands.
1128 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1129 /// particular Metadata subclass.
1131 class TypedMDOperandIterator
1132 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1133 MDNode::op_iterator I = nullptr;
1136 TypedMDOperandIterator() = default;
1137 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1138 T *operator*() const { return cast_or_null<T>(*I); }
1139 TypedMDOperandIterator &operator++() {
1143 TypedMDOperandIterator operator++(int) {
1144 TypedMDOperandIterator Temp(*this);
1148 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1149 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1152 /// \brief Typed, array-like tuple of metadata.
1154 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1155 /// particular type of metadata.
1156 template <class T> class MDTupleTypedArrayWrapper {
1157 const MDTuple *N = nullptr;
1160 MDTupleTypedArrayWrapper() = default;
1161 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1164 MDTupleTypedArrayWrapper(
1165 const MDTupleTypedArrayWrapper<U> &Other,
1166 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1171 explicit MDTupleTypedArrayWrapper(
1172 const MDTupleTypedArrayWrapper<U> &Other,
1173 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1177 explicit operator bool() const { return get(); }
1178 explicit operator MDTuple *() const { return get(); }
1180 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1181 MDTuple *operator->() const { return get(); }
1182 MDTuple &operator*() const { return *get(); }
1184 // FIXME: Fix callers and remove condition on N.
1185 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1186 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1188 // FIXME: Fix callers and remove condition on N.
1189 typedef TypedMDOperandIterator<T> iterator;
1190 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1191 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1194 #define HANDLE_METADATA(CLASS) \
1195 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1196 #include "llvm/IR/Metadata.def"
1198 //===----------------------------------------------------------------------===//
1199 /// \brief A tuple of MDNodes.
1201 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1202 /// to modules, have names, and contain lists of MDNodes.
1204 /// TODO: Inherit from Metadata.
1205 class NamedMDNode : public ilist_node<NamedMDNode> {
1206 friend struct ilist_traits<NamedMDNode>;
1207 friend class LLVMContextImpl;
1208 friend class Module;
1209 NamedMDNode(const NamedMDNode &) = delete;
1213 void *Operands; // SmallVector<TrackingMDRef, 4>
1215 void setParent(Module *M) { Parent = M; }
1217 explicit NamedMDNode(const Twine &N);
1219 template<class T1, class T2>
1220 class op_iterator_impl :
1221 public std::iterator<std::bidirectional_iterator_tag, T2> {
1222 const NamedMDNode *Node;
1224 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1226 friend class NamedMDNode;
1229 op_iterator_impl() : Node(nullptr), Idx(0) { }
1231 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1232 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1233 op_iterator_impl &operator++() {
1237 op_iterator_impl operator++(int) {
1238 op_iterator_impl tmp(*this);
1242 op_iterator_impl &operator--() {
1246 op_iterator_impl operator--(int) {
1247 op_iterator_impl tmp(*this);
1252 T1 operator*() const { return Node->getOperand(Idx); }
1256 /// \brief Drop all references and remove the node from parent module.
1257 void eraseFromParent();
1259 /// \brief Remove all uses and clear node vector.
1260 void dropAllReferences();
1264 /// \brief Get the module that holds this named metadata collection.
1265 inline Module *getParent() { return Parent; }
1266 inline const Module *getParent() const { return Parent; }
1268 MDNode *getOperand(unsigned i) const;
1269 unsigned getNumOperands() const;
1270 void addOperand(MDNode *M);
1271 void setOperand(unsigned I, MDNode *New);
1272 StringRef getName() const;
1273 void print(raw_ostream &ROS, bool IsForDebug = false) const;
1276 // ---------------------------------------------------------------------------
1277 // Operand Iterator interface...
1279 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1280 op_iterator op_begin() { return op_iterator(this, 0); }
1281 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1283 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1284 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1285 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1287 inline iterator_range<op_iterator> operands() {
1288 return make_range(op_begin(), op_end());
1290 inline iterator_range<const_op_iterator> operands() const {
1291 return make_range(op_begin(), op_end());
1295 } // end llvm namespace
1297 #endif // LLVM_IR_METADATA_H