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;
286 /// Flag that can be set to false if this metadata should not be
287 /// RAUW'ed, e.g. if it is used as the key of a map.
291 ReplaceableMetadataImpl(LLVMContext &Context)
292 : Context(Context), NextIndex(0), CanReplace(true) {}
293 ~ReplaceableMetadataImpl() {
294 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
297 /// Set the CanReplace flag to the given value.
298 void setCanReplace(bool Replaceable) { CanReplace = Replaceable; }
300 LLVMContext &getContext() const { return Context; }
302 /// \brief Replace all uses of this with MD.
304 /// Replace all uses of this with \c MD, which is allowed to be null.
305 void replaceAllUsesWith(Metadata *MD);
307 /// \brief Resolve all uses of this.
309 /// Resolve all uses of this, turning off RAUW permanently. If \c
310 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
312 void resolveAllUses(bool ResolveUsers = true);
315 void addRef(void *Ref, OwnerTy Owner);
316 void dropRef(void *Ref);
317 void moveRef(void *Ref, void *New, const Metadata &MD);
319 static ReplaceableMetadataImpl *get(Metadata &MD);
322 /// \brief Value wrapper in the Metadata hierarchy.
324 /// This is a custom value handle that allows other metadata to refer to
325 /// classes in the Value hierarchy.
327 /// Because of full uniquing support, each value is only wrapped by a single \a
328 /// ValueAsMetadata object, so the lookup maps are far more efficient than
329 /// those using ValueHandleBase.
330 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
331 friend class ReplaceableMetadataImpl;
332 friend class LLVMContextImpl;
336 /// \brief Drop users without RAUW (during teardown).
338 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
342 ValueAsMetadata(unsigned ID, Value *V)
343 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
344 assert(V && "Expected valid value");
346 ~ValueAsMetadata() = default;
349 static ValueAsMetadata *get(Value *V);
350 static ConstantAsMetadata *getConstant(Value *C) {
351 return cast<ConstantAsMetadata>(get(C));
353 static LocalAsMetadata *getLocal(Value *Local) {
354 return cast<LocalAsMetadata>(get(Local));
357 static ValueAsMetadata *getIfExists(Value *V);
358 static ConstantAsMetadata *getConstantIfExists(Value *C) {
359 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
361 static LocalAsMetadata *getLocalIfExists(Value *Local) {
362 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
365 Value *getValue() const { return V; }
366 Type *getType() const { return V->getType(); }
367 LLVMContext &getContext() const { return V->getContext(); }
369 static void handleDeletion(Value *V);
370 static void handleRAUW(Value *From, Value *To);
373 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
375 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
376 /// \a Value gets RAUW'ed and the target already exists, this is used to
377 /// merge the two metadata nodes.
378 void replaceAllUsesWith(Metadata *MD) {
379 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
383 static bool classof(const Metadata *MD) {
384 return MD->getMetadataID() == LocalAsMetadataKind ||
385 MD->getMetadataID() == ConstantAsMetadataKind;
389 class ConstantAsMetadata : public ValueAsMetadata {
390 friend class ValueAsMetadata;
392 ConstantAsMetadata(Constant *C)
393 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
396 static ConstantAsMetadata *get(Constant *C) {
397 return ValueAsMetadata::getConstant(C);
399 static ConstantAsMetadata *getIfExists(Constant *C) {
400 return ValueAsMetadata::getConstantIfExists(C);
403 Constant *getValue() const {
404 return cast<Constant>(ValueAsMetadata::getValue());
407 static bool classof(const Metadata *MD) {
408 return MD->getMetadataID() == ConstantAsMetadataKind;
412 class LocalAsMetadata : public ValueAsMetadata {
413 friend class ValueAsMetadata;
415 LocalAsMetadata(Value *Local)
416 : ValueAsMetadata(LocalAsMetadataKind, Local) {
417 assert(!isa<Constant>(Local) && "Expected local value");
421 static LocalAsMetadata *get(Value *Local) {
422 return ValueAsMetadata::getLocal(Local);
424 static LocalAsMetadata *getIfExists(Value *Local) {
425 return ValueAsMetadata::getLocalIfExists(Local);
428 static bool classof(const Metadata *MD) {
429 return MD->getMetadataID() == LocalAsMetadataKind;
433 /// \brief Transitional API for extracting constants from Metadata.
435 /// This namespace contains transitional functions for metadata that points to
438 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
439 /// operands could refer to any \a Value. There's was a lot of code like this:
443 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
446 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
447 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
448 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
449 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
450 /// requires subtle control flow changes.
452 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
453 /// so that metadata can refer to numbers without traversing a bridge to the \a
454 /// Value hierarchy. In this final state, the code above would look like this:
458 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
461 /// The API in this namespace supports the transition. \a MDInt doesn't exist
462 /// yet, and even once it does, changing each metadata schema to use it is its
463 /// own mini-project. In the meantime this API prevents us from introducing
464 /// complex and bug-prone control flow that will disappear in the end. In
465 /// particular, the above code looks like this:
469 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
472 /// The full set of provided functions includes:
474 /// mdconst::hasa <=> isa
475 /// mdconst::extract <=> cast
476 /// mdconst::extract_or_null <=> cast_or_null
477 /// mdconst::dyn_extract <=> dyn_cast
478 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
480 /// The target of the cast must be a subclass of \a Constant.
484 template <class T> T &make();
485 template <class T, class Result> struct HasDereference {
488 template <size_t N> struct SFINAE {};
490 template <class U, class V>
491 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
492 template <class U, class V> static No &hasDereference(...);
494 static const bool value =
495 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
497 template <class V, class M> struct IsValidPointer {
498 static const bool value = std::is_base_of<Constant, V>::value &&
499 HasDereference<M, const Metadata &>::value;
501 template <class V, class M> struct IsValidReference {
502 static const bool value = std::is_base_of<Constant, V>::value &&
503 std::is_convertible<M, const Metadata &>::value;
505 } // end namespace detail
507 /// \brief Check whether Metadata has a Value.
509 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
511 template <class X, class Y>
512 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
514 assert(MD && "Null pointer sent into hasa");
515 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
516 return isa<X>(V->getValue());
519 template <class X, class Y>
521 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
526 /// \brief Extract a Value from Metadata.
528 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
529 template <class X, class Y>
530 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
532 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
534 template <class X, class Y>
536 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
541 /// \brief Extract a Value from Metadata, allowing null.
543 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
544 /// from \c MD, allowing \c MD to be null.
545 template <class X, class Y>
546 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
547 extract_or_null(Y &&MD) {
548 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
549 return cast<X>(V->getValue());
553 /// \brief Extract a Value from Metadata, if any.
555 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
556 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
557 /// Value it does contain is of the wrong subclass.
558 template <class X, class Y>
559 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
560 dyn_extract(Y &&MD) {
561 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
562 return dyn_cast<X>(V->getValue());
566 /// \brief Extract a Value from Metadata, if any, allowing null.
568 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
569 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
570 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
571 template <class X, class Y>
572 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
573 dyn_extract_or_null(Y &&MD) {
574 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
575 return dyn_cast<X>(V->getValue());
579 } // end namespace mdconst
581 //===----------------------------------------------------------------------===//
582 /// \brief A single uniqued string.
584 /// These are used to efficiently contain a byte sequence for metadata.
585 /// MDString is always unnamed.
586 class MDString : public Metadata {
587 friend class StringMapEntry<MDString>;
589 MDString(const MDString &) = delete;
590 MDString &operator=(MDString &&) = delete;
591 MDString &operator=(const MDString &) = delete;
593 StringMapEntry<MDString> *Entry;
594 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
595 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
598 static MDString *get(LLVMContext &Context, StringRef Str);
599 static MDString *get(LLVMContext &Context, const char *Str) {
600 return get(Context, Str ? StringRef(Str) : StringRef());
603 StringRef getString() const;
605 unsigned getLength() const { return (unsigned)getString().size(); }
607 typedef StringRef::iterator iterator;
609 /// \brief Pointer to the first byte of the string.
610 iterator begin() const { return getString().begin(); }
612 /// \brief Pointer to one byte past the end of the string.
613 iterator end() const { return getString().end(); }
615 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
616 const unsigned char *bytes_end() const { return getString().bytes_end(); }
618 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
619 static bool classof(const Metadata *MD) {
620 return MD->getMetadataID() == MDStringKind;
624 /// \brief A collection of metadata nodes that might be associated with a
625 /// memory access used by the alias-analysis infrastructure.
627 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
629 : TBAA(T), Scope(S), NoAlias(N) {}
631 bool operator==(const AAMDNodes &A) const {
632 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
635 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
637 explicit operator bool() const { return TBAA || Scope || NoAlias; }
639 /// \brief The tag for type-based alias analysis.
642 /// \brief The tag for alias scope specification (used with noalias).
645 /// \brief The tag specifying the noalias scope.
649 // Specialize DenseMapInfo for AAMDNodes.
651 struct DenseMapInfo<AAMDNodes> {
652 static inline AAMDNodes getEmptyKey() {
653 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
656 static inline AAMDNodes getTombstoneKey() {
657 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
660 static unsigned getHashValue(const AAMDNodes &Val) {
661 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
662 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
663 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
665 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
670 /// \brief Tracking metadata reference owned by Metadata.
672 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
673 /// of \a Metadata, which has the option of registering itself for callbacks to
674 /// re-unique itself.
676 /// In particular, this is used by \a MDNode.
678 MDOperand(MDOperand &&) = delete;
679 MDOperand(const MDOperand &) = delete;
680 MDOperand &operator=(MDOperand &&) = delete;
681 MDOperand &operator=(const MDOperand &) = delete;
686 MDOperand() : MD(nullptr) {}
687 ~MDOperand() { untrack(); }
689 Metadata *get() const { return MD; }
690 operator Metadata *() const { return get(); }
691 Metadata *operator->() const { return get(); }
692 Metadata &operator*() const { return *get(); }
698 void reset(Metadata *MD, Metadata *Owner) {
705 void track(Metadata *Owner) {
708 MetadataTracking::track(this, *MD, *Owner);
710 MetadataTracking::track(MD);
714 assert(static_cast<void *>(this) == &MD && "Expected same address");
716 MetadataTracking::untrack(MD);
720 template <> struct simplify_type<MDOperand> {
721 typedef Metadata *SimpleType;
722 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
725 template <> struct simplify_type<const MDOperand> {
726 typedef Metadata *SimpleType;
727 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
730 /// \brief Pointer to the context, with optional RAUW support.
732 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
733 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
734 class ContextAndReplaceableUses {
735 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
737 ContextAndReplaceableUses() = delete;
738 ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
739 ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
740 ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
741 ContextAndReplaceableUses &
742 operator=(const ContextAndReplaceableUses &) = delete;
745 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
746 ContextAndReplaceableUses(
747 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
748 : Ptr(ReplaceableUses.release()) {
749 assert(getReplaceableUses() && "Expected non-null replaceable uses");
751 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
753 operator LLVMContext &() { return getContext(); }
755 /// \brief Whether this contains RAUW support.
756 bool hasReplaceableUses() const {
757 return Ptr.is<ReplaceableMetadataImpl *>();
759 LLVMContext &getContext() const {
760 if (hasReplaceableUses())
761 return getReplaceableUses()->getContext();
762 return *Ptr.get<LLVMContext *>();
764 ReplaceableMetadataImpl *getReplaceableUses() const {
765 if (hasReplaceableUses())
766 return Ptr.get<ReplaceableMetadataImpl *>();
770 /// \brief Assign RAUW support to this.
772 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
775 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
776 assert(ReplaceableUses && "Expected non-null replaceable uses");
777 assert(&ReplaceableUses->getContext() == &getContext() &&
778 "Expected same context");
779 delete getReplaceableUses();
780 Ptr = ReplaceableUses.release();
783 /// \brief Drop RAUW support.
785 /// Cede ownership of RAUW support, returning it.
786 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
787 assert(hasReplaceableUses() && "Expected to own replaceable uses");
788 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
789 getReplaceableUses());
790 Ptr = &ReplaceableUses->getContext();
791 return ReplaceableUses;
795 struct TempMDNodeDeleter {
796 inline void operator()(MDNode *Node) const;
799 #define HANDLE_MDNODE_LEAF(CLASS) \
800 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
801 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
802 #include "llvm/IR/Metadata.def"
804 /// \brief Metadata node.
806 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
807 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
808 /// until forward references are known. The basic metadata node is an \a
811 /// There is limited support for RAUW at construction time. At construction
812 /// time, if any operand is a temporary node (or an unresolved uniqued node,
813 /// which indicates a transitive temporary operand), the node itself will be
814 /// unresolved. As soon as all operands become resolved, it will drop RAUW
815 /// support permanently.
817 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
818 /// to be called on some member of the cycle once all temporary nodes have been
820 class MDNode : public Metadata {
821 friend class ReplaceableMetadataImpl;
822 friend class LLVMContextImpl;
824 MDNode(const MDNode &) = delete;
825 void operator=(const MDNode &) = delete;
826 void *operator new(size_t) = delete;
828 unsigned NumOperands;
829 unsigned NumUnresolved;
832 ContextAndReplaceableUses Context;
834 void *operator new(size_t Size, unsigned NumOps);
835 void operator delete(void *Mem);
837 /// \brief Required by std, but never called.
838 void operator delete(void *, unsigned) {
839 llvm_unreachable("Constructor throws?");
842 /// \brief Required by std, but never called.
843 void operator delete(void *, unsigned, bool) {
844 llvm_unreachable("Constructor throws?");
847 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
848 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
851 void dropAllReferences();
853 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
854 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
856 typedef iterator_range<MDOperand *> mutable_op_range;
857 mutable_op_range mutable_operands() {
858 return mutable_op_range(mutable_begin(), mutable_end());
862 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
863 static inline MDTuple *getIfExists(LLVMContext &Context,
864 ArrayRef<Metadata *> MDs);
865 static inline MDTuple *getDistinct(LLVMContext &Context,
866 ArrayRef<Metadata *> MDs);
867 static inline TempMDTuple getTemporary(LLVMContext &Context,
868 ArrayRef<Metadata *> MDs);
870 /// \brief Create a (temporary) clone of this.
871 TempMDNode clone() const;
873 /// \brief Deallocate a node created by getTemporary.
875 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
876 /// references will be reset.
877 static void deleteTemporary(MDNode *N);
879 LLVMContext &getContext() const { return Context.getContext(); }
881 /// \brief Replace a specific operand.
882 void replaceOperandWith(unsigned I, Metadata *New);
884 /// \brief Check if node is fully resolved.
886 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
887 /// this always returns \c true.
889 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
890 /// support (because all operands are resolved).
892 /// As forward declarations are resolved, their containers should get
893 /// resolved automatically. However, if this (or one of its operands) is
894 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
895 bool isResolved() const { return !Context.hasReplaceableUses(); }
897 bool isUniqued() const { return Storage == Uniqued; }
898 bool isDistinct() const { return Storage == Distinct; }
899 bool isTemporary() const { return Storage == Temporary; }
901 /// \brief RAUW a temporary.
903 /// \pre \a isTemporary() must be \c true.
904 void replaceAllUsesWith(Metadata *MD) {
905 assert(isTemporary() && "Expected temporary node");
906 assert(!isResolved() && "Expected RAUW support");
907 Context.getReplaceableUses()->replaceAllUsesWith(MD);
910 /// Set the CanReplace flag to the given value.
911 void setCanReplace(bool Replaceable) {
912 Context.getReplaceableUses()->setCanReplace(Replaceable);
915 /// \brief Resolve cycles.
917 /// Once all forward declarations have been resolved, force cycles to be
918 /// resolved. If \p MDMaterialized is true, then any temporary metadata
919 /// is ignored, otherwise it asserts when encountering temporary metadata.
921 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
922 void resolveCycles(bool MDMaterialized = true);
924 /// \brief Replace a temporary node with a permanent one.
926 /// Try to create a uniqued version of \c N -- in place, if possible -- and
927 /// return it. If \c N cannot be uniqued, return a distinct node instead.
929 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
930 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
931 return cast<T>(N.release()->replaceWithPermanentImpl());
934 /// \brief Replace a temporary node with a uniqued one.
936 /// Create a uniqued version of \c N -- in place, if possible -- and return
937 /// it. Takes ownership of the temporary node.
939 /// \pre N does not self-reference.
941 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
942 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
943 return cast<T>(N.release()->replaceWithUniquedImpl());
946 /// \brief Replace a temporary node with a distinct one.
948 /// Create a distinct version of \c N -- in place, if possible -- and return
949 /// it. Takes ownership of the temporary node.
951 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
952 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
953 return cast<T>(N.release()->replaceWithDistinctImpl());
957 MDNode *replaceWithPermanentImpl();
958 MDNode *replaceWithUniquedImpl();
959 MDNode *replaceWithDistinctImpl();
962 /// \brief Set an operand.
964 /// Sets the operand directly, without worrying about uniquing.
965 void setOperand(unsigned I, Metadata *New);
967 void storeDistinctInContext();
968 template <class T, class StoreT>
969 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
970 template <class T> static T *storeImpl(T *N, StorageType Storage);
973 void handleChangedOperand(void *Ref, Metadata *New);
976 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
977 void decrementUnresolvedOperandCount();
978 unsigned countUnresolvedOperands();
980 /// \brief Mutate this to be "uniqued".
982 /// Mutate this so that \a isUniqued().
983 /// \pre \a isTemporary().
984 /// \pre already added to uniquing set.
987 /// \brief Mutate this to be "distinct".
989 /// Mutate this so that \a isDistinct().
990 /// \pre \a isTemporary().
993 void deleteAsSubclass();
995 void eraseFromStore();
997 template <class NodeTy> struct HasCachedHash;
998 template <class NodeTy>
999 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1000 N->recalculateHash();
1002 template <class NodeTy>
1003 static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1004 template <class NodeTy>
1005 static void dispatchResetHash(NodeTy *N, std::true_type) {
1008 template <class NodeTy>
1009 static void dispatchResetHash(NodeTy *, std::false_type) {}
1012 typedef const MDOperand *op_iterator;
1013 typedef iterator_range<op_iterator> op_range;
1015 op_iterator op_begin() const {
1016 return const_cast<MDNode *>(this)->mutable_begin();
1018 op_iterator op_end() const {
1019 return const_cast<MDNode *>(this)->mutable_end();
1021 op_range operands() const { return op_range(op_begin(), op_end()); }
1023 const MDOperand &getOperand(unsigned I) const {
1024 assert(I < NumOperands && "Out of range");
1025 return op_begin()[I];
1028 /// \brief Return number of MDNode operands.
1029 unsigned getNumOperands() const { return NumOperands; }
1031 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1032 static bool classof(const Metadata *MD) {
1033 switch (MD->getMetadataID()) {
1036 #define HANDLE_MDNODE_LEAF(CLASS) \
1039 #include "llvm/IR/Metadata.def"
1043 /// \brief Check whether MDNode is a vtable access.
1044 bool isTBAAVtableAccess() const;
1046 /// \brief Methods for metadata merging.
1047 static MDNode *concatenate(MDNode *A, MDNode *B);
1048 static MDNode *intersect(MDNode *A, MDNode *B);
1049 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1050 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1051 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1052 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1053 static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1057 /// \brief Tuple of metadata.
1059 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1060 /// default based on their operands.
1061 class MDTuple : public MDNode {
1062 friend class LLVMContextImpl;
1063 friend class MDNode;
1065 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1066 ArrayRef<Metadata *> Vals)
1067 : MDNode(C, MDTupleKind, Storage, Vals) {
1070 ~MDTuple() { dropAllReferences(); }
1072 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1073 void recalculateHash();
1075 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1076 StorageType Storage, bool ShouldCreate = true);
1078 TempMDTuple cloneImpl() const {
1079 return getTemporary(getContext(),
1080 SmallVector<Metadata *, 4>(op_begin(), op_end()));
1084 /// \brief Get the hash, if any.
1085 unsigned getHash() const { return SubclassData32; }
1087 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1088 return getImpl(Context, MDs, Uniqued);
1090 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1091 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1094 /// \brief Return a distinct node.
1096 /// Return a distinct node -- i.e., a node that is not uniqued.
1097 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1098 return getImpl(Context, MDs, Distinct);
1101 /// \brief Return a temporary node.
1103 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1104 /// not uniqued, may be RAUW'd, and must be manually deleted with
1105 /// deleteTemporary.
1106 static TempMDTuple getTemporary(LLVMContext &Context,
1107 ArrayRef<Metadata *> MDs) {
1108 return TempMDTuple(getImpl(Context, MDs, Temporary));
1111 /// \brief Return a (temporary) clone of this.
1112 TempMDTuple clone() const { return cloneImpl(); }
1114 static bool classof(const Metadata *MD) {
1115 return MD->getMetadataID() == MDTupleKind;
1119 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1120 return MDTuple::get(Context, MDs);
1122 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1123 return MDTuple::getIfExists(Context, MDs);
1125 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1126 return MDTuple::getDistinct(Context, MDs);
1128 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1129 ArrayRef<Metadata *> MDs) {
1130 return MDTuple::getTemporary(Context, MDs);
1133 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1134 MDNode::deleteTemporary(Node);
1137 /// \brief Typed iterator through MDNode operands.
1139 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1140 /// particular Metadata subclass.
1142 class TypedMDOperandIterator
1143 : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1144 MDNode::op_iterator I = nullptr;
1147 TypedMDOperandIterator() = default;
1148 explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1149 T *operator*() const { return cast_or_null<T>(*I); }
1150 TypedMDOperandIterator &operator++() {
1154 TypedMDOperandIterator operator++(int) {
1155 TypedMDOperandIterator Temp(*this);
1159 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1160 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1163 /// \brief Typed, array-like tuple of metadata.
1165 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1166 /// particular type of metadata.
1167 template <class T> class MDTupleTypedArrayWrapper {
1168 const MDTuple *N = nullptr;
1171 MDTupleTypedArrayWrapper() = default;
1172 MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1175 MDTupleTypedArrayWrapper(
1176 const MDTupleTypedArrayWrapper<U> &Other,
1177 typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1182 explicit MDTupleTypedArrayWrapper(
1183 const MDTupleTypedArrayWrapper<U> &Other,
1184 typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1188 explicit operator bool() const { return get(); }
1189 explicit operator MDTuple *() const { return get(); }
1191 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1192 MDTuple *operator->() const { return get(); }
1193 MDTuple &operator*() const { return *get(); }
1195 // FIXME: Fix callers and remove condition on N.
1196 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1197 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1199 // FIXME: Fix callers and remove condition on N.
1200 typedef TypedMDOperandIterator<T> iterator;
1201 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1202 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1205 #define HANDLE_METADATA(CLASS) \
1206 typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1207 #include "llvm/IR/Metadata.def"
1209 //===----------------------------------------------------------------------===//
1210 /// \brief A tuple of MDNodes.
1212 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1213 /// to modules, have names, and contain lists of MDNodes.
1215 /// TODO: Inherit from Metadata.
1216 class NamedMDNode : public ilist_node<NamedMDNode> {
1217 friend struct ilist_traits<NamedMDNode>;
1218 friend class LLVMContextImpl;
1219 friend class Module;
1220 NamedMDNode(const NamedMDNode &) = delete;
1224 void *Operands; // SmallVector<TrackingMDRef, 4>
1226 void setParent(Module *M) { Parent = M; }
1228 explicit NamedMDNode(const Twine &N);
1230 template<class T1, class T2>
1231 class op_iterator_impl :
1232 public std::iterator<std::bidirectional_iterator_tag, T2> {
1233 const NamedMDNode *Node;
1235 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1237 friend class NamedMDNode;
1240 op_iterator_impl() : Node(nullptr), Idx(0) { }
1242 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1243 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1244 op_iterator_impl &operator++() {
1248 op_iterator_impl operator++(int) {
1249 op_iterator_impl tmp(*this);
1253 op_iterator_impl &operator--() {
1257 op_iterator_impl operator--(int) {
1258 op_iterator_impl tmp(*this);
1263 T1 operator*() const { return Node->getOperand(Idx); }
1267 /// \brief Drop all references and remove the node from parent module.
1268 void eraseFromParent();
1270 /// \brief Remove all uses and clear node vector.
1271 void dropAllReferences();
1275 /// \brief Get the module that holds this named metadata collection.
1276 inline Module *getParent() { return Parent; }
1277 inline const Module *getParent() const { return Parent; }
1279 MDNode *getOperand(unsigned i) const;
1280 unsigned getNumOperands() const;
1281 void addOperand(MDNode *M);
1282 void setOperand(unsigned I, MDNode *New);
1283 StringRef getName() const;
1284 void print(raw_ostream &ROS, bool IsForDebug = false) const;
1287 // ---------------------------------------------------------------------------
1288 // Operand Iterator interface...
1290 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1291 op_iterator op_begin() { return op_iterator(this, 0); }
1292 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1294 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1295 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1296 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1298 inline iterator_range<op_iterator> operands() {
1299 return make_range(op_begin(), op_end());
1301 inline iterator_range<const_op_iterator> operands() const {
1302 return make_range(op_begin(), op_end());
1306 } // end llvm namespace
1308 #endif // LLVM_IR_METADATA_H