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.
54 StorageType Storage : 2;
55 // TODO: expose remaining bits to subclasses.
57 unsigned short SubclassData16;
58 unsigned SubclassData32;
64 ConstantAsMetadataKind,
70 Metadata(unsigned ID, StorageType Storage)
71 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
75 /// \brief Default handling of a changed operand, which asserts.
77 /// If subclasses pass themselves in as owners to a tracking node reference,
78 /// they must provide an implementation of this method.
79 void handleChangedOperand(void *, Metadata *) {
80 llvm_unreachable("Unimplemented in Metadata subclass");
84 unsigned getMetadataID() const { return SubclassID; }
86 /// \brief User-friendly dump.
88 void print(raw_ostream &OS) const;
89 void printAsOperand(raw_ostream &OS, bool PrintType = true,
90 const Module *M = nullptr) const;
93 #define HANDLE_METADATA(CLASS) class CLASS;
94 #include "llvm/IR/Metadata.def"
96 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
101 /// \brief Metadata wrapper in the Value hierarchy.
103 /// A member of the \a Value hierarchy to represent a reference to metadata.
104 /// This allows, e.g., instrinsics to have metadata as operands.
106 /// Notably, this is the only thing in either hierarchy that is allowed to
107 /// reference \a LocalAsMetadata.
108 class MetadataAsValue : public Value {
109 friend class ReplaceableMetadataImpl;
110 friend class LLVMContextImpl;
114 MetadataAsValue(Type *Ty, Metadata *MD);
117 /// \brief Drop use of metadata (during teardown).
118 void dropUse() { MD = nullptr; }
121 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
122 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
123 Metadata *getMetadata() const { return MD; }
125 static bool classof(const Value *V) {
126 return V->getValueID() == MetadataAsValueVal;
130 void handleChangedMetadata(Metadata *MD);
135 /// \brief Shared implementation of use-lists for replaceable metadata.
137 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
138 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
139 /// and \a TempMDNode).
140 class ReplaceableMetadataImpl {
141 friend class MetadataTracking;
144 typedef MetadataTracking::OwnerTy OwnerTy;
147 LLVMContext &Context;
149 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
152 ReplaceableMetadataImpl(LLVMContext &Context)
153 : Context(Context), NextIndex(0) {}
154 ~ReplaceableMetadataImpl() {
155 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
158 LLVMContext &getContext() const { return Context; }
160 /// \brief Replace all uses of this with MD.
162 /// Replace all uses of this with \c MD, which is allowed to be null.
163 void replaceAllUsesWith(Metadata *MD);
165 /// \brief Resolve all uses of this.
167 /// Resolve all uses of this, turning off RAUW permanently. If \c
168 /// ResolveUsers, call \a UniquableMDNode::resolve() on any users whose last
169 /// operand is resolved.
170 void resolveAllUses(bool ResolveUsers = true);
173 void addRef(void *Ref, OwnerTy Owner);
174 void dropRef(void *Ref);
175 void moveRef(void *Ref, void *New, const Metadata &MD);
177 static ReplaceableMetadataImpl *get(Metadata &MD);
180 /// \brief Value wrapper in the Metadata hierarchy.
182 /// This is a custom value handle that allows other metadata to refer to
183 /// classes in the Value hierarchy.
185 /// Because of full uniquing support, each value is only wrapped by a single \a
186 /// ValueAsMetadata object, so the lookup maps are far more efficient than
187 /// those using ValueHandleBase.
188 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
189 friend class ReplaceableMetadataImpl;
190 friend class LLVMContextImpl;
194 /// \brief Drop users without RAUW (during teardown).
196 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
200 ValueAsMetadata(unsigned ID, Value *V)
201 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
202 assert(V && "Expected valid value");
204 ~ValueAsMetadata() {}
207 static ValueAsMetadata *get(Value *V);
208 static ConstantAsMetadata *getConstant(Value *C) {
209 return cast<ConstantAsMetadata>(get(C));
211 static LocalAsMetadata *getLocal(Value *Local) {
212 return cast<LocalAsMetadata>(get(Local));
215 static ValueAsMetadata *getIfExists(Value *V);
216 static ConstantAsMetadata *getConstantIfExists(Value *C) {
217 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
219 static LocalAsMetadata *getLocalIfExists(Value *Local) {
220 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
223 Value *getValue() const { return V; }
224 Type *getType() const { return V->getType(); }
225 LLVMContext &getContext() const { return V->getContext(); }
227 static void handleDeletion(Value *V);
228 static void handleRAUW(Value *From, Value *To);
231 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
233 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
234 /// \a Value gets RAUW'ed and the target already exists, this is used to
235 /// merge the two metadata nodes.
236 void replaceAllUsesWith(Metadata *MD) {
237 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
241 static bool classof(const Metadata *MD) {
242 return MD->getMetadataID() == LocalAsMetadataKind ||
243 MD->getMetadataID() == ConstantAsMetadataKind;
247 class ConstantAsMetadata : public ValueAsMetadata {
248 friend class ValueAsMetadata;
250 ConstantAsMetadata(Constant *C)
251 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
254 static ConstantAsMetadata *get(Constant *C) {
255 return ValueAsMetadata::getConstant(C);
257 static ConstantAsMetadata *getIfExists(Constant *C) {
258 return ValueAsMetadata::getConstantIfExists(C);
261 Constant *getValue() const {
262 return cast<Constant>(ValueAsMetadata::getValue());
265 static bool classof(const Metadata *MD) {
266 return MD->getMetadataID() == ConstantAsMetadataKind;
270 class LocalAsMetadata : public ValueAsMetadata {
271 friend class ValueAsMetadata;
273 LocalAsMetadata(Value *Local)
274 : ValueAsMetadata(LocalAsMetadataKind, Local) {
275 assert(!isa<Constant>(Local) && "Expected local value");
279 static LocalAsMetadata *get(Value *Local) {
280 return ValueAsMetadata::getLocal(Local);
282 static LocalAsMetadata *getIfExists(Value *Local) {
283 return ValueAsMetadata::getLocalIfExists(Local);
286 static bool classof(const Metadata *MD) {
287 return MD->getMetadataID() == LocalAsMetadataKind;
291 /// \brief Transitional API for extracting constants from Metadata.
293 /// This namespace contains transitional functions for metadata that points to
296 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
297 /// operands could refer to any \a Value. There's was a lot of code like this:
301 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
304 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
305 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
306 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
307 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
308 /// requires subtle control flow changes.
310 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
311 /// so that metadata can refer to numbers without traversing a bridge to the \a
312 /// Value hierarchy. In this final state, the code above would look like this:
316 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
319 /// The API in this namespace supports the transition. \a MDInt doesn't exist
320 /// yet, and even once it does, changing each metadata schema to use it is its
321 /// own mini-project. In the meantime this API prevents us from introducing
322 /// complex and bug-prone control flow that will disappear in the end. In
323 /// particular, the above code looks like this:
327 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
330 /// The full set of provided functions includes:
332 /// mdconst::hasa <=> isa
333 /// mdconst::extract <=> cast
334 /// mdconst::extract_or_null <=> cast_or_null
335 /// mdconst::dyn_extract <=> dyn_cast
336 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
338 /// The target of the cast must be a subclass of \a Constant.
342 template <class T> T &make();
343 template <class T, class Result> struct HasDereference {
346 template <size_t N> struct SFINAE {};
348 template <class U, class V>
349 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
350 template <class U, class V> static No &hasDereference(...);
352 static const bool value =
353 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
355 template <class V, class M> struct IsValidPointer {
356 static const bool value = std::is_base_of<Constant, V>::value &&
357 HasDereference<M, const Metadata &>::value;
359 template <class V, class M> struct IsValidReference {
360 static const bool value = std::is_base_of<Constant, V>::value &&
361 std::is_convertible<M, const Metadata &>::value;
363 } // end namespace detail
365 /// \brief Check whether Metadata has a Value.
367 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
369 template <class X, class Y>
370 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
372 assert(MD && "Null pointer sent into hasa");
373 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
374 return isa<X>(V->getValue());
377 template <class X, class Y>
379 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
384 /// \brief Extract a Value from Metadata.
386 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
387 template <class X, class Y>
388 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
390 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
392 template <class X, class Y>
394 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
399 /// \brief Extract a Value from Metadata, allowing null.
401 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
402 /// from \c MD, allowing \c MD to be null.
403 template <class X, class Y>
404 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
405 extract_or_null(Y &&MD) {
406 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
407 return cast<X>(V->getValue());
411 /// \brief Extract a Value from Metadata, if any.
413 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
414 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
415 /// Value it does contain is of the wrong subclass.
416 template <class X, class Y>
417 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
418 dyn_extract(Y &&MD) {
419 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
420 return dyn_cast<X>(V->getValue());
424 /// \brief Extract a Value from Metadata, if any, allowing null.
426 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
427 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
428 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
429 template <class X, class Y>
430 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
431 dyn_extract_or_null(Y &&MD) {
432 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
433 return dyn_cast<X>(V->getValue());
437 } // end namespace mdconst
439 //===----------------------------------------------------------------------===//
440 /// \brief A single uniqued string.
442 /// These are used to efficiently contain a byte sequence for metadata.
443 /// MDString is always unnamed.
444 class MDString : public Metadata {
445 friend class StringMapEntry<MDString>;
447 MDString(const MDString &) LLVM_DELETED_FUNCTION;
448 MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
449 MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
451 StringMapEntry<MDString> *Entry;
452 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
453 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
456 static MDString *get(LLVMContext &Context, StringRef Str);
457 static MDString *get(LLVMContext &Context, const char *Str) {
458 return get(Context, Str ? StringRef(Str) : StringRef());
461 StringRef getString() const;
463 unsigned getLength() const { return (unsigned)getString().size(); }
465 typedef StringRef::iterator iterator;
467 /// \brief Pointer to the first byte of the string.
468 iterator begin() const { return getString().begin(); }
470 /// \brief Pointer to one byte past the end of the string.
471 iterator end() const { return getString().end(); }
473 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
474 const unsigned char *bytes_end() const { return getString().bytes_end(); }
476 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
477 static bool classof(const Metadata *MD) {
478 return MD->getMetadataID() == MDStringKind;
482 /// \brief A collection of metadata nodes that might be associated with a
483 /// memory access used by the alias-analysis infrastructure.
485 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
487 : TBAA(T), Scope(S), NoAlias(N) {}
489 bool operator==(const AAMDNodes &A) const {
490 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
493 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
495 LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
497 /// \brief The tag for type-based alias analysis.
500 /// \brief The tag for alias scope specification (used with noalias).
503 /// \brief The tag specifying the noalias scope.
507 // Specialize DenseMapInfo for AAMDNodes.
509 struct DenseMapInfo<AAMDNodes> {
510 static inline AAMDNodes getEmptyKey() {
511 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
513 static inline AAMDNodes getTombstoneKey() {
514 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
516 static unsigned getHashValue(const AAMDNodes &Val) {
517 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
518 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
519 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
521 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
526 /// \brief Tracking metadata reference owned by Metadata.
528 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
529 /// of \a Metadata, which has the option of registering itself for callbacks to
530 /// re-unique itself.
532 /// In particular, this is used by \a MDNode.
534 MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
535 MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
536 MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
537 MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
542 MDOperand() : MD(nullptr) {}
543 ~MDOperand() { untrack(); }
545 Metadata *get() const { return MD; }
546 operator Metadata *() const { return get(); }
547 Metadata *operator->() const { return get(); }
548 Metadata &operator*() const { return *get(); }
554 void reset(Metadata *MD, Metadata *Owner) {
561 void track(Metadata *Owner) {
564 MetadataTracking::track(this, *MD, *Owner);
566 MetadataTracking::track(MD);
570 assert(static_cast<void *>(this) == &MD && "Expected same address");
572 MetadataTracking::untrack(MD);
576 template <> struct simplify_type<MDOperand> {
577 typedef Metadata *SimpleType;
578 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
581 template <> struct simplify_type<const MDOperand> {
582 typedef Metadata *SimpleType;
583 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
586 /// \brief Pointer to the context, with optional RAUW support.
588 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
589 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
590 class ContextAndReplaceableUses {
591 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
593 ContextAndReplaceableUses() LLVM_DELETED_FUNCTION;
594 ContextAndReplaceableUses(ContextAndReplaceableUses &&)
595 LLVM_DELETED_FUNCTION;
596 ContextAndReplaceableUses(const ContextAndReplaceableUses &)
597 LLVM_DELETED_FUNCTION;
598 ContextAndReplaceableUses &
599 operator=(ContextAndReplaceableUses &&) LLVM_DELETED_FUNCTION;
600 ContextAndReplaceableUses &
601 operator=(const ContextAndReplaceableUses &) LLVM_DELETED_FUNCTION;
604 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
605 ContextAndReplaceableUses(
606 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
607 : Ptr(ReplaceableUses.release()) {
608 assert(getReplaceableUses() && "Expected non-null replaceable uses");
610 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
612 operator LLVMContext &() { return getContext(); }
614 /// \brief Whether this contains RAUW support.
615 bool hasReplaceableUses() const {
616 return Ptr.is<ReplaceableMetadataImpl *>();
618 LLVMContext &getContext() const {
619 if (hasReplaceableUses())
620 return getReplaceableUses()->getContext();
621 return *Ptr.get<LLVMContext *>();
623 ReplaceableMetadataImpl *getReplaceableUses() const {
624 if (hasReplaceableUses())
625 return Ptr.get<ReplaceableMetadataImpl *>();
629 /// \brief Assign RAUW support to this.
631 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
634 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
635 assert(ReplaceableUses && "Expected non-null replaceable uses");
636 assert(&ReplaceableUses->getContext() == &getContext() &&
637 "Expected same context");
638 delete getReplaceableUses();
639 Ptr = ReplaceableUses.release();
642 /// \brief Drop RAUW support.
644 /// Cede ownership of RAUW support, returning it.
645 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
646 assert(hasReplaceableUses() && "Expected to own replaceable uses");
647 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
648 getReplaceableUses());
649 Ptr = &ReplaceableUses->getContext();
650 return ReplaceableUses;
655 struct TempMDNodeDeleter {
656 inline void operator()(T *Node) const;
659 #define HANDLE_UNIQUABLE_LEAF(CLASS) \
660 typedef std::unique_ptr<CLASS, TempMDNodeDeleter<CLASS>> Temp##CLASS;
661 #include "llvm/IR/Metadata.def"
663 //===----------------------------------------------------------------------===//
664 /// \brief Tuple of metadata.
665 class MDNode : public Metadata {
666 friend class ReplaceableMetadataImpl;
668 MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
669 void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
670 void *operator new(size_t) LLVM_DELETED_FUNCTION;
673 ContextAndReplaceableUses Context;
676 unsigned NumOperands;
679 unsigned MDNodeSubclassData;
681 void *operator new(size_t Size, unsigned NumOps);
682 void operator delete(void *Mem);
684 /// \brief Required by std, but never called.
685 void operator delete(void *, unsigned) {
686 llvm_unreachable("Constructor throws?");
689 /// \brief Required by std, but never called.
690 void operator delete(void *, unsigned, bool) {
691 llvm_unreachable("Constructor throws?");
694 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
695 ArrayRef<Metadata *> MDs);
698 void dropAllReferences();
700 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
701 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
704 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
705 static inline MDTuple *getIfExists(LLVMContext &Context,
706 ArrayRef<Metadata *> MDs);
707 static inline MDTuple *getDistinct(LLVMContext &Context,
708 ArrayRef<Metadata *> MDs);
709 static inline TempMDTuple getTemporary(LLVMContext &Context,
710 ArrayRef<Metadata *> MDs);
712 /// \brief Deallocate a node created by getTemporary.
714 /// The node must not have any users.
715 static void deleteTemporary(MDNode *N);
717 LLVMContext &getContext() const { return Context.getContext(); }
719 /// \brief Replace a specific operand.
720 void replaceOperandWith(unsigned I, Metadata *New);
722 /// \brief Check if node is fully resolved.
724 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
725 /// this always returns \c true.
727 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
728 /// support (because all operands are resolved).
730 /// As forward declarations are resolved, their containers should get
731 /// resolved automatically. However, if this (or one of its operands) is
732 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
733 bool isResolved() const { return !Context.hasReplaceableUses(); }
735 bool isUniqued() const { return Storage == Uniqued; }
736 bool isDistinct() const { return Storage == Distinct; }
737 bool isTemporary() const { return Storage == Temporary; }
739 /// \brief RAUW a temporary.
741 /// \pre \a isTemporary() must be \c true.
742 void replaceAllUsesWith(Metadata *MD) {
743 assert(isTemporary() && "Expected temporary node");
744 assert(!isResolved() && "Expected RAUW support");
745 Context.getReplaceableUses()->replaceAllUsesWith(MD);
749 /// \brief Set an operand.
751 /// Sets the operand directly, without worrying about uniquing.
752 void setOperand(unsigned I, Metadata *New);
755 typedef const MDOperand *op_iterator;
756 typedef iterator_range<op_iterator> op_range;
758 op_iterator op_begin() const {
759 return const_cast<MDNode *>(this)->mutable_begin();
761 op_iterator op_end() const {
762 return const_cast<MDNode *>(this)->mutable_end();
764 op_range operands() const { return op_range(op_begin(), op_end()); }
766 const MDOperand &getOperand(unsigned I) const {
767 assert(I < NumOperands && "Out of range");
768 return op_begin()[I];
771 /// \brief Return number of MDNode operands.
772 unsigned getNumOperands() const { return NumOperands; }
774 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
775 static bool classof(const Metadata *MD) {
776 return MD->getMetadataID() == MDTupleKind ||
777 MD->getMetadataID() == MDLocationKind;
780 /// \brief Check whether MDNode is a vtable access.
781 bool isTBAAVtableAccess() const;
783 /// \brief Methods for metadata merging.
784 static MDNode *concatenate(MDNode *A, MDNode *B);
785 static MDNode *intersect(MDNode *A, MDNode *B);
786 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
787 static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
788 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
789 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
792 /// \brief Uniquable metadata node.
794 /// A uniquable metadata node. This contains the basic functionality
795 /// for implementing sub-types of \a MDNode that can be uniqued like
798 /// There is limited support for RAUW at construction time. At construction
799 /// time, if any operand is a temporary node (or an unresolved uniqued node,
800 /// which indicates a transitive temporary operand), the node itself will be
801 /// unresolved. As soon as all operands become resolved, it will drop RAUW
802 /// support permanently.
804 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
805 /// to be called on some member of the cycle once all temporary nodes have been
807 class UniquableMDNode : public MDNode {
808 friend class ReplaceableMetadataImpl;
810 friend class LLVMContextImpl;
813 /// \brief Create a new node.
815 /// If \c AllowRAUW, then if any operands are unresolved support RAUW. RAUW
816 /// will be dropped once all operands have been resolved (or if \a
817 /// resolveCycles() is called).
818 UniquableMDNode(LLVMContext &C, unsigned ID, StorageType Storage,
819 ArrayRef<Metadata *> Vals);
820 ~UniquableMDNode() {}
822 void storeDistinctInContext();
823 template <class T, class StoreT>
824 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
827 static bool classof(const Metadata *MD) {
828 return MD->getMetadataID() == MDTupleKind ||
829 MD->getMetadataID() == MDLocationKind;
832 /// \brief Resolve cycles.
834 /// Once all forward declarations have been resolved, force cycles to be
837 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
838 void resolveCycles();
841 void handleChangedOperand(void *Ref, Metadata *New);
844 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
845 void decrementUnresolvedOperandCount();
847 void deleteAsSubclass();
848 UniquableMDNode *uniquify();
849 void eraseFromStore();
852 /// \brief Tuple of metadata.
854 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
855 /// default based on their operands.
856 class MDTuple : public UniquableMDNode {
857 friend class LLVMContextImpl;
858 friend class UniquableMDNode;
860 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
861 ArrayRef<Metadata *> Vals)
862 : UniquableMDNode(C, MDTupleKind, Storage, Vals) {
865 ~MDTuple() { dropAllReferences(); }
867 void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
868 void recalculateHash();
870 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
871 StorageType Storage, bool ShouldCreate = true);
874 /// \brief Get the hash, if any.
875 unsigned getHash() const { return MDNodeSubclassData; }
877 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
878 return getImpl(Context, MDs, Uniqued);
880 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
881 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
884 /// \brief Return a distinct node.
886 /// Return a distinct node -- i.e., a node that is not uniqued.
887 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
888 return getImpl(Context, MDs, Distinct);
891 /// \brief Return a temporary node.
893 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
894 /// not uniqued, may be RAUW'd, and must be manually deleted with
896 static TempMDTuple getTemporary(LLVMContext &Context,
897 ArrayRef<Metadata *> MDs) {
898 return TempMDTuple(getImpl(Context, MDs, Temporary));
901 static bool classof(const Metadata *MD) {
902 return MD->getMetadataID() == MDTupleKind;
906 MDTuple *uniquifyImpl();
907 void eraseFromStoreImpl();
910 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
911 return MDTuple::get(Context, MDs);
913 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
914 return MDTuple::getIfExists(Context, MDs);
916 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
917 return MDTuple::getDistinct(Context, MDs);
919 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
920 ArrayRef<Metadata *> MDs) {
921 return MDTuple::getTemporary(Context, MDs);
924 void TempMDNodeDeleter<T>::operator()(T *Node) const {
925 MDNode::deleteTemporary(Node);
928 /// \brief Debug location.
930 /// A debug location in source code, used for debug info and otherwise.
931 class MDLocation : public UniquableMDNode {
932 friend class LLVMContextImpl;
933 friend class UniquableMDNode;
935 MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
936 unsigned Column, ArrayRef<Metadata *> MDs);
937 ~MDLocation() { dropAllReferences(); }
939 static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
940 unsigned Column, Metadata *Scope,
941 Metadata *InlinedAt, StorageType Storage,
942 bool ShouldCreate = true);
944 // Disallow replacing operands.
945 void replaceOperandWith(unsigned I, Metadata *New) LLVM_DELETED_FUNCTION;
948 static MDLocation *get(LLVMContext &Context, unsigned Line, unsigned Column,
949 Metadata *Scope, Metadata *InlinedAt = nullptr) {
950 return getImpl(Context, Line, Column, Scope, InlinedAt, Uniqued);
952 static MDLocation *getIfExists(LLVMContext &Context, unsigned Line,
953 unsigned Column, Metadata *Scope,
954 Metadata *InlinedAt = nullptr) {
955 return getImpl(Context, Line, Column, Scope, InlinedAt, Uniqued,
956 /* ShouldCreate */ false);
958 static MDLocation *getDistinct(LLVMContext &Context, unsigned Line,
959 unsigned Column, Metadata *Scope,
960 Metadata *InlinedAt = nullptr) {
961 return getImpl(Context, Line, Column, Scope, InlinedAt, Distinct);
963 static TempMDLocation getTemporary(LLVMContext &Context, unsigned Line,
964 unsigned Column, Metadata *Scope,
965 Metadata *InlinedAt = nullptr) {
966 return TempMDLocation(
967 getImpl(Context, Line, Column, Scope, InlinedAt, Temporary));
970 unsigned getLine() const { return MDNodeSubclassData; }
971 unsigned getColumn() const { return SubclassData16; }
972 Metadata *getScope() const { return getOperand(0); }
973 Metadata *getInlinedAt() const {
974 if (getNumOperands() == 2)
975 return getOperand(1);
979 static bool classof(const Metadata *MD) {
980 return MD->getMetadataID() == MDLocationKind;
984 MDLocation *uniquifyImpl();
985 void eraseFromStoreImpl();
988 //===----------------------------------------------------------------------===//
989 /// \brief A tuple of MDNodes.
991 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
992 /// to modules, have names, and contain lists of MDNodes.
994 /// TODO: Inherit from Metadata.
995 class NamedMDNode : public ilist_node<NamedMDNode> {
996 friend class SymbolTableListTraits<NamedMDNode, Module>;
997 friend struct ilist_traits<NamedMDNode>;
998 friend class LLVMContextImpl;
1000 NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
1004 void *Operands; // SmallVector<TrackingMDRef, 4>
1006 void setParent(Module *M) { Parent = M; }
1008 explicit NamedMDNode(const Twine &N);
1010 template<class T1, class T2>
1011 class op_iterator_impl :
1012 public std::iterator<std::bidirectional_iterator_tag, T2> {
1013 const NamedMDNode *Node;
1015 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1017 friend class NamedMDNode;
1020 op_iterator_impl() : Node(nullptr), Idx(0) { }
1022 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1023 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1024 op_iterator_impl &operator++() {
1028 op_iterator_impl operator++(int) {
1029 op_iterator_impl tmp(*this);
1033 op_iterator_impl &operator--() {
1037 op_iterator_impl operator--(int) {
1038 op_iterator_impl tmp(*this);
1043 T1 operator*() const { return Node->getOperand(Idx); }
1047 /// \brief Drop all references and remove the node from parent module.
1048 void eraseFromParent();
1050 /// \brief Remove all uses and clear node vector.
1051 void dropAllReferences();
1055 /// \brief Get the module that holds this named metadata collection.
1056 inline Module *getParent() { return Parent; }
1057 inline const Module *getParent() const { return Parent; }
1059 MDNode *getOperand(unsigned i) const;
1060 unsigned getNumOperands() const;
1061 void addOperand(MDNode *M);
1062 void setOperand(unsigned I, MDNode *New);
1063 StringRef getName() const;
1064 void print(raw_ostream &ROS) const;
1067 // ---------------------------------------------------------------------------
1068 // Operand Iterator interface...
1070 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1071 op_iterator op_begin() { return op_iterator(this, 0); }
1072 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1074 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1075 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1076 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1078 inline iterator_range<op_iterator> operands() {
1079 return iterator_range<op_iterator>(op_begin(), op_end());
1081 inline iterator_range<const_op_iterator> operands() const {
1082 return iterator_range<const_op_iterator>(op_begin(), op_end());
1086 } // end llvm namespace