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 Storage flag for non-uniqued, otherwise unowned, metadata.
51 bool IsDistinctInContext : 1;
52 // TODO: expose remaining bits to subclasses.
54 unsigned short SubclassData16;
55 unsigned SubclassData32;
62 ConstantAsMetadataKind,
69 : SubclassID(ID), IsDistinctInContext(false), SubclassData16(0),
73 /// \brief Store this in a big non-uniqued untyped bucket.
74 bool isStoredDistinctInContext() const { return IsDistinctInContext; }
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;
149 SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
152 ReplaceableMetadataImpl() : NextIndex(0) {}
153 ~ReplaceableMetadataImpl() {
154 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
157 /// \brief Replace all uses of this with MD.
159 /// Replace all uses of this with \c MD, which is allowed to be null.
160 void replaceAllUsesWith(Metadata *MD);
162 /// \brief Resolve all uses of this.
164 /// Resolve all uses of this, turning off RAUW permanently. If \c
165 /// ResolveUsers, call \a UniquableMDNode::resolve() on any users whose last
166 /// operand is resolved.
167 void resolveAllUses(bool ResolveUsers = true);
170 void addRef(void *Ref, OwnerTy Owner);
171 void dropRef(void *Ref);
172 void moveRef(void *Ref, void *New, const Metadata &MD);
174 static ReplaceableMetadataImpl *get(Metadata &MD);
177 /// \brief Value wrapper in the Metadata hierarchy.
179 /// This is a custom value handle that allows other metadata to refer to
180 /// classes in the Value hierarchy.
182 /// Because of full uniquing support, each value is only wrapped by a single \a
183 /// ValueAsMetadata object, so the lookup maps are far more efficient than
184 /// those using ValueHandleBase.
185 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
186 friend class ReplaceableMetadataImpl;
187 friend class LLVMContextImpl;
191 /// \brief Drop users without RAUW (during teardown).
193 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
197 ValueAsMetadata(unsigned ID, Value *V)
198 : Metadata(ID), V(V) {
199 assert(V && "Expected valid value");
201 ~ValueAsMetadata() {}
204 static ValueAsMetadata *get(Value *V);
205 static ConstantAsMetadata *getConstant(Value *C) {
206 return cast<ConstantAsMetadata>(get(C));
208 static LocalAsMetadata *getLocal(Value *Local) {
209 return cast<LocalAsMetadata>(get(Local));
212 static ValueAsMetadata *getIfExists(Value *V);
213 static ConstantAsMetadata *getConstantIfExists(Value *C) {
214 return cast_or_null<ConstantAsMetadata>(getIfExists(C));
216 static LocalAsMetadata *getLocalIfExists(Value *Local) {
217 return cast_or_null<LocalAsMetadata>(getIfExists(Local));
220 Value *getValue() const { return V; }
221 Type *getType() const { return V->getType(); }
222 LLVMContext &getContext() const { return V->getContext(); }
224 static void handleDeletion(Value *V);
225 static void handleRAUW(Value *From, Value *To);
228 /// \brief Handle collisions after \a Value::replaceAllUsesWith().
230 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
231 /// \a Value gets RAUW'ed and the target already exists, this is used to
232 /// merge the two metadata nodes.
233 void replaceAllUsesWith(Metadata *MD) {
234 ReplaceableMetadataImpl::replaceAllUsesWith(MD);
238 static bool classof(const Metadata *MD) {
239 return MD->getMetadataID() == LocalAsMetadataKind ||
240 MD->getMetadataID() == ConstantAsMetadataKind;
244 class ConstantAsMetadata : public ValueAsMetadata {
245 friend class ValueAsMetadata;
247 ConstantAsMetadata(Constant *C)
248 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
251 static ConstantAsMetadata *get(Constant *C) {
252 return ValueAsMetadata::getConstant(C);
254 static ConstantAsMetadata *getIfExists(Constant *C) {
255 return ValueAsMetadata::getConstantIfExists(C);
258 Constant *getValue() const {
259 return cast<Constant>(ValueAsMetadata::getValue());
262 static bool classof(const Metadata *MD) {
263 return MD->getMetadataID() == ConstantAsMetadataKind;
267 class LocalAsMetadata : public ValueAsMetadata {
268 friend class ValueAsMetadata;
270 LocalAsMetadata(Value *Local)
271 : ValueAsMetadata(LocalAsMetadataKind, Local) {
272 assert(!isa<Constant>(Local) && "Expected local value");
276 static LocalAsMetadata *get(Value *Local) {
277 return ValueAsMetadata::getLocal(Local);
279 static LocalAsMetadata *getIfExists(Value *Local) {
280 return ValueAsMetadata::getLocalIfExists(Local);
283 static bool classof(const Metadata *MD) {
284 return MD->getMetadataID() == LocalAsMetadataKind;
288 /// \brief Transitional API for extracting constants from Metadata.
290 /// This namespace contains transitional functions for metadata that points to
293 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
294 /// operands could refer to any \a Value. There's was a lot of code like this:
298 /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
301 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
302 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
303 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
304 /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
305 /// requires subtle control flow changes.
307 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
308 /// so that metadata can refer to numbers without traversing a bridge to the \a
309 /// Value hierarchy. In this final state, the code above would look like this:
313 /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
316 /// The API in this namespace supports the transition. \a MDInt doesn't exist
317 /// yet, and even once it does, changing each metadata schema to use it is its
318 /// own mini-project. In the meantime this API prevents us from introducing
319 /// complex and bug-prone control flow that will disappear in the end. In
320 /// particular, the above code looks like this:
324 /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
327 /// The full set of provided functions includes:
329 /// mdconst::hasa <=> isa
330 /// mdconst::extract <=> cast
331 /// mdconst::extract_or_null <=> cast_or_null
332 /// mdconst::dyn_extract <=> dyn_cast
333 /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
335 /// The target of the cast must be a subclass of \a Constant.
339 template <class T> T &make();
340 template <class T, class Result> struct HasDereference {
343 template <size_t N> struct SFINAE {};
345 template <class U, class V>
346 static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
347 template <class U, class V> static No &hasDereference(...);
349 static const bool value =
350 sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
352 template <class V, class M> struct IsValidPointer {
353 static const bool value = std::is_base_of<Constant, V>::value &&
354 HasDereference<M, const Metadata &>::value;
356 template <class V, class M> struct IsValidReference {
357 static const bool value = std::is_base_of<Constant, V>::value &&
358 std::is_convertible<M, const Metadata &>::value;
360 } // end namespace detail
362 /// \brief Check whether Metadata has a Value.
364 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
366 template <class X, class Y>
367 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
369 assert(MD && "Null pointer sent into hasa");
370 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
371 return isa<X>(V->getValue());
374 template <class X, class Y>
376 typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
381 /// \brief Extract a Value from Metadata.
383 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
384 template <class X, class Y>
385 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
387 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
389 template <class X, class Y>
391 typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
396 /// \brief Extract a Value from Metadata, allowing null.
398 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
399 /// from \c MD, allowing \c MD to be null.
400 template <class X, class Y>
401 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
402 extract_or_null(Y &&MD) {
403 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
404 return cast<X>(V->getValue());
408 /// \brief Extract a Value from Metadata, if any.
410 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
411 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
412 /// Value it does contain is of the wrong subclass.
413 template <class X, class Y>
414 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
415 dyn_extract(Y &&MD) {
416 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
417 return dyn_cast<X>(V->getValue());
421 /// \brief Extract a Value from Metadata, if any, allowing null.
423 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
424 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
425 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
426 template <class X, class Y>
427 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
428 dyn_extract_or_null(Y &&MD) {
429 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
430 return dyn_cast<X>(V->getValue());
434 } // end namespace mdconst
436 //===----------------------------------------------------------------------===//
437 /// \brief A single uniqued string.
439 /// These are used to efficiently contain a byte sequence for metadata.
440 /// MDString is always unnamed.
441 class MDString : public Metadata {
442 friend class StringMapEntry<MDString>;
444 MDString(const MDString &) LLVM_DELETED_FUNCTION;
445 MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
446 MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
448 StringMapEntry<MDString> *Entry;
449 MDString() : Metadata(MDStringKind), Entry(nullptr) {}
450 MDString(MDString &&) : Metadata(MDStringKind) {}
453 static MDString *get(LLVMContext &Context, StringRef Str);
454 static MDString *get(LLVMContext &Context, const char *Str) {
455 return get(Context, Str ? StringRef(Str) : StringRef());
458 StringRef getString() const;
460 unsigned getLength() const { return (unsigned)getString().size(); }
462 typedef StringRef::iterator iterator;
464 /// \brief Pointer to the first byte of the string.
465 iterator begin() const { return getString().begin(); }
467 /// \brief Pointer to one byte past the end of the string.
468 iterator end() const { return getString().end(); }
470 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
471 const unsigned char *bytes_end() const { return getString().bytes_end(); }
473 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
474 static bool classof(const Metadata *MD) {
475 return MD->getMetadataID() == MDStringKind;
479 /// \brief A collection of metadata nodes that might be associated with a
480 /// memory access used by the alias-analysis infrastructure.
482 explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
484 : TBAA(T), Scope(S), NoAlias(N) {}
486 bool operator==(const AAMDNodes &A) const {
487 return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
490 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
492 LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
494 /// \brief The tag for type-based alias analysis.
497 /// \brief The tag for alias scope specification (used with noalias).
500 /// \brief The tag specifying the noalias scope.
504 // Specialize DenseMapInfo for AAMDNodes.
506 struct DenseMapInfo<AAMDNodes> {
507 static inline AAMDNodes getEmptyKey() {
508 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
510 static inline AAMDNodes getTombstoneKey() {
511 return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
513 static unsigned getHashValue(const AAMDNodes &Val) {
514 return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
515 DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
516 DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
518 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
523 /// \brief Tracking metadata reference owned by Metadata.
525 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
526 /// of \a Metadata, which has the option of registering itself for callbacks to
527 /// re-unique itself.
529 /// In particular, this is used by \a MDNode.
531 MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
532 MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
533 MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
534 MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
539 MDOperand() : MD(nullptr) {}
540 ~MDOperand() { untrack(); }
542 Metadata *get() const { return MD; }
543 operator Metadata *() const { return get(); }
544 Metadata *operator->() const { return get(); }
545 Metadata &operator*() const { return *get(); }
551 void reset(Metadata *MD, Metadata *Owner) {
558 void track(Metadata *Owner) {
561 MetadataTracking::track(this, *MD, *Owner);
563 MetadataTracking::track(MD);
567 assert(static_cast<void *>(this) == &MD && "Expected same address");
569 MetadataTracking::untrack(MD);
573 template <> struct simplify_type<MDOperand> {
574 typedef Metadata *SimpleType;
575 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
578 template <> struct simplify_type<const MDOperand> {
579 typedef Metadata *SimpleType;
580 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
583 //===----------------------------------------------------------------------===//
584 /// \brief Tuple of metadata.
585 class MDNode : public Metadata {
586 MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
587 void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
588 void *operator new(size_t) LLVM_DELETED_FUNCTION;
590 LLVMContext &Context;
591 unsigned NumOperands;
594 unsigned MDNodeSubclassData;
596 void *operator new(size_t Size, unsigned NumOps);
597 void operator delete(void *Mem);
599 /// \brief Required by std, but never called.
600 void operator delete(void *, unsigned) {
601 llvm_unreachable("Constructor throws?");
604 /// \brief Required by std, but never called.
605 void operator delete(void *, unsigned, bool) {
606 llvm_unreachable("Constructor throws?");
609 MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs);
612 void dropAllReferences();
614 MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
615 MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
618 static inline MDNode *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
619 static inline MDNode *getIfExists(LLVMContext &Context,
620 ArrayRef<Metadata *> MDs);
621 static inline MDNode *getDistinct(LLVMContext &Context,
622 ArrayRef<Metadata *> MDs);
624 /// \brief Return a temporary MDNode
626 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
627 /// not uniqued, may be RAUW'd, and must be manually deleted with
629 static MDNodeFwdDecl *getTemporary(LLVMContext &Context,
630 ArrayRef<Metadata *> MDs);
632 /// \brief Deallocate a node created by getTemporary.
634 /// The node must not have any users.
635 static void deleteTemporary(MDNode *N);
637 LLVMContext &getContext() const { return Context; }
639 /// \brief Replace a specific operand.
640 void replaceOperandWith(unsigned I, Metadata *New);
642 /// \brief Check if node is fully resolved.
643 bool isResolved() const;
645 /// \brief Check if node is distinct.
647 /// Distinct nodes are not uniqued, and will not be returned by \a
649 bool isDistinct() const {
650 return isStoredDistinctInContext() || isa<MDNodeFwdDecl>(this);
654 /// \brief Set an operand.
656 /// Sets the operand directly, without worrying about uniquing.
657 void setOperand(unsigned I, Metadata *New);
660 typedef const MDOperand *op_iterator;
661 typedef iterator_range<op_iterator> op_range;
663 op_iterator op_begin() const {
664 return const_cast<MDNode *>(this)->mutable_begin();
666 op_iterator op_end() const {
667 return const_cast<MDNode *>(this)->mutable_end();
669 op_range operands() const { return op_range(op_begin(), op_end()); }
671 const MDOperand &getOperand(unsigned I) const {
672 assert(I < NumOperands && "Out of range");
673 return op_begin()[I];
676 /// \brief Return number of MDNode operands.
677 unsigned getNumOperands() const { return NumOperands; }
679 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
680 static bool classof(const Metadata *MD) {
681 return MD->getMetadataID() == MDTupleKind ||
682 MD->getMetadataID() == MDLocationKind ||
683 MD->getMetadataID() == MDNodeFwdDeclKind;
686 /// \brief Check whether MDNode is a vtable access.
687 bool isTBAAVtableAccess() const;
689 /// \brief Methods for metadata merging.
690 static MDNode *concatenate(MDNode *A, MDNode *B);
691 static MDNode *intersect(MDNode *A, MDNode *B);
692 static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
693 static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
694 static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
695 static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
696 static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
699 /// \brief Uniquable metadata node.
701 /// A uniquable metadata node. This contains the basic functionality
702 /// for implementing sub-types of \a MDNode that can be uniqued like
705 /// There is limited support for RAUW at construction time. At
706 /// construction time, if any operands are an instance of \a
707 /// MDNodeFwdDecl (or another unresolved \a UniquableMDNode, which
708 /// indicates an \a MDNodeFwdDecl in its path), the node itself will be
709 /// unresolved. As soon as all operands become resolved, it will drop
710 /// RAUW support permanently.
712 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
713 /// to be called on some member of the cycle when each \a MDNodeFwdDecl
714 /// has been removed.
715 class UniquableMDNode : public MDNode {
716 friend class ReplaceableMetadataImpl;
718 friend class LLVMContextImpl;
720 /// \brief Support RAUW as long as one of its arguments is replaceable.
722 /// FIXME: Save memory by storing this in a pointer union with the
723 /// LLVMContext, and adding an LLVMContext reference to RMI.
724 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses;
727 /// \brief Create a new node.
729 /// If \c AllowRAUW, then if any operands are unresolved support RAUW. RAUW
730 /// will be dropped once all operands have been resolved (or if \a
731 /// resolveCycles() is called).
732 UniquableMDNode(LLVMContext &C, unsigned ID, ArrayRef<Metadata *> Vals,
734 ~UniquableMDNode() {}
736 void storeDistinctInContext();
739 static bool classof(const Metadata *MD) {
740 return MD->getMetadataID() == MDTupleKind ||
741 MD->getMetadataID() == MDLocationKind;
744 /// \brief Check whether any operands are forward declarations.
746 /// Returns \c true as long as any operands (or their operands, etc.) are \a
749 /// As forward declarations are resolved, their containers should get
750 /// resolved automatically. However, if this (or one of its operands) is
751 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
752 bool isResolved() const { return !ReplaceableUses; }
754 /// \brief Resolve cycles.
756 /// Once all forward declarations have been resolved, force cycles to be
759 /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl.
760 void resolveCycles();
763 void handleChangedOperand(void *Ref, Metadata *New);
766 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
767 void decrementUnresolvedOperandCount();
769 void deleteAsSubclass();
770 UniquableMDNode *uniquify();
771 void eraseFromStore();
774 /// \brief Tuple of metadata.
776 /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
777 /// default based on their operands.
778 class MDTuple : public UniquableMDNode {
779 friend class LLVMContextImpl;
780 friend class UniquableMDNode;
782 MDTuple(LLVMContext &C, ArrayRef<Metadata *> Vals, bool AllowRAUW)
783 : UniquableMDNode(C, MDTupleKind, Vals, AllowRAUW) {}
784 ~MDTuple() { dropAllReferences(); }
786 void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
787 void recalculateHash();
789 static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
793 /// \brief Get the hash, if any.
794 unsigned getHash() const { return MDNodeSubclassData; }
796 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
797 return getImpl(Context, MDs, /* ShouldCreate */ true);
799 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
800 return getImpl(Context, MDs, /* ShouldCreate */ false);
803 /// \brief Return a distinct node.
805 /// Return a distinct node -- i.e., a node that is not uniqued.
806 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs);
808 static bool classof(const Metadata *MD) {
809 return MD->getMetadataID() == MDTupleKind;
813 MDTuple *uniquifyImpl();
814 void eraseFromStoreImpl();
817 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
818 return MDTuple::get(Context, MDs);
820 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
821 return MDTuple::getIfExists(Context, MDs);
823 MDNode *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
824 return MDTuple::getDistinct(Context, MDs);
827 /// \brief Debug location.
829 /// A debug location in source code, used for debug info and otherwise.
830 class MDLocation : public UniquableMDNode {
831 friend class LLVMContextImpl;
832 friend class UniquableMDNode;
834 MDLocation(LLVMContext &C, unsigned Line, unsigned Column,
835 ArrayRef<Metadata *> MDs, bool AllowRAUW);
836 ~MDLocation() { dropAllReferences(); }
838 static MDLocation *constructHelper(LLVMContext &Context, unsigned Line,
839 unsigned Column, Metadata *Scope,
840 Metadata *InlinedAt, bool AllowRAUW);
842 static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
843 unsigned Column, Metadata *Scope,
844 Metadata *InlinedAt, bool ShouldCreate);
846 // Disallow replacing operands.
847 void replaceOperandWith(unsigned I, Metadata *New) LLVM_DELETED_FUNCTION;
850 static MDLocation *get(LLVMContext &Context, unsigned Line, unsigned Column,
851 Metadata *Scope, Metadata *InlinedAt = nullptr) {
852 return getImpl(Context, Line, Column, Scope, InlinedAt,
853 /* ShouldCreate */ true);
855 static MDLocation *getIfExists(LLVMContext &Context, unsigned Line,
856 unsigned Column, Metadata *Scope,
857 Metadata *InlinedAt = nullptr) {
858 return getImpl(Context, Line, Column, Scope, InlinedAt,
859 /* ShouldCreate */ false);
861 static MDLocation *getDistinct(LLVMContext &Context, unsigned Line,
862 unsigned Column, Metadata *Scope,
863 Metadata *InlinedAt = nullptr);
865 unsigned getLine() const { return MDNodeSubclassData; }
866 unsigned getColumn() const { return SubclassData16; }
867 Metadata *getScope() const { return getOperand(0); }
868 Metadata *getInlinedAt() const {
869 if (getNumOperands() == 2)
870 return getOperand(1);
874 static bool classof(const Metadata *MD) {
875 return MD->getMetadataID() == MDLocationKind;
879 MDLocation *uniquifyImpl();
880 void eraseFromStoreImpl();
883 /// \brief Forward declaration of metadata.
885 /// Forward declaration of metadata, in the form of a basic tuple. Unlike \a
886 /// MDTuple, this class has full support for RAUW, is not owned, is not
887 /// uniqued, and is suitable for forward references.
888 class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
889 friend class Metadata;
890 friend class ReplaceableMetadataImpl;
892 MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
893 : MDNode(C, MDNodeFwdDeclKind, Vals) {}
896 ~MDNodeFwdDecl() { dropAllReferences(); }
898 // MSVC doesn't see the alternative: "using MDNode::operator delete".
899 void operator delete(void *Mem) { MDNode::operator delete(Mem); }
901 static MDNodeFwdDecl *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
902 return new (MDs.size()) MDNodeFwdDecl(Context, MDs);
905 static bool classof(const Metadata *MD) {
906 return MD->getMetadataID() == MDNodeFwdDeclKind;
909 using ReplaceableMetadataImpl::replaceAllUsesWith;
912 //===----------------------------------------------------------------------===//
913 /// \brief A tuple of MDNodes.
915 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
916 /// to modules, have names, and contain lists of MDNodes.
918 /// TODO: Inherit from Metadata.
919 class NamedMDNode : public ilist_node<NamedMDNode> {
920 friend class SymbolTableListTraits<NamedMDNode, Module>;
921 friend struct ilist_traits<NamedMDNode>;
922 friend class LLVMContextImpl;
924 NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
928 void *Operands; // SmallVector<TrackingMDRef, 4>
930 void setParent(Module *M) { Parent = M; }
932 explicit NamedMDNode(const Twine &N);
934 template<class T1, class T2>
935 class op_iterator_impl :
936 public std::iterator<std::bidirectional_iterator_tag, T2> {
937 const NamedMDNode *Node;
939 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
941 friend class NamedMDNode;
944 op_iterator_impl() : Node(nullptr), Idx(0) { }
946 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
947 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
948 op_iterator_impl &operator++() {
952 op_iterator_impl operator++(int) {
953 op_iterator_impl tmp(*this);
957 op_iterator_impl &operator--() {
961 op_iterator_impl operator--(int) {
962 op_iterator_impl tmp(*this);
967 T1 operator*() const { return Node->getOperand(Idx); }
971 /// \brief Drop all references and remove the node from parent module.
972 void eraseFromParent();
974 /// \brief Remove all uses and clear node vector.
975 void dropAllReferences();
979 /// \brief Get the module that holds this named metadata collection.
980 inline Module *getParent() { return Parent; }
981 inline const Module *getParent() const { return Parent; }
983 MDNode *getOperand(unsigned i) const;
984 unsigned getNumOperands() const;
985 void addOperand(MDNode *M);
986 void setOperand(unsigned I, MDNode *New);
987 StringRef getName() const;
988 void print(raw_ostream &ROS) const;
991 // ---------------------------------------------------------------------------
992 // Operand Iterator interface...
994 typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
995 op_iterator op_begin() { return op_iterator(this, 0); }
996 op_iterator op_end() { return op_iterator(this, getNumOperands()); }
998 typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
999 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1000 const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
1002 inline iterator_range<op_iterator> operands() {
1003 return iterator_range<op_iterator>(op_begin(), op_end());
1005 inline iterator_range<const_op_iterator> operands() const {
1006 return iterator_range<const_op_iterator>(op_begin(), op_end());
1010 } // end llvm namespace