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;
65 ConstantAsMetadataKind,
71 Metadata(unsigned ID, StorageType Storage)
72 : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
76 /// \brief Store this in a big non-uniqued untyped bucket.
77 bool isStoredDistinctInContext() const { return Storage == Distinct; }
79 /// \brief Default handling of a changed operand, which asserts.
81 /// If subclasses pass themselves in as owners to a tracking node reference,
82 /// they must provide an implementation of this method.
83 void handleChangedOperand(void *, Metadata *) {
84 llvm_unreachable("Unimplemented in Metadata subclass");
88 unsigned getMetadataID() const { return SubclassID; }
90 /// \brief User-friendly dump.
92 void print(raw_ostream &OS) const;
93 void printAsOperand(raw_ostream &OS, bool PrintType = true,
94 const Module *M = nullptr) const;
97 #define HANDLE_METADATA(CLASS) class CLASS;
98 #include "llvm/IR/Metadata.def"
100 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
105 /// \brief Metadata wrapper in the Value hierarchy.
107 /// A member of the \a Value hierarchy to represent a reference to metadata.
108 /// This allows, e.g., instrinsics to have metadata as operands.
110 /// Notably, this is the only thing in either hierarchy that is allowed to
111 /// reference \a LocalAsMetadata.
112 class MetadataAsValue : public Value {
113 friend class ReplaceableMetadataImpl;
114 friend class LLVMContextImpl;
118 MetadataAsValue(Type *Ty, Metadata *MD);
121 /// \brief Drop use of metadata (during teardown).
122 void dropUse() { MD = nullptr; }
125 static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
126 static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
127 Metadata *getMetadata() const { return MD; }
129 static bool classof(const Value *V) {
130 return V->getValueID() == MetadataAsValueVal;
134 void handleChangedMetadata(Metadata *MD);
139 /// \brief Shared implementation of use-lists for replaceable metadata.
141 /// Most metadata cannot be RAUW'ed. This is a shared implementation of
142 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
143 /// and \a TempMDNode).
144 class ReplaceableMetadataImpl {
145 friend class MetadataTracking;
148 typedef MetadataTracking::OwnerTy OwnerTy;
151 LLVMContext &Context;
153 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
156 ReplaceableMetadataImpl(LLVMContext &Context)
157 : Context(Context), NextIndex(0) {}
158 ~ReplaceableMetadataImpl() {
159 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
162 LLVMContext &getContext() const { return Context; }
164 /// \brief Replace all uses of this with MD.
166 /// Replace all uses of this with \c MD, which is allowed to be null.
167 void replaceAllUsesWith(Metadata *MD);
169 /// \brief Resolve all uses of this.
171 /// Resolve all uses of this, turning off RAUW permanently. If \c
172 /// ResolveUsers, call \a UniquableMDNode::resolve() on any users whose last
173 /// operand is resolved.
174 void resolveAllUses(bool ResolveUsers = true);
177 void addRef(void *Ref, OwnerTy Owner);
178 void dropRef(void *Ref);
179 void moveRef(void *Ref, void *New, const Metadata &MD);
181 static ReplaceableMetadataImpl *get(Metadata &MD);
184 /// \brief Value wrapper in the Metadata hierarchy.
186 /// This is a custom value handle that allows other metadata to refer to
187 /// classes in the Value hierarchy.
189 /// Because of full uniquing support, each value is only wrapped by a single \a
190 /// ValueAsMetadata object, so the lookup maps are far more efficient than
191 /// those using ValueHandleBase.
192 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
193 friend class ReplaceableMetadataImpl;
194 friend class LLVMContextImpl;
198 /// \brief Drop users without RAUW (during teardown).
200 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
204 ValueAsMetadata(unsigned ID, Value *V)
205 : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
206 assert(V && "Expected valid value");
208 ~ValueAsMetadata() {}
211 static ValueAsMetadata *get(Value *V);
212 static ConstantAsMetadata *getConstant(Value *C) {
213 return cast<ConstantAsMetadata>(get(C));
215 static LocalAsMetadata *getLocal(Value *Local) {
216 return cast<LocalAsMetadata>(get(Local));
219 static ValueAsMetadata *getIfExists(Value *V);
220 static ConstantAsMetadata *getConstantIfExists(Value *C) {
221 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
223 static LocalAsMetadata *getLocalIfExists(Value *Local) {
224 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
227 Value *getValue() const { return V; }
228 Type *getType() const { return V->getType(); }
229 LLVMContext &getContext() const { return V->getContext(); }
231 static void handleDeletion(Value *V);
232 static void handleRAUW(Value *From, Value *To);
235 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
237 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
238 /// \a Value gets RAUW'ed and the target already exists, this is used to
239 /// merge the two metadata nodes.
240 void replaceAllUsesWith(Metadata *MD) {
241 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
245 static bool classof(const Metadata *MD) {
246 return MD->getMetadataID() == LocalAsMetadataKind ||
247 MD->getMetadataID() == ConstantAsMetadataKind;
251 class ConstantAsMetadata : public ValueAsMetadata {
252 friend class ValueAsMetadata;
254 ConstantAsMetadata(Constant *C)
255 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
258 static ConstantAsMetadata *get(Constant *C) {
259 return ValueAsMetadata::getConstant(C);
261 static ConstantAsMetadata *getIfExists(Constant *C) {
262 return ValueAsMetadata::getConstantIfExists(C);
265 Constant *getValue() const {
266 return cast<Constant>(ValueAsMetadata::getValue());
269 static bool classof(const Metadata *MD) {
270 return MD->getMetadataID() == ConstantAsMetadataKind;
274 class LocalAsMetadata : public ValueAsMetadata {
275 friend class ValueAsMetadata;
277 LocalAsMetadata(Value *Local)
278 : ValueAsMetadata(LocalAsMetadataKind, Local) {
279 assert(!isa<Constant>(Local) && "Expected local value");
283 static LocalAsMetadata *get(Value *Local) {
284 return ValueAsMetadata::getLocal(Local);
286 static LocalAsMetadata *getIfExists(Value *Local) {
287 return ValueAsMetadata::getLocalIfExists(Local);
290 static bool classof(const Metadata *MD) {
291 return MD->getMetadataID() == LocalAsMetadataKind;
295 /// \brief Transitional API for extracting constants from Metadata.
297 /// This namespace contains transitional functions for metadata that points to
300 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
301 /// operands could refer to any \a Value. There's was a lot of code like this:
305 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
308 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
309 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
310 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
311 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
312 /// requires subtle control flow changes.
314 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
315 /// so that metadata can refer to numbers without traversing a bridge to the \a
316 /// Value hierarchy. In this final state, the code above would look like this:
320 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
323 /// The API in this namespace supports the transition. \a MDInt doesn't exist
324 /// yet, and even once it does, changing each metadata schema to use it is its
325 /// own mini-project. In the meantime this API prevents us from introducing
326 /// complex and bug-prone control flow that will disappear in the end. In
327 /// particular, the above code looks like this:
331 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
334 /// The full set of provided functions includes:
336 /// mdconst::hasa <=> isa
337 /// mdconst::extract <=> cast
338 /// mdconst::extract_or_null <=> cast_or_null
339 /// mdconst::dyn_extract <=> dyn_cast
340 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
342 /// The target of the cast must be a subclass of \a Constant.
346 template <class T> T &make();
347 template <class T, class Result> struct HasDereference {
350 template <size_t N> struct SFINAE {};
352 template <class U, class V>
353 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
354 template <class U, class V> static No &hasDereference(...);
356 static const bool value =
357 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
359 template <class V, class M> struct IsValidPointer {
360 static const bool value = std::is_base_of<Constant, V>::value &&
361 HasDereference<M, const Metadata &>::value;
363 template <class V, class M> struct IsValidReference {
364 static const bool value = std::is_base_of<Constant, V>::value &&
365 std::is_convertible<M, const Metadata &>::value;
367 } // end namespace detail
369 /// \brief Check whether Metadata has a Value.
371 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
373 template <class X, class Y>
374 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
376 assert(MD && "Null pointer sent into hasa");
377 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
378 return isa<X>(V->getValue());
381 template <class X, class Y>
383 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
388 /// \brief Extract a Value from Metadata.
390 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
391 template <class X, class Y>
392 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
394 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
396 template <class X, class Y>
398 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
403 /// \brief Extract a Value from Metadata, allowing null.
405 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
406 /// from \c MD, allowing \c MD to be null.
407 template <class X, class Y>
408 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
409 extract_or_null(Y &&MD) {
410 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
411 return cast<X>(V->getValue());
415 /// \brief Extract a Value from Metadata, if any.
417 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
418 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
419 /// Value it does contain is of the wrong subclass.
420 template <class X, class Y>
421 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
422 dyn_extract(Y &&MD) {
423 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
424 return dyn_cast<X>(V->getValue());
428 /// \brief Extract a Value from Metadata, if any, allowing null.
430 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
431 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
432 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
433 template <class X, class Y>
434 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
435 dyn_extract_or_null(Y &&MD) {
436 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
437 return dyn_cast<X>(V->getValue());
441 } // end namespace mdconst
443 //===----------------------------------------------------------------------===//
444 /// \brief A single uniqued string.
446 /// These are used to efficiently contain a byte sequence for metadata.
447 /// MDString is always unnamed.
448 class MDString : public Metadata {
449 friend class StringMapEntry<MDString>;
451 MDString(const MDString &) LLVM_DELETED_FUNCTION;
452 MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
453 MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
455 StringMapEntry<MDString> *Entry;
456 MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
457 MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
460 static MDString *get(LLVMContext &Context, StringRef Str);
461 static MDString *get(LLVMContext &Context, const char *Str) {
462 return get(Context, Str ? StringRef(Str) : StringRef());
465 StringRef getString() const;
467 unsigned getLength() const { return (unsigned)getString().size(); }
469 typedef StringRef::iterator iterator;
471 /// \brief Pointer to the first byte of the string.
472 iterator begin() const { return getString().begin(); }
474 /// \brief Pointer to one byte past the end of the string.
475 iterator end() const { return getString().end(); }
477 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
478 const unsigned char *bytes_end() const { return getString().bytes_end(); }
480 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
481 static bool classof(const Metadata *MD) {
482 return MD->getMetadataID() == MDStringKind;
486 /// \brief A collection of metadata nodes that might be associated with a
487 /// memory access used by the alias-analysis infrastructure.
489 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
491 : TBAA(T), Scope(S), NoAlias(N) {}
493 bool operator==(const AAMDNodes &A) const {
494 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
497 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
499 LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
501 /// \brief The tag for type-based alias analysis.
504 /// \brief The tag for alias scope specification (used with noalias).
507 /// \brief The tag specifying the noalias scope.
511 // Specialize DenseMapInfo for AAMDNodes.
513 struct DenseMapInfo<AAMDNodes> {
514 static inline AAMDNodes getEmptyKey() {
515 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
517 static inline AAMDNodes getTombstoneKey() {
518 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
520 static unsigned getHashValue(const AAMDNodes &Val) {
521 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
522 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
523 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
525 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
530 /// \brief Tracking metadata reference owned by Metadata.
532 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
533 /// of \a Metadata, which has the option of registering itself for callbacks to
534 /// re-unique itself.
536 /// In particular, this is used by \a MDNode.
538 MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
539 MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
540 MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
541 MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
546 MDOperand() : MD(nullptr) {}
547 ~MDOperand() { untrack(); }
549 Metadata *get() const { return MD; }
550 operator Metadata *() const { return get(); }
551 Metadata *operator->() const { return get(); }
552 Metadata &operator*() const { return *get(); }
558 void reset(Metadata *MD, Metadata *Owner) {
565 void track(Metadata *Owner) {
568 MetadataTracking::track(this, *MD, *Owner);
570 MetadataTracking::track(MD);
574 assert(static_cast<void *>(this) == &MD && "Expected same address");
576 MetadataTracking::untrack(MD);
580 template <> struct simplify_type<MDOperand> {
581 typedef Metadata *SimpleType;
582 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
585 template <> struct simplify_type<const MDOperand> {
586 typedef Metadata *SimpleType;
587 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
590 /// \brief Pointer to the context, with optional RAUW support.
592 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
593 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
594 class ContextAndReplaceableUses {
595 PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
597 ContextAndReplaceableUses() LLVM_DELETED_FUNCTION;
598 ContextAndReplaceableUses(ContextAndReplaceableUses &&)
599 LLVM_DELETED_FUNCTION;
600 ContextAndReplaceableUses(const ContextAndReplaceableUses &)
601 LLVM_DELETED_FUNCTION;
602 ContextAndReplaceableUses &
603 operator=(ContextAndReplaceableUses &&) LLVM_DELETED_FUNCTION;
604 ContextAndReplaceableUses &
605 operator=(const ContextAndReplaceableUses &) LLVM_DELETED_FUNCTION;
608 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
609 ContextAndReplaceableUses(
610 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
611 : Ptr(ReplaceableUses.release()) {
612 assert(getReplaceableUses() && "Expected non-null replaceable uses");
614 ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
616 operator LLVMContext &() { return getContext(); }
618 /// \brief Whether this contains RAUW support.
619 bool hasReplaceableUses() const {
620 return Ptr.is<ReplaceableMetadataImpl *>();
622 LLVMContext &getContext() const {
623 if (hasReplaceableUses())
624 return getReplaceableUses()->getContext();
625 return *Ptr.get<LLVMContext *>();
627 ReplaceableMetadataImpl *getReplaceableUses() const {
628 if (hasReplaceableUses())
629 return Ptr.get<ReplaceableMetadataImpl *>();
633 /// \brief Assign RAUW support to this.
635 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
638 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
639 assert(ReplaceableUses && "Expected non-null replaceable uses");
640 assert(&ReplaceableUses->getContext() == &getContext() &&
641 "Expected same context");
642 delete getReplaceableUses();
643 Ptr = ReplaceableUses.release();
646 /// \brief Drop RAUW support.
648 /// Cede ownership of RAUW support, returning it.
649 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
650 assert(hasReplaceableUses() && "Expected to own replaceable uses");
651 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
652 getReplaceableUses());
653 Ptr = &ReplaceableUses->getContext();
654 return ReplaceableUses;
658 //===----------------------------------------------------------------------===//
659 /// \brief Tuple of metadata.
660 class MDNode : public Metadata {
661 friend class ReplaceableMetadataImpl;
663 MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
664 void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
665 void *operator new(size_t) LLVM_DELETED_FUNCTION;
668 ContextAndReplaceableUses Context;
671 unsigned NumOperands;
674 unsigned MDNodeSubclassData;
676 void *operator new(size_t Size, unsigned NumOps);
677 void operator delete(void *Mem);
679 /// \brief Required by std, but never called.
680 void operator delete(void *, unsigned) {
681 llvm_unreachable("Constructor throws?");
684 /// \brief Required by std, but never called.
685 void operator delete(void *, unsigned, bool) {
686 llvm_unreachable("Constructor throws?");
689 MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
690 ArrayRef<Metadata *> MDs);
693 void dropAllReferences();
695 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
696 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
699 static inline MDNode *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
700 static inline MDNode *getIfExists(LLVMContext &Context,
701 ArrayRef<Metadata *> MDs);
702 static inline MDNode *getDistinct(LLVMContext &Context,
703 ArrayRef<Metadata *> MDs);
705 /// \brief Return a temporary MDNode
707 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
708 /// not uniqued, may be RAUW'd, and must be manually deleted with
710 static MDNodeFwdDecl *getTemporary(LLVMContext &Context,
711 ArrayRef<Metadata *> MDs);
713 /// \brief Deallocate a node created by getTemporary.
715 /// The node must not have any users.
716 static void deleteTemporary(MDNode *N);
718 LLVMContext &getContext() const { return Context.getContext(); }
720 /// \brief Replace a specific operand.
721 void replaceOperandWith(unsigned I, Metadata *New);
723 /// \brief Check if node is fully resolved.
724 bool isResolved() const;
726 bool isUniqued() const { return Storage == Uniqued; }
727 bool isDistinct() const { return Storage == Distinct; }
728 bool isTemporary() const { return Storage == Temporary; }
731 /// \brief Set an operand.
733 /// Sets the operand directly, without worrying about uniquing.
734 void setOperand(unsigned I, Metadata *New);
737 typedef const MDOperand *op_iterator;
738 typedef iterator_range<op_iterator> op_range;
740 op_iterator op_begin() const {
741 return const_cast<MDNode *>(this)->mutable_begin();
743 op_iterator op_end() const {
744 return const_cast<MDNode *>(this)->mutable_end();
746 op_range operands() const { return op_range(op_begin(), op_end()); }
748 const MDOperand &getOperand(unsigned I) const {
749 assert(I < NumOperands && "Out of range");
750 return op_begin()[I];
753 /// \brief Return number of MDNode operands.
754 unsigned getNumOperands() const { return NumOperands; }
756 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
757 static bool classof(const Metadata *MD) {
758 return MD->getMetadataID() == MDTupleKind ||
759 MD->getMetadataID() == MDLocationKind ||
760 MD->getMetadataID() == MDNodeFwdDeclKind;
763 /// \brief Check whether MDNode is a vtable access.
764 bool isTBAAVtableAccess() const;
766 /// \brief Methods for metadata merging.
767 static MDNode *concatenate(MDNode *A, MDNode *B);
768 static MDNode *intersect(MDNode *A, MDNode *B);
769 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
770 static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
771 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
772 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
775 /// \brief Uniquable metadata node.
777 /// A uniquable metadata node. This contains the basic functionality
778 /// for implementing sub-types of \a MDNode that can be uniqued like
781 /// There is limited support for RAUW at construction time. At
782 /// construction time, if any operands are an instance of \a
783 /// MDNodeFwdDecl (or another unresolved \a UniquableMDNode, which
784 /// indicates an \a MDNodeFwdDecl in its path), the node itself will be
785 /// unresolved. As soon as all operands become resolved, it will drop
786 /// RAUW support permanently.
788 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
789 /// to be called on some member of the cycle when each \a MDNodeFwdDecl
790 /// has been removed.
791 class UniquableMDNode : public MDNode {
792 friend class ReplaceableMetadataImpl;
794 friend class LLVMContextImpl;
797 /// \brief Create a new node.
799 /// If \c AllowRAUW, then if any operands are unresolved support RAUW. RAUW
800 /// will be dropped once all operands have been resolved (or if \a
801 /// resolveCycles() is called).
802 UniquableMDNode(LLVMContext &C, unsigned ID, StorageType Storage,
803 ArrayRef<Metadata *> Vals);
804 ~UniquableMDNode() {}
806 void storeDistinctInContext();
809 static bool classof(const Metadata *MD) {
810 return MD->getMetadataID() == MDTupleKind ||
811 MD->getMetadataID() == MDLocationKind;
814 /// \brief Check whether any operands are forward declarations.
816 /// Returns \c true as long as any operands (or their operands, etc.) are \a
819 /// As forward declarations are resolved, their containers should get
820 /// resolved automatically. However, if this (or one of its operands) is
821 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
822 bool isResolved() const { return !Context.hasReplaceableUses(); }
824 /// \brief Resolve cycles.
826 /// Once all forward declarations have been resolved, force cycles to be
829 /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl.
830 void resolveCycles();
833 void handleChangedOperand(void *Ref, Metadata *New);
836 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
837 void decrementUnresolvedOperandCount();
839 void deleteAsSubclass();
840 UniquableMDNode *uniquify();
841 void eraseFromStore();
844 /// \brief Tuple of metadata.
846 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
847 /// default based on their operands.
848 class MDTuple : public UniquableMDNode {
849 friend class LLVMContextImpl;
850 friend class UniquableMDNode;
852 MDTuple(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Vals)
853 : UniquableMDNode(C, MDTupleKind, Storage, Vals) {}
854 ~MDTuple() { dropAllReferences(); }
856 void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
857 void recalculateHash();
859 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
863 /// \brief Get the hash, if any.
864 unsigned getHash() const { return MDNodeSubclassData; }
866 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
867 return getImpl(Context, MDs, /* ShouldCreate */ true);
869 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
870 return getImpl(Context, MDs, /* ShouldCreate */ false);
873 /// \brief Return a distinct node.
875 /// Return a distinct node -- i.e., a node that is not uniqued.
876 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs);
878 static bool classof(const Metadata *MD) {
879 return MD->getMetadataID() == MDTupleKind;
883 MDTuple *uniquifyImpl();
884 void eraseFromStoreImpl();
887 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
888 return MDTuple::get(Context, MDs);
890 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
891 return MDTuple::getIfExists(Context, MDs);
893 MDNode *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
894 return MDTuple::getDistinct(Context, MDs);
897 /// \brief Debug location.
899 /// A debug location in source code, used for debug info and otherwise.
900 class MDLocation : public UniquableMDNode {
901 friend class LLVMContextImpl;
902 friend class UniquableMDNode;
904 MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
905 unsigned Column, ArrayRef<Metadata *> MDs);
906 ~MDLocation() { dropAllReferences(); }
908 static MDLocation *constructHelper(LLVMContext &Context, StorageType Storage,
909 unsigned Line, unsigned Column,
910 Metadata *Scope, Metadata *InlinedAt);
912 static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
913 unsigned Column, Metadata *Scope,
914 Metadata *InlinedAt, bool ShouldCreate);
916 // Disallow replacing operands.
917 void replaceOperandWith(unsigned I, Metadata *New) LLVM_DELETED_FUNCTION;
920 static MDLocation *get(LLVMContext &Context, unsigned Line, unsigned Column,
921 Metadata *Scope, Metadata *InlinedAt = nullptr) {
922 return getImpl(Context, Line, Column, Scope, InlinedAt,
923 /* ShouldCreate */ true);
925 static MDLocation *getIfExists(LLVMContext &Context, unsigned Line,
926 unsigned Column, Metadata *Scope,
927 Metadata *InlinedAt = nullptr) {
928 return getImpl(Context, Line, Column, Scope, InlinedAt,
929 /* ShouldCreate */ false);
931 static MDLocation *getDistinct(LLVMContext &Context, unsigned Line,
932 unsigned Column, Metadata *Scope,
933 Metadata *InlinedAt = nullptr);
935 unsigned getLine() const { return MDNodeSubclassData; }
936 unsigned getColumn() const { return SubclassData16; }
937 Metadata *getScope() const { return getOperand(0); }
938 Metadata *getInlinedAt() const {
939 if (getNumOperands() == 2)
940 return getOperand(1);
944 static bool classof(const Metadata *MD) {
945 return MD->getMetadataID() == MDLocationKind;
949 MDLocation *uniquifyImpl();
950 void eraseFromStoreImpl();
953 /// \brief Forward declaration of metadata.
955 /// Forward declaration of metadata, in the form of a basic tuple. Unlike \a
956 /// MDTuple, this class has full support for RAUW, is not owned, is not
957 /// uniqued, and is suitable for forward references.
958 class MDNodeFwdDecl : public MDNode {
959 friend class Metadata;
961 MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
962 : MDNode(C, MDNodeFwdDeclKind, Temporary, Vals) {}
965 ~MDNodeFwdDecl() { dropAllReferences(); }
967 // MSVC doesn't see the alternative: "using MDNode::operator delete".
968 void operator delete(void *Mem) { MDNode::operator delete(Mem); }
970 static MDNodeFwdDecl *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
971 return new (MDs.size()) MDNodeFwdDecl(Context, MDs);
974 static bool classof(const Metadata *MD) {
975 return MD->getMetadataID() == MDNodeFwdDeclKind;
978 void replaceAllUsesWith(Metadata *MD) {
979 assert(Context.hasReplaceableUses() && "Expected RAUW support");
980 Context.getReplaceableUses()->replaceAllUsesWith(MD);
984 //===----------------------------------------------------------------------===//
985 /// \brief A tuple of MDNodes.
987 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
988 /// to modules, have names, and contain lists of MDNodes.
990 /// TODO: Inherit from Metadata.
991 class NamedMDNode : public ilist_node<NamedMDNode> {
992 friend class SymbolTableListTraits<NamedMDNode, Module>;
993 friend struct ilist_traits<NamedMDNode>;
994 friend class LLVMContextImpl;
996 NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
1000 void *Operands; // SmallVector<TrackingMDRef, 4>
1002 void setParent(Module *M) { Parent = M; }
1004 explicit NamedMDNode(const Twine &N);
1006 template<class T1, class T2>
1007 class op_iterator_impl :
1008 public std::iterator<std::bidirectional_iterator_tag, T2> {
1009 const NamedMDNode *Node;
1011 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1013 friend class NamedMDNode;
1016 op_iterator_impl() : Node(nullptr), Idx(0) { }
1018 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1019 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1020 op_iterator_impl &operator++() {
1024 op_iterator_impl operator++(int) {
1025 op_iterator_impl tmp(*this);
1029 op_iterator_impl &operator--() {
1033 op_iterator_impl operator--(int) {
1034 op_iterator_impl tmp(*this);
1039 T1 operator*() const { return Node->getOperand(Idx); }
1043 /// \brief Drop all references and remove the node from parent module.
1044 void eraseFromParent();
1046 /// \brief Remove all uses and clear node vector.
1047 void dropAllReferences();
1051 /// \brief Get the module that holds this named metadata collection.
1052 inline Module *getParent() { return Parent; }
1053 inline const Module *getParent() const { return Parent; }
1055 MDNode *getOperand(unsigned i) const;
1056 unsigned getNumOperands() const;
1057 void addOperand(MDNode *M);
1058 void setOperand(unsigned I, MDNode *New);
1059 StringRef getName() const;
1060 void print(raw_ostream &ROS) const;
1063 // ---------------------------------------------------------------------------
1064 // Operand Iterator interface...
1066 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1067 op_iterator op_begin() { return op_iterator(this, 0); }
1068 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
1070 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1071 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1072 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1074 inline iterator_range<op_iterator> operands() {
1075 return iterator_range<op_iterator>(op_begin(), op_end());
1077 inline iterator_range<const_op_iterator> operands() const {
1078 return iterator_range<const_op_iterator>(op_begin(), op_end());
1082 } // end llvm namespace