1 //===-- llvm/Metadata.h - Metadata definitions ------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/MetadataTracking.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <type_traits>
32 template<typename ValueSubClass, typename ItemParentClass>
33 class SymbolTableListTraits;
36 enum LLVMConstants : uint32_t {
37 DEBUG_METADATA_VERSION = 2 // Current debug info version number.
40 /// \brief Root of the metadata hierarchy.
42 /// This is a root class for typeless data in the IR.
44 friend class ReplaceableMetadataImpl;
47 const unsigned char SubclassID;
50 /// \brief Active type of storage.
51 enum StorageType { Uniqued, Distinct, Temporary };
53 /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
55 // TODO: expose remaining bits to subclasses.
57 unsigned short SubclassData16;
58 unsigned SubclassData32;
65 ConstantAsMetadataKind,
71 Metadata(unsigned ID, StorageType Storage)
72 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
76 /// \brief Default handling of a changed operand, which asserts.
78 /// If subclasses pass themselves in as owners to a tracking node reference,
79 /// they must provide an implementation of this method.
80 void handleChangedOperand(void *, Metadata *) {
81 llvm_unreachable("Unimplemented in Metadata subclass");
85 unsigned getMetadataID() const { return SubclassID; }
87 /// \brief User-friendly dump.
89 void print(raw_ostream &OS) const;
90 void printAsOperand(raw_ostream &OS, bool PrintType = true,
91 const Module *M = nullptr) const;
94 #define HANDLE_METADATA(CLASS) class CLASS;
95 #include "llvm/IR/Metadata.def"
97 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
102 /// \brief Metadata wrapper in the Value hierarchy.
104 /// A member of the \a Value hierarchy to represent a reference to metadata.
105 /// This allows, e.g., instrinsics to have metadata as operands.
107 /// Notably, this is the only thing in either hierarchy that is allowed to
108 /// reference \a LocalAsMetadata.
109 class MetadataAsValue : public Value {
110 friend class ReplaceableMetadataImpl;
111 friend class LLVMContextImpl;
115 MetadataAsValue(Type *Ty, Metadata *MD);
118 /// \brief Drop use of metadata (during teardown).
119 void dropUse() { MD = nullptr; }
122 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
123 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
124 Metadata *getMetadata() const { return MD; }
126 static bool classof(const Value *V) {
127 return V->getValueID() == MetadataAsValueVal;
131 void handleChangedMetadata(Metadata *MD);
136 /// \brief Shared implementation of use-lists for replaceable metadata.
138 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
139 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
140 /// and \a TempMDNode).
141 class ReplaceableMetadataImpl {
142 friend class MetadataTracking;
145 typedef MetadataTracking::OwnerTy OwnerTy;
148 LLVMContext &Context;
150 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
153 ReplaceableMetadataImpl(LLVMContext &Context)
154 : Context(Context), NextIndex(0) {}
155 ~ReplaceableMetadataImpl() {
156 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
159 LLVMContext &getContext() const { return Context; }
161 /// \brief Replace all uses of this with MD.
163 /// Replace all uses of this with \c MD, which is allowed to be null.
164 void replaceAllUsesWith(Metadata *MD);
166 /// \brief Resolve all uses of this.
168 /// Resolve all uses of this, turning off RAUW permanently. If \c
169 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
171 void resolveAllUses(bool ResolveUsers = true);
174 void addRef(void *Ref, OwnerTy Owner);
175 void dropRef(void *Ref);
176 void moveRef(void *Ref, void *New, const Metadata &MD);
178 static ReplaceableMetadataImpl *get(Metadata &MD);
181 /// \brief Value wrapper in the Metadata hierarchy.
183 /// This is a custom value handle that allows other metadata to refer to
184 /// classes in the Value hierarchy.
186 /// Because of full uniquing support, each value is only wrapped by a single \a
187 /// ValueAsMetadata object, so the lookup maps are far more efficient than
188 /// those using ValueHandleBase.
189 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
190 friend class ReplaceableMetadataImpl;
191 friend class LLVMContextImpl;
195 /// \brief Drop users without RAUW (during teardown).
197 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
201 ValueAsMetadata(unsigned ID, Value *V)
202 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
203 assert(V && "Expected valid value");
205 ~ValueAsMetadata() {}
208 static ValueAsMetadata *get(Value *V);
209 static ConstantAsMetadata *getConstant(Value *C) {
210 return cast<ConstantAsMetadata>(get(C));
212 static LocalAsMetadata *getLocal(Value *Local) {
213 return cast<LocalAsMetadata>(get(Local));
216 static ValueAsMetadata *getIfExists(Value *V);
217 static ConstantAsMetadata *getConstantIfExists(Value *C) {
218 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
220 static LocalAsMetadata *getLocalIfExists(Value *Local) {
221 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
224 Value *getValue() const { return V; }
225 Type *getType() const { return V->getType(); }
226 LLVMContext &getContext() const { return V->getContext(); }
228 static void handleDeletion(Value *V);
229 static void handleRAUW(Value *From, Value *To);
232 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
234 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
235 /// \a Value gets RAUW'ed and the target already exists, this is used to
236 /// merge the two metadata nodes.
237 void replaceAllUsesWith(Metadata *MD) {
238 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
242 static bool classof(const Metadata *MD) {
243 return MD->getMetadataID() == LocalAsMetadataKind ||
244 MD->getMetadataID() == ConstantAsMetadataKind;
248 class ConstantAsMetadata : public ValueAsMetadata {
249 friend class ValueAsMetadata;
251 ConstantAsMetadata(Constant *C)
252 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
255 static ConstantAsMetadata *get(Constant *C) {
256 return ValueAsMetadata::getConstant(C);
258 static ConstantAsMetadata *getIfExists(Constant *C) {
259 return ValueAsMetadata::getConstantIfExists(C);
262 Constant *getValue() const {
263 return cast<Constant>(ValueAsMetadata::getValue());
266 static bool classof(const Metadata *MD) {
267 return MD->getMetadataID() == ConstantAsMetadataKind;
271 class LocalAsMetadata : public ValueAsMetadata {
272 friend class ValueAsMetadata;
274 LocalAsMetadata(Value *Local)
275 : ValueAsMetadata(LocalAsMetadataKind, Local) {
276 assert(!isa<Constant>(Local) && "Expected local value");
280 static LocalAsMetadata *get(Value *Local) {
281 return ValueAsMetadata::getLocal(Local);
283 static LocalAsMetadata *getIfExists(Value *Local) {
284 return ValueAsMetadata::getLocalIfExists(Local);
287 static bool classof(const Metadata *MD) {
288 return MD->getMetadataID() == LocalAsMetadataKind;
292 /// \brief Transitional API for extracting constants from Metadata.
294 /// This namespace contains transitional functions for metadata that points to
297 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
298 /// operands could refer to any \a Value. There's was a lot of code like this:
302 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
305 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
306 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
307 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
308 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
309 /// requires subtle control flow changes.
311 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
312 /// so that metadata can refer to numbers without traversing a bridge to the \a
313 /// Value hierarchy. In this final state, the code above would look like this:
317 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
320 /// The API in this namespace supports the transition. \a MDInt doesn't exist
321 /// yet, and even once it does, changing each metadata schema to use it is its
322 /// own mini-project. In the meantime this API prevents us from introducing
323 /// complex and bug-prone control flow that will disappear in the end. In
324 /// particular, the above code looks like this:
328 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
331 /// The full set of provided functions includes:
333 /// mdconst::hasa <=> isa
334 /// mdconst::extract <=> cast
335 /// mdconst::extract_or_null <=> cast_or_null
336 /// mdconst::dyn_extract <=> dyn_cast
337 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
339 /// The target of the cast must be a subclass of \a Constant.
343 template <class T> T &make();
344 template <class T, class Result> struct HasDereference {
347 template <size_t N> struct SFINAE {};
349 template <class U, class V>
350 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
351 template <class U, class V> static No &hasDereference(...);
353 static const bool value =
354 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
356 template <class V, class M> struct IsValidPointer {
357 static const bool value = std::is_base_of<Constant, V>::value &&
358 HasDereference<M, const Metadata &>::value;
360 template <class V, class M> struct IsValidReference {
361 static const bool value = std::is_base_of<Constant, V>::value &&
362 std::is_convertible<M, const Metadata &>::value;
364 } // end namespace detail
366 /// \brief Check whether Metadata has a Value.
368 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
370 template <class X, class Y>
371 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
373 assert(MD && "Null pointer sent into hasa");
374 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
375 return isa<X>(V->getValue());
378 template <class X, class Y>
380 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
385 /// \brief Extract a Value from Metadata.
387 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
388 template <class X, class Y>
389 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
391 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
393 template <class X, class Y>
395 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
400 /// \brief Extract a Value from Metadata, allowing null.
402 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
403 /// from \c MD, allowing \c MD to be null.
404 template <class X, class Y>
405 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
406 extract_or_null(Y &&MD) {
407 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
408 return cast<X>(V->getValue());
412 /// \brief Extract a Value from Metadata, if any.
414 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
415 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
416 /// Value it does contain is of the wrong subclass.
417 template <class X, class Y>
418 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
419 dyn_extract(Y &&MD) {
420 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
421 return dyn_cast<X>(V->getValue());
425 /// \brief Extract a Value from Metadata, if any, allowing null.
427 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
428 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
429 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
430 template <class X, class Y>
431 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
432 dyn_extract_or_null(Y &&MD) {
433 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
434 return dyn_cast<X>(V->getValue());
438 } // end namespace mdconst
440 //===----------------------------------------------------------------------===//
441 /// \brief A single uniqued string.
443 /// These are used to efficiently contain a byte sequence for metadata.
444 /// MDString is always unnamed.
445 class MDString : public Metadata {
446 friend class StringMapEntry<MDString>;
448 MDString(const MDString &) LLVM_DELETED_FUNCTION;
449 MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
450 MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
452 StringMapEntry<MDString> *Entry;
453 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
454 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
457 static MDString *get(LLVMContext &Context, StringRef Str);
458 static MDString *get(LLVMContext &Context, const char *Str) {
459 return get(Context, Str ? StringRef(Str) : StringRef());
462 StringRef getString() const;
464 unsigned getLength() const { return (unsigned)getString().size(); }
466 typedef StringRef::iterator iterator;
468 /// \brief Pointer to the first byte of the string.
469 iterator begin() const { return getString().begin(); }
471 /// \brief Pointer to one byte past the end of the string.
472 iterator end() const { return getString().end(); }
474 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
475 const unsigned char *bytes_end() const { return getString().bytes_end(); }
477 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
478 static bool classof(const Metadata *MD) {
479 return MD->getMetadataID() == MDStringKind;
483 /// \brief A collection of metadata nodes that might be associated with a
484 /// memory access used by the alias-analysis infrastructure.
486 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
488 : TBAA(T), Scope(S), NoAlias(N) {}
490 bool operator==(const AAMDNodes &A) const {
491 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
494 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
496 LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
498 /// \brief The tag for type-based alias analysis.
501 /// \brief The tag for alias scope specification (used with noalias).
504 /// \brief The tag specifying the noalias scope.
508 // Specialize DenseMapInfo for AAMDNodes.
510 struct DenseMapInfo<AAMDNodes> {
511 static inline AAMDNodes getEmptyKey() {
512 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
514 static inline AAMDNodes getTombstoneKey() {
515 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
517 static unsigned getHashValue(const AAMDNodes &Val) {
518 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
519 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
520 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
522 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
527 /// \brief Tracking metadata reference owned by Metadata.
529 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
530 /// of \a Metadata, which has the option of registering itself for callbacks to
531 /// re-unique itself.
533 /// In particular, this is used by \a MDNode.
535 MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
536 MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
537 MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
538 MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
543 MDOperand() : MD(nullptr) {}
544 ~MDOperand() { untrack(); }
546 Metadata *get() const { return MD; }
547 operator Metadata *() const { return get(); }
548 Metadata *operator->() const { return get(); }
549 Metadata &operator*() const { return *get(); }
555 void reset(Metadata *MD, Metadata *Owner) {
562 void track(Metadata *Owner) {
565 MetadataTracking::track(this, *MD, *Owner);
567 MetadataTracking::track(MD);
571 assert(static_cast<void *>(this) == &MD && "Expected same address");
573 MetadataTracking::untrack(MD);
577 template <> struct simplify_type<MDOperand> {
578 typedef Metadata *SimpleType;
579 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
582 template <> struct simplify_type<const MDOperand> {
583 typedef Metadata *SimpleType;
584 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
587 /// \brief Pointer to the context, with optional RAUW support.
589 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
590 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
591 class ContextAndReplaceableUses {
592 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
594 ContextAndReplaceableUses() LLVM_DELETED_FUNCTION;
595 ContextAndReplaceableUses(ContextAndReplaceableUses &&)
596 LLVM_DELETED_FUNCTION;
597 ContextAndReplaceableUses(const ContextAndReplaceableUses &)
598 LLVM_DELETED_FUNCTION;
599 ContextAndReplaceableUses &
600 operator=(ContextAndReplaceableUses &&) LLVM_DELETED_FUNCTION;
601 ContextAndReplaceableUses &
602 operator=(const ContextAndReplaceableUses &) LLVM_DELETED_FUNCTION;
605 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
606 ContextAndReplaceableUses(
607 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
608 : Ptr(ReplaceableUses.release()) {
609 assert(getReplaceableUses() && "Expected non-null replaceable uses");
611 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
613 operator LLVMContext &() { return getContext(); }
615 /// \brief Whether this contains RAUW support.
616 bool hasReplaceableUses() const {
617 return Ptr.is<ReplaceableMetadataImpl *>();
619 LLVMContext &getContext() const {
620 if (hasReplaceableUses())
621 return getReplaceableUses()->getContext();
622 return *Ptr.get<LLVMContext *>();
624 ReplaceableMetadataImpl *getReplaceableUses() const {
625 if (hasReplaceableUses())
626 return Ptr.get<ReplaceableMetadataImpl *>();
630 /// \brief Assign RAUW support to this.
632 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
635 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
636 assert(ReplaceableUses && "Expected non-null replaceable uses");
637 assert(&ReplaceableUses->getContext() == &getContext() &&
638 "Expected same context");
639 delete getReplaceableUses();
640 Ptr = ReplaceableUses.release();
643 /// \brief Drop RAUW support.
645 /// Cede ownership of RAUW support, returning it.
646 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
647 assert(hasReplaceableUses() && "Expected to own replaceable uses");
648 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
649 getReplaceableUses());
650 Ptr = &ReplaceableUses->getContext();
651 return ReplaceableUses;
655 struct TempMDNodeDeleter {
656 inline void operator()(MDNode *Node) const;
659 #define HANDLE_MDNODE_LEAF(CLASS) \
660 typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
661 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
662 #include "llvm/IR/Metadata.def"
664 /// \brief Metadata node.
666 /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
667 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
668 /// until forward references are known. The basic metadata node is an \a
671 /// There is limited support for RAUW at construction time. At construction
672 /// time, if any operand is a temporary node (or an unresolved uniqued node,
673 /// which indicates a transitive temporary operand), the node itself will be
674 /// unresolved. As soon as all operands become resolved, it will drop RAUW
675 /// support permanently.
677 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
678 /// to be called on some member of the cycle once all temporary nodes have been
680 class MDNode : public Metadata {
681 friend class ReplaceableMetadataImpl;
682 friend class LLVMContextImpl;
684 MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
685 void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
686 void *operator new(size_t) LLVM_DELETED_FUNCTION;
688 unsigned NumOperands;
689 unsigned NumUnresolved;
692 ContextAndReplaceableUses Context;
694 void *operator new(size_t Size, unsigned NumOps);
695 void operator delete(void *Mem);
697 /// \brief Required by std, but never called.
698 void operator delete(void *, unsigned) {
699 llvm_unreachable("Constructor throws?");
702 /// \brief Required by std, but never called.
703 void operator delete(void *, unsigned, bool) {
704 llvm_unreachable("Constructor throws?");
707 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
708 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
711 void dropAllReferences();
713 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
714 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
717 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
718 static inline MDTuple *getIfExists(LLVMContext &Context,
719 ArrayRef<Metadata *> MDs);
720 static inline MDTuple *getDistinct(LLVMContext &Context,
721 ArrayRef<Metadata *> MDs);
722 static inline TempMDTuple getTemporary(LLVMContext &Context,
723 ArrayRef<Metadata *> MDs);
725 /// \brief Create a (temporary) clone of this.
726 TempMDNode clone() const;
728 /// \brief Deallocate a node created by getTemporary.
730 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
731 /// references will be reset.
732 static void deleteTemporary(MDNode *N);
734 LLVMContext &getContext() const { return Context.getContext(); }
736 /// \brief Replace a specific operand.
737 void replaceOperandWith(unsigned I, Metadata *New);
739 /// \brief Check if node is fully resolved.
741 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
742 /// this always returns \c true.
744 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
745 /// support (because all operands are resolved).
747 /// As forward declarations are resolved, their containers should get
748 /// resolved automatically. However, if this (or one of its operands) is
749 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
750 bool isResolved() const { return !Context.hasReplaceableUses(); }
752 bool isUniqued() const { return Storage == Uniqued; }
753 bool isDistinct() const { return Storage == Distinct; }
754 bool isTemporary() const { return Storage == Temporary; }
756 /// \brief RAUW a temporary.
758 /// \pre \a isTemporary() must be \c true.
759 void replaceAllUsesWith(Metadata *MD) {
760 assert(isTemporary() && "Expected temporary node");
761 assert(!isResolved() && "Expected RAUW support");
762 Context.getReplaceableUses()->replaceAllUsesWith(MD);
765 /// \brief Resolve cycles.
767 /// Once all forward declarations have been resolved, force cycles to be
770 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
771 void resolveCycles();
773 /// \brief Replace a temporary node with a uniqued one.
775 /// Create a uniqued version of \c N -- in place, if possible -- and return
776 /// it. Takes ownership of the temporary node.
778 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
779 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
780 return cast<T>(N.release()->replaceWithUniquedImpl());
783 /// \brief Replace a temporary node with a distinct one.
785 /// Create a distinct version of \c N -- in place, if possible -- and return
786 /// it. Takes ownership of the temporary node.
788 static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
789 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
790 return cast<T>(N.release()->replaceWithDistinctImpl());
794 MDNode *replaceWithUniquedImpl();
795 MDNode *replaceWithDistinctImpl();
798 /// \brief Set an operand.
800 /// Sets the operand directly, without worrying about uniquing.
801 void setOperand(unsigned I, Metadata *New);
803 void storeDistinctInContext();
804 template <class T, class StoreT>
805 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
808 void handleChangedOperand(void *Ref, Metadata *New);
811 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
812 void decrementUnresolvedOperandCount();
813 unsigned countUnresolvedOperands();
815 /// \brief Mutate this to be "uniqued".
817 /// Mutate this so that \a isUniqued().
818 /// \pre \a isTemporary().
819 /// \pre already added to uniquing set.
822 /// \brief Mutate this to be "distinct".
824 /// Mutate this so that \a isDistinct().
825 /// \pre \a isTemporary().
828 void deleteAsSubclass();
830 void eraseFromStore();
832 template <class NodeTy> struct HasCachedHash;
833 template <class NodeTy>
834 static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
835 N->recalculateHash();
837 template <class NodeTy>
838 static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
839 template <class NodeTy>
840 static void dispatchResetHash(NodeTy *N, std::true_type) {
843 template <class NodeTy>
844 static void dispatchResetHash(NodeTy *N, std::false_type) {}
847 typedef const MDOperand *op_iterator;
848 typedef iterator_range<op_iterator> op_range;
850 op_iterator op_begin() const {
851 return const_cast<MDNode *>(this)->mutable_begin();
853 op_iterator op_end() const {
854 return const_cast<MDNode *>(this)->mutable_end();
856 op_range operands() const { return op_range(op_begin(), op_end()); }
858 const MDOperand &getOperand(unsigned I) const {
859 assert(I < NumOperands && "Out of range");
860 return op_begin()[I];
863 /// \brief Return number of MDNode operands.
864 unsigned getNumOperands() const { return NumOperands; }
866 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
867 static bool classof(const Metadata *MD) {
868 return MD->getMetadataID() == MDTupleKind ||
869 MD->getMetadataID() == MDLocationKind ||
870 MD->getMetadataID() == GenericDebugNodeKind;
873 /// \brief Check whether MDNode is a vtable access.
874 bool isTBAAVtableAccess() const;
876 /// \brief Methods for metadata merging.
877 static MDNode *concatenate(MDNode *A, MDNode *B);
878 static MDNode *intersect(MDNode *A, MDNode *B);
879 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
880 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
881 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
884 /// \brief Tuple of metadata.
886 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
887 /// default based on their operands.
888 class MDTuple : public MDNode {
889 friend class LLVMContextImpl;
892 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
893 ArrayRef<Metadata *> Vals)
894 : MDNode(C, MDTupleKind, Storage, Vals) {
897 ~MDTuple() { dropAllReferences(); }
899 void setHash(unsigned Hash) { SubclassData32 = Hash; }
900 void recalculateHash();
902 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
903 StorageType Storage, bool ShouldCreate = true);
905 TempMDTuple cloneImpl() const {
906 return getTemporary(getContext(),
907 SmallVector<Metadata *, 4>(op_begin(), op_end()));
911 /// \brief Get the hash, if any.
912 unsigned getHash() const { return SubclassData32; }
914 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
915 return getImpl(Context, MDs, Uniqued);
917 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
918 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
921 /// \brief Return a distinct node.
923 /// Return a distinct node -- i.e., a node that is not uniqued.
924 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
925 return getImpl(Context, MDs, Distinct);
928 /// \brief Return a temporary node.
930 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
931 /// not uniqued, may be RAUW'd, and must be manually deleted with
933 static TempMDTuple getTemporary(LLVMContext &Context,
934 ArrayRef<Metadata *> MDs) {
935 return TempMDTuple(getImpl(Context, MDs, Temporary));
938 /// \brief Return a (temporary) clone of this.
939 TempMDTuple clone() const { return cloneImpl(); }
941 static bool classof(const Metadata *MD) {
942 return MD->getMetadataID() == MDTupleKind;
946 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
947 return MDTuple::get(Context, MDs);
949 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
950 return MDTuple::getIfExists(Context, MDs);
952 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
953 return MDTuple::getDistinct(Context, MDs);
955 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
956 ArrayRef<Metadata *> MDs) {
957 return MDTuple::getTemporary(Context, MDs);
960 void TempMDNodeDeleter::operator()(MDNode *Node) const {
961 MDNode::deleteTemporary(Node);
964 /// \brief Debug location.
966 /// A debug location in source code, used for debug info and otherwise.
967 class MDLocation : public MDNode {
968 friend class LLVMContextImpl;
971 MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
972 unsigned Column, ArrayRef<Metadata *> MDs);
973 ~MDLocation() { dropAllReferences(); }
975 static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
976 unsigned Column, Metadata *Scope,
977 Metadata *InlinedAt, StorageType Storage,
978 bool ShouldCreate = true);
980 TempMDLocation cloneImpl() const {
981 return getTemporary(getContext(), getLine(), getColumn(), getScope(),
985 // Disallow replacing operands.
986 void replaceOperandWith(unsigned I, Metadata *New) LLVM_DELETED_FUNCTION;
989 static MDLocation *get(LLVMContext &Context, unsigned Line, unsigned Column,
990 Metadata *Scope, Metadata *InlinedAt = nullptr) {
991 return getImpl(Context, Line, Column, Scope, InlinedAt, Uniqued);
993 static MDLocation *getIfExists(LLVMContext &Context, unsigned Line,
994 unsigned Column, Metadata *Scope,
995 Metadata *InlinedAt = nullptr) {
996 return getImpl(Context, Line, Column, Scope, InlinedAt, Uniqued,
997 /* ShouldCreate */ false);
999 static MDLocation *getDistinct(LLVMContext &Context, unsigned Line,
1000 unsigned Column, Metadata *Scope,
1001 Metadata *InlinedAt = nullptr) {
1002 return getImpl(Context, Line, Column, Scope, InlinedAt, Distinct);
1004 static TempMDLocation getTemporary(LLVMContext &Context, unsigned Line,
1005 unsigned Column, Metadata *Scope,
1006 Metadata *InlinedAt = nullptr) {
1007 return TempMDLocation(
1008 getImpl(Context, Line, Column, Scope, InlinedAt, Temporary));
1011 /// \brief Return a (temporary) clone of this.
1012 TempMDLocation clone() const { return cloneImpl(); }
1014 unsigned getLine() const { return SubclassData32; }
1015 unsigned getColumn() const { return SubclassData16; }
1016 Metadata *getScope() const { return getOperand(0); }
1017 Metadata *getInlinedAt() const {
1018 if (getNumOperands() == 2)
1019 return getOperand(1);
1023 static bool classof(const Metadata *MD) {
1024 return MD->getMetadataID() == MDLocationKind;
1028 /// \brief Tagged DWARF-like metadata node.
1030 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
1031 /// defined in llvm/Support/Dwarf.h). Called \a DebugNode because it's
1032 /// potentially used for non-DWARF output.
1033 class DebugNode : public MDNode {
1034 friend class LLVMContextImpl;
1035 friend class MDNode;
1038 DebugNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1039 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
1040 : MDNode(C, ID, Storage, Ops1, Ops2) {
1041 assert(Tag < 1u << 16);
1042 SubclassData16 = Tag;
1047 unsigned getTag() const { return SubclassData16; }
1049 static bool classof(const Metadata *MD) {
1050 return MD->getMetadataID() == GenericDebugNodeKind;
1054 /// \brief Generic tagged DWARF-like metadata node.
1056 /// An un-specialized DWARF-like metadata node. The first operand is a
1057 /// (possibly empty) null-separated \a MDString header that contains arbitrary
1058 /// fields. The remaining operands are \a dwarf_operands(), and are pointers
1059 /// to other metadata.
1060 class GenericDebugNode : public DebugNode {
1061 friend class LLVMContextImpl;
1062 friend class MDNode;
1064 GenericDebugNode(LLVMContext &C, StorageType Storage, unsigned Hash,
1065 unsigned Tag, ArrayRef<Metadata *> Ops1,
1066 ArrayRef<Metadata *> Ops2)
1067 : DebugNode(C, GenericDebugNodeKind, Storage, Tag, Ops1, Ops2) {
1070 ~GenericDebugNode() { dropAllReferences(); }
1072 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1073 void recalculateHash();
1075 static GenericDebugNode *getImpl(LLVMContext &Context, unsigned Tag,
1077 ArrayRef<Metadata *> DwarfOps,
1078 StorageType Storage,
1079 bool ShouldCreate = true);
1081 TempGenericDebugNode cloneImpl() const {
1082 return getTemporary(
1083 getContext(), getTag(), getHeader(),
1084 SmallVector<Metadata *, 4>(dwarf_op_begin(), dwarf_op_end()));
1088 unsigned getHash() const { return SubclassData32; }
1090 static GenericDebugNode *get(LLVMContext &Context, unsigned Tag,
1092 ArrayRef<Metadata *> DwarfOps) {
1093 return getImpl(Context, Tag, Header, DwarfOps, Uniqued);
1095 static GenericDebugNode *getIfExists(LLVMContext &Context, unsigned Tag,
1097 ArrayRef<Metadata *> DwarfOps) {
1098 return getImpl(Context, Tag, Header, DwarfOps, Uniqued,
1099 /* ShouldCreate */ false);
1101 static GenericDebugNode *getDistinct(LLVMContext &Context, unsigned Tag,
1103 ArrayRef<Metadata *> DwarfOps) {
1104 return getImpl(Context, Tag, Header, DwarfOps, Distinct);
1106 static TempGenericDebugNode getTemporary(LLVMContext &Context, unsigned Tag,
1108 ArrayRef<Metadata *> DwarfOps) {
1109 return TempGenericDebugNode(
1110 getImpl(Context, Tag, Header, DwarfOps, Temporary));
1113 /// \brief Return a (temporary) clone of this.
1114 TempGenericDebugNode clone() const { return cloneImpl(); }
1116 unsigned getTag() const { return SubclassData16; }
1117 StringRef getHeader() const {
1118 if (auto *S = cast_or_null<MDString>(getOperand(0)))
1119 return S->getString();
1123 op_iterator dwarf_op_begin() const { return op_begin() + 1; }
1124 op_iterator dwarf_op_end() const { return op_end(); }
1125 op_range dwarf_operands() const {
1126 return op_range(dwarf_op_begin(), dwarf_op_end());
1129 unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
1130 const MDOperand &getDwarfOperand(unsigned I) const {
1131 return getOperand(I + 1);
1133 void replaceDwarfOperandWith(unsigned I, Metadata *New) {
1134 replaceOperandWith(I + 1, New);
1137 static bool classof(const Metadata *MD) {
1138 return MD->getMetadataID() == GenericDebugNodeKind;
1142 //===----------------------------------------------------------------------===//
1143 /// \brief A tuple of MDNodes.
1145 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1146 /// to modules, have names, and contain lists of MDNodes.
1148 /// TODO: Inherit from Metadata.
1149 class NamedMDNode : public ilist_node<NamedMDNode> {
1150 friend class SymbolTableListTraits<NamedMDNode, Module>;
1151 friend struct ilist_traits<NamedMDNode>;
1152 friend class LLVMContextImpl;
1153 friend class Module;
1154 NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
1158 void *Operands; // SmallVector<TrackingMDRef, 4>
1160 void setParent(Module *M) { Parent = M; }
1162 explicit NamedMDNode(const Twine &N);
1164 template<class T1, class T2>
1165 class op_iterator_impl :
1166 public std::iterator<std::bidirectional_iterator_tag, T2> {
1167 const NamedMDNode *Node;
1169 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1171 friend class NamedMDNode;
1174 op_iterator_impl() : Node(nullptr), Idx(0) { }
1176 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1177 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1178 op_iterator_impl &operator++() {
1182 op_iterator_impl operator++(int) {
1183 op_iterator_impl tmp(*this);
1187 op_iterator_impl &operator--() {
1191 op_iterator_impl operator--(int) {
1192 op_iterator_impl tmp(*this);
1197 T1 operator*() const { return Node->getOperand(Idx); }
1201 /// \brief Drop all references and remove the node from parent module.
1202 void eraseFromParent();
1204 /// \brief Remove all uses and clear node vector.
1205 void dropAllReferences();
1209 /// \brief Get the module that holds this named metadata collection.
1210 inline Module *getParent() { return Parent; }
1211 inline const Module *getParent() const { return Parent; }
1213 MDNode *getOperand(unsigned i) const;
1214 unsigned getNumOperands() const;
1215 void addOperand(MDNode *M);
1216 void setOperand(unsigned I, MDNode *New);
1217 StringRef getName() const;
1218 void print(raw_ostream &ROS) const;
1221 // ---------------------------------------------------------------------------
1222 // Operand Iterator interface...
1224 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1225 op_iterator op_begin() { return op_iterator(this, 0); }
1226 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1228 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1229 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1230 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1232 inline iterator_range<op_iterator> operands() {
1233 return iterator_range<op_iterator>(op_begin(), op_end());
1235 inline iterator_range<const_op_iterator> operands() const {
1236 return iterator_range<const_op_iterator>(op_begin(), op_end());
1240 } // end llvm namespace