LLVM 23.0.0git
Metadata.h
Go to the documentation of this file.
1//===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// @file
10/// This file contains the declarations for metadata subclasses.
11/// They represent the different flavors of metadata that live in LLVM.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_METADATA_H
16#define LLVM_IR_METADATA_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/ilist_node.h"
26#include "llvm/IR/Constant.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Value.h"
33#include <cassert>
34#include <cstddef>
35#include <cstdint>
36#include <iterator>
37#include <memory>
38#include <string>
39#include <type_traits>
40#include <utility>
41
42namespace llvm {
43
44enum class CaptureComponents : uint8_t;
45class Module;
47class raw_ostream;
49template <typename T> class StringMapEntry;
50template <typename ValueTy> class StringMapEntryStorage;
51class Type;
52
54 DEBUG_METADATA_VERSION = 3 // Current debug info version number.
55};
56
57/// Magic number in the value profile metadata showing a target has been
58/// promoted for the instruction and shouldn't be promoted again.
60
61/// Root of the metadata hierarchy.
62///
63/// This is a root class for typeless data in the IR.
64class Metadata {
66
67 /// RTTI.
68 const unsigned char SubclassID;
69
70protected:
71 /// Active type of storage.
73
74 /// Storage flag for non-uniqued, otherwise unowned, metadata.
75 unsigned char Storage : 7;
76
77 unsigned char SubclassData1 : 1;
78 unsigned short SubclassData16 = 0;
79 unsigned SubclassData32 = 0;
80
81public:
83#define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
84#include "llvm/IR/Metadata.def"
85 };
86
87protected:
89 : SubclassID(ID), Storage(Storage), SubclassData1(false) {
90 static_assert(sizeof(*this) == 8, "Metadata fields poorly packed");
91 }
92
93 ~Metadata() = default;
94
95 /// Default handling of a changed operand, which asserts.
96 ///
97 /// If subclasses pass themselves in as owners to a tracking node reference,
98 /// they must provide an implementation of this method.
100 llvm_unreachable("Unimplemented in Metadata subclass");
101 }
102
103public:
104 unsigned getMetadataID() const { return SubclassID; }
105
106 /// User-friendly dump.
107 ///
108 /// If \c M is provided, metadata nodes will be numbered canonically;
109 /// otherwise, pointer addresses are substituted.
110 ///
111 /// Note: this uses an explicit overload instead of default arguments so that
112 /// the nullptr version is easy to call from a debugger.
113 ///
114 /// @{
115 LLVM_ABI void dump() const;
116 LLVM_ABI void dump(const Module *M) const;
117 /// @}
118
119 /// Print.
120 ///
121 /// Prints definition of \c this.
122 ///
123 /// If \c M is provided, metadata nodes will be numbered canonically;
124 /// otherwise, pointer addresses are substituted.
125 /// @{
126 LLVM_ABI void print(raw_ostream &OS, const Module *M = nullptr,
127 bool IsForDebug = false) const;
129 const Module *M = nullptr, bool IsForDebug = false) const;
130 /// @}
131
132 /// Print as operand.
133 ///
134 /// Prints reference of \c this.
135 ///
136 /// If \c M is provided, metadata nodes will be numbered canonically;
137 /// otherwise, pointer addresses are substituted.
138 /// @{
140 const Module *M = nullptr) const;
142 const Module *M = nullptr) const;
143 /// @}
144
145 /// Metadata IDs that may generate poison.
146 constexpr static const unsigned PoisonGeneratingIDs[] = {
147 LLVMContext::MD_range, LLVMContext::MD_nonnull, LLVMContext::MD_align,
148 LLVMContext::MD_nofpclass};
149};
150
151// Create wrappers for C Binding types (see CBindingWrapping.h).
153
154// Specialized opaque metadata conversions.
156 return reinterpret_cast<Metadata**>(MDs);
157}
158
159#define HANDLE_METADATA(CLASS) class CLASS;
160#include "llvm/IR/Metadata.def"
161
162// Provide specializations of isa so that we don't need definitions of
163// subclasses to see if the metadata is a subclass.
164#define HANDLE_METADATA_LEAF(CLASS) \
165 template <> struct isa_impl<CLASS, Metadata> { \
166 static inline bool doit(const Metadata &MD) { \
167 return MD.getMetadataID() == Metadata::CLASS##Kind; \
168 } \
169 };
170#include "llvm/IR/Metadata.def"
171
173 MD.print(OS);
174 return OS;
175}
176
177/// Metadata wrapper in the Value hierarchy.
178///
179/// A member of the \a Value hierarchy to represent a reference to metadata.
180/// This allows, e.g., intrinsics to have metadata as operands.
181///
182/// Notably, this is the only thing in either hierarchy that is allowed to
183/// reference \a LocalAsMetadata.
184class MetadataAsValue : public Value {
186 friend class LLVMContextImpl;
187
188 Metadata *MD;
189
190 MetadataAsValue(Type *Ty, Metadata *MD);
191
192 /// Drop use of metadata (during teardown).
193 void dropUse() { MD = nullptr; }
194
195public:
197
198 LLVM_ABI static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
200 Metadata *MD);
201
202 Metadata *getMetadata() const { return MD; }
203
204 static bool classof(const Value *V) {
205 return V->getValueID() == MetadataAsValueVal;
206 }
207
208private:
209 void handleChangedMetadata(Metadata *MD);
210 void track();
211 void untrack();
212};
213
214/// Base class for tracking ValueAsMetadata/DIArgLists with user lookups and
215/// Owner callbacks outside of ValueAsMetadata.
216///
217/// Currently only inherited by DbgVariableRecord; if other classes need to use
218/// it, then a SubclassID will need to be added (either as a new field or by
219/// making DebugValue into a PointerIntUnion) to discriminate between the
220/// subclasses in lookup and callback handling.
222protected:
223 // Capacity to store 3 debug values.
224 // TODO: Not all DebugValueUser instances need all 3 elements, if we
225 // restructure the DbgVariableRecord class then we can template parameterize
226 // this array size.
227 std::array<Metadata *, 3> DebugValues;
228
230
231public:
233 LLVM_ABI const DbgVariableRecord *getUser() const;
234 /// To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where `Old`
235 /// is a pointer to one of the pointers in `DebugValues` (so should be type
236 /// Metadata**), and `NewDebugValue` is the new Metadata* that is replacing
237 /// *Old.
238 /// For manually replacing elements of DebugValues,
239 /// `resetDebugValue(Idx, NewDebugValue)` should be used instead.
240 LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue);
241 DebugValueUser() = default;
242 explicit DebugValueUser(std::array<Metadata *, 3> DebugValues)
244 trackDebugValues();
245 }
247 DebugValues = X.DebugValues;
248 retrackDebugValues(X);
249 }
251 DebugValues = X.DebugValues;
252 trackDebugValues();
253 }
254
256 if (&X == this)
257 return *this;
258
259 untrackDebugValues();
260 DebugValues = X.DebugValues;
261 retrackDebugValues(X);
262 return *this;
263 }
264
266 if (&X == this)
267 return *this;
268
269 untrackDebugValues();
270 DebugValues = X.DebugValues;
271 trackDebugValues();
272 return *this;
273 }
274
275 ~DebugValueUser() { untrackDebugValues(); }
276
278 untrackDebugValues();
279 DebugValues.fill(nullptr);
280 }
281
282 void resetDebugValue(size_t Idx, Metadata *DebugValue) {
283 assert(Idx < 3 && "Invalid debug value index.");
284 untrackDebugValue(Idx);
285 DebugValues[Idx] = DebugValue;
286 trackDebugValue(Idx);
287 }
288
289 bool operator==(const DebugValueUser &X) const {
290 return DebugValues == X.DebugValues;
291 }
292 bool operator!=(const DebugValueUser &X) const {
293 return DebugValues != X.DebugValues;
294 }
295
296private:
297 LLVM_ABI void trackDebugValue(size_t Idx);
298 LLVM_ABI void trackDebugValues();
299
300 LLVM_ABI void untrackDebugValue(size_t Idx);
301 LLVM_ABI void untrackDebugValues();
302
303 LLVM_ABI void retrackDebugValues(DebugValueUser &X);
304};
305
306/// API for tracking metadata references through RAUW and deletion.
307///
308/// Shared API for updating \a Metadata pointers in subclasses that support
309/// RAUW.
310///
311/// This API is not meant to be used directly. See \a TrackingMDRef for a
312/// user-friendly tracking reference.
314public:
315 /// Track the reference to metadata.
316 ///
317 /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
318 /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
319 /// deleted, \c MD will be set to \c nullptr.
320 ///
321 /// If tracking isn't supported, \c *MD will not change.
322 ///
323 /// \return true iff tracking is supported by \c MD.
324 static bool track(Metadata *&MD) {
325 return track(&MD, *MD, static_cast<Metadata *>(nullptr));
326 }
327
328 /// Track the reference to metadata for \a Metadata.
329 ///
330 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
331 /// tell it that its operand changed. This could trigger \c Owner being
332 /// re-uniqued.
333 static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
334 return track(Ref, MD, &Owner);
335 }
336
337 /// Track the reference to metadata for \a MetadataAsValue.
338 ///
339 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
340 /// tell it that its operand changed. This could trigger \c Owner being
341 /// re-uniqued.
342 static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
343 return track(Ref, MD, &Owner);
344 }
345
346 /// Track the reference to metadata for \a DebugValueUser.
347 ///
348 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
349 /// tell it that its operand changed. This could trigger \c Owner being
350 /// re-uniqued.
351 static bool track(void *Ref, Metadata &MD, DebugValueUser &Owner) {
352 return track(Ref, MD, &Owner);
353 }
354
355 /// Stop tracking a reference to metadata.
356 ///
357 /// Stops \c *MD from tracking \c MD.
358 static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
359 LLVM_ABI static void untrack(void *Ref, Metadata &MD);
360
361 /// Move tracking from one reference to another.
362 ///
363 /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
364 /// except that ownership callbacks are maintained.
365 ///
366 /// Note: it is an error if \c *MD does not equal \c New.
367 ///
368 /// \return true iff tracking is supported by \c MD.
369 static bool retrack(Metadata *&MD, Metadata *&New) {
370 return retrack(&MD, *MD, &New);
371 }
372 LLVM_ABI static bool retrack(void *Ref, Metadata &MD, void *New);
373
374 /// Check whether metadata is replaceable.
375 LLVM_ABI static bool isReplaceable(const Metadata &MD);
376
378
379private:
380 /// Track a reference to metadata for an owner.
381 ///
382 /// Generalized version of tracking.
383 LLVM_ABI static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
384};
385
386/// Shared implementation of use-lists for replaceable metadata.
387///
388/// Most metadata cannot be RAUW'ed. This is a shared implementation of
389/// use-lists and associated API for the three that support it (
390/// \a ValueAsMetadata, \a TempMDNode, and \a DIArgList).
392 friend class MetadataTracking;
393
394public:
396
397private:
398 LLVMContext &Context;
399 uint64_t NextIndex = 0;
401
402public:
403 ReplaceableMetadataImpl(LLVMContext &Context) : Context(Context) {}
404
406 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
407 }
408
409 LLVMContext &getContext() const { return Context; }
410
411 /// Replace all uses of this with MD.
412 ///
413 /// Replace all uses of this with \c MD, which is allowed to be null.
415 /// Replace all uses of the constant with Undef in debug info metadata
416 LLVM_ABI static void SalvageDebugInfo(const Constant &C);
417 /// Returns the list of all DIArgList users of this.
419 /// Returns the list of all DbgVariableRecord users of this.
421
422 /// Resolve all uses of this.
423 ///
424 /// Resolve all uses of this, turning off RAUW permanently. If \c
425 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
426 /// is resolved.
427 LLVM_ABI void resolveAllUses(bool ResolveUsers = true);
428
429 unsigned getNumUses() const { return UseMap.size(); }
430
431private:
432 void addRef(void *Ref, OwnerTy Owner);
433 void dropRef(void *Ref);
434 void moveRef(void *Ref, void *New, const Metadata &MD);
435
436 /// Lazily construct RAUW support on MD.
437 ///
438 /// If this is an unresolved MDNode, RAUW support will be created on-demand.
439 /// ValueAsMetadata always has RAUW support.
440 static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
441
442 /// Get RAUW support on MD, if it exists.
443 static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
444
445 /// Check whether this node will support RAUW.
446 ///
447 /// Returns \c true unless getOrCreate() would return null.
448 static bool isReplaceable(const Metadata &MD);
449};
450
451/// Value wrapper in the Metadata hierarchy.
452///
453/// This is a custom value handle that allows other metadata to refer to
454/// classes in the Value hierarchy.
455///
456/// Because of full uniquing support, each value is only wrapped by a single \a
457/// ValueAsMetadata object, so the lookup maps are far more efficient than
458/// those using ValueHandleBase.
461 friend class LLVMContextImpl;
462
463 Value *V;
464
465 /// Drop users without RAUW (during teardown).
466 void dropUsers() {
467 ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
468 }
469
470protected:
473 assert(V && "Expected valid value");
474 }
475
476 ~ValueAsMetadata() = default;
477
478public:
479 LLVM_ABI static ValueAsMetadata *get(Value *V);
480
484
488
490
494
498
499 Value *getValue() const { return V; }
500 Type *getType() const { return V->getType(); }
501 LLVMContext &getContext() const { return V->getContext(); }
502
509
510 LLVM_ABI static void handleDeletion(Value *V);
511 LLVM_ABI static void handleRAUW(Value *From, Value *To);
512
513protected:
514 /// Handle collisions after \a Value::replaceAllUsesWith().
515 ///
516 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
517 /// \a Value gets RAUW'ed and the target already exists, this is used to
518 /// merge the two metadata nodes.
522
523public:
524 static bool classof(const Metadata *MD) {
525 return MD->getMetadataID() == LocalAsMetadataKind ||
526 MD->getMetadataID() == ConstantAsMetadataKind;
527 }
528};
529
530class ConstantAsMetadata : public ValueAsMetadata {
531 friend class ValueAsMetadata;
532
533 ConstantAsMetadata(Constant *C)
534 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
535
536public:
537 static ConstantAsMetadata *get(Constant *C) {
539 }
540
541 static ConstantAsMetadata *getIfExists(Constant *C) {
543 }
544
548
549 static bool classof(const Metadata *MD) {
550 return MD->getMetadataID() == ConstantAsMetadataKind;
551 }
552};
553
554class LocalAsMetadata : public ValueAsMetadata {
555 friend class ValueAsMetadata;
556
557 LocalAsMetadata(Value *Local)
558 : ValueAsMetadata(LocalAsMetadataKind, Local) {
559 assert(!isa<Constant>(Local) && "Expected local value");
560 }
561
562public:
563 static LocalAsMetadata *get(Value *Local) {
565 }
566
567 static LocalAsMetadata *getIfExists(Value *Local) {
569 }
570
571 static bool classof(const Metadata *MD) {
572 return MD->getMetadataID() == LocalAsMetadataKind;
573 }
574};
575
576/// Transitional API for extracting constants from Metadata.
577///
578/// This namespace contains transitional functions for metadata that points to
579/// \a Constants.
580///
581/// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
582/// operands could refer to any \a Value. There's was a lot of code like this:
583///
584/// \code
585/// MDNode *N = ...;
586/// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
587/// \endcode
588///
589/// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
590/// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
591/// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
592/// cast in the \a Value hierarchy. Besides creating boiler-plate, this
593/// requires subtle control flow changes.
594///
595/// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
596/// so that metadata can refer to numbers without traversing a bridge to the \a
597/// Value hierarchy. In this final state, the code above would look like this:
598///
599/// \code
600/// MDNode *N = ...;
601/// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
602/// \endcode
603///
604/// The API in this namespace supports the transition. \a MDInt doesn't exist
605/// yet, and even once it does, changing each metadata schema to use it is its
606/// own mini-project. In the meantime this API prevents us from introducing
607/// complex and bug-prone control flow that will disappear in the end. In
608/// particular, the above code looks like this:
609///
610/// \code
611/// MDNode *N = ...;
612/// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
613/// \endcode
614///
615/// The full set of provided functions includes:
616///
617/// mdconst::hasa <=> isa
618/// mdconst::extract <=> cast
619/// mdconst::extract_or_null <=> cast_or_null
620/// mdconst::dyn_extract <=> dyn_cast
621/// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
622///
623/// The target of the cast must be a subclass of \a Constant.
624namespace mdconst {
625
626namespace detail {
627template <typename U, typename V>
628using check_has_dereference = decltype(static_cast<V>(*std::declval<U &>()));
629
630template <typename U, typename V>
631static constexpr bool HasDereference =
633
634template <class V, class M> struct IsValidPointer {
635 static const bool value = std::is_base_of<Constant, V>::value &&
637};
638template <class V, class M> struct IsValidReference {
639 static const bool value = std::is_base_of<Constant, V>::value &&
640 std::is_convertible<M, const Metadata &>::value;
641};
642
643} // end namespace detail
644
645/// Check whether Metadata has a Value.
646///
647/// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
648/// type \c X.
649template <class X, class Y>
650inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, bool>
651hasa(Y &&MD) {
652 assert(MD && "Null pointer sent into hasa");
653 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
654 return isa<X>(V->getValue());
655 return false;
656}
657template <class X, class Y>
658inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, bool>
659hasa(Y &MD) {
660 return hasa(&MD);
661}
662
663/// Extract a Value from Metadata.
664///
665/// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
666template <class X, class Y>
667inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
668extract(Y &&MD) {
670}
671template <class X, class Y>
672inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, X *>
673extract(Y &MD) {
674 return extract(&MD);
675}
676
677/// Extract a Value from Metadata, allowing null.
678///
679/// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
680/// from \c MD, allowing \c MD to be null.
681template <class X, class Y>
682inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
684 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
685 return cast<X>(V->getValue());
686 return nullptr;
687}
688
689/// Extract a Value from Metadata, if any.
690///
691/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
692/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
693/// Value it does contain is of the wrong subclass.
694template <class X, class Y>
695inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
697 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
698 return dyn_cast<X>(V->getValue());
699 return nullptr;
700}
701
702/// Extract a Value from Metadata, if any, allowing null.
703///
704/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
705/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
706/// Value it does contain is of the wrong subclass, allowing \c MD to be null.
707template <class X, class Y>
708inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
710 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
711 return dyn_cast<X>(V->getValue());
712 return nullptr;
713}
714
715} // end namespace mdconst
716
717//===----------------------------------------------------------------------===//
718/// A single uniqued string.
719///
720/// These are used to efficiently contain a byte sequence for metadata.
721/// MDString is always unnamed.
722class MDString : public Metadata {
723 friend class StringMapEntryStorage<MDString>;
724
725 StringMapEntry<MDString> *Entry = nullptr;
726
727 MDString() : Metadata(MDStringKind, Uniqued) {}
728
729public:
730 MDString(const MDString &) = delete;
731 MDString &operator=(MDString &&) = delete;
732 MDString &operator=(const MDString &) = delete;
733
734 LLVM_ABI static MDString *get(LLVMContext &Context, StringRef Str);
735 static MDString *get(LLVMContext &Context, const char *Str) {
736 return get(Context, Str ? StringRef(Str) : StringRef());
737 }
738 LLVM_ABI static MDString *getIfExists(LLVMContext &Context, StringRef Str);
739
741
742 unsigned getLength() const { return (unsigned)getString().size(); }
743
745
746 /// Pointer to the first byte of the string.
747 iterator begin() const { return getString().begin(); }
748
749 /// Pointer to one byte past the end of the string.
750 iterator end() const { return getString().end(); }
751
752 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
753 const unsigned char *bytes_end() const { return getString().bytes_end(); }
754
755 /// Methods for support type inquiry through isa, cast, and dyn_cast.
756 static bool classof(const Metadata *MD) {
757 return MD->getMetadataID() == MDStringKind;
758 }
759};
760
761/// A collection of metadata nodes that might be associated with a
762/// memory access used by the alias-analysis infrastructure.
763struct AAMDNodes {
764 explicit AAMDNodes() = default;
765 explicit AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N, MDNode *NAS)
766 : TBAA(T), TBAAStruct(TS), Scope(S), NoAlias(N), NoAliasAddrSpace(NAS) {}
767
768 bool operator==(const AAMDNodes &A) const {
769 return TBAA == A.TBAA && TBAAStruct == A.TBAAStruct && Scope == A.Scope &&
770 NoAlias == A.NoAlias && NoAliasAddrSpace == A.NoAliasAddrSpace;
771 }
772
773 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
774
775 explicit operator bool() const {
776 return TBAA || TBAAStruct || Scope || NoAlias || NoAliasAddrSpace;
777 }
778
779 /// The tag for type-based alias analysis.
780 MDNode *TBAA = nullptr;
781
782 /// The tag for type-based alias analysis (tbaa struct).
783 MDNode *TBAAStruct = nullptr;
784
785 /// The tag for alias scope specification (used with noalias).
786 MDNode *Scope = nullptr;
787
788 /// The tag specifying the noalias scope.
789 MDNode *NoAlias = nullptr;
790
791 /// The tag specifying the noalias address spaces.
793
794 // Shift tbaa Metadata node to start off bytes later
795 LLVM_ABI static MDNode *shiftTBAA(MDNode *M, size_t off);
796
797 // Shift tbaa.struct Metadata node to start off bytes later
798 LLVM_ABI static MDNode *shiftTBAAStruct(MDNode *M, size_t off);
799
800 // Extend tbaa Metadata node to apply to a series of bytes of length len.
801 // A size of -1 denotes an unknown size.
802 LLVM_ABI static MDNode *extendToTBAA(MDNode *TBAA, ssize_t len);
803
804 /// Given two sets of AAMDNodes that apply to the same pointer,
805 /// give the best AAMDNodes that are compatible with both (i.e. a set of
806 /// nodes whose allowable aliasing conclusions are a subset of those
807 /// allowable by both of the inputs). However, for efficiency
808 /// reasons, do not create any new MDNodes.
810 AAMDNodes Result;
811 Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
812 Result.TBAAStruct = Other.TBAAStruct == TBAAStruct ? TBAAStruct : nullptr;
813 Result.Scope = Other.Scope == Scope ? Scope : nullptr;
814 Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
815 Result.NoAliasAddrSpace =
816 Other.NoAliasAddrSpace == NoAliasAddrSpace ? NoAliasAddrSpace : nullptr;
817 return Result;
818 }
819
820 /// Create a new AAMDNode that describes this AAMDNode after applying a
821 /// constant offset to the start of the pointer.
822 AAMDNodes shift(size_t Offset) const {
823 AAMDNodes Result;
824 Result.TBAA = TBAA ? shiftTBAA(TBAA, Offset) : nullptr;
825 Result.TBAAStruct =
827 Result.Scope = Scope;
828 Result.NoAlias = NoAlias;
829 Result.NoAliasAddrSpace = NoAliasAddrSpace;
830 return Result;
831 }
832
833 /// Create a new AAMDNode that describes this AAMDNode after extending it to
834 /// apply to a series of bytes of length Len. A size of -1 denotes an unknown
835 /// size.
836 AAMDNodes extendTo(ssize_t Len) const {
837 AAMDNodes Result;
838 Result.TBAA = TBAA ? extendToTBAA(TBAA, Len) : nullptr;
839 // tbaa.struct contains (offset, size, type) triples. Extending the length
840 // of the tbaa.struct doesn't require changing this (though more information
841 // could be provided by adding more triples at subsequent lengths).
842 Result.TBAAStruct = TBAAStruct;
843 Result.Scope = Scope;
844 Result.NoAlias = NoAlias;
845 Result.NoAliasAddrSpace = NoAliasAddrSpace;
846 return Result;
847 }
848
849 /// Given two sets of AAMDNodes applying to potentially different locations,
850 /// determine the best AAMDNodes that apply to both.
851 LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const;
852
853 /// Determine the best AAMDNodes after concatenating two different locations
854 /// together. Different from `merge`, where different locations should
855 /// overlap each other, `concat` puts non-overlapping locations together.
857
858 /// Create a new AAMDNode for accessing \p AccessSize bytes of this AAMDNode.
859 /// If this AAMDNode has !tbaa.struct and \p AccessSize matches the size of
860 /// the field at offset 0, get the TBAA tag describing the accessed field.
861 /// If such an AAMDNode already embeds !tbaa, the existing one is retrieved.
862 /// Finally, !tbaa.struct is zeroed out.
863 LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize);
864 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
865 const DataLayout &DL);
866 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, unsigned AccessSize);
867};
868
869// Specialize DenseMapInfo for AAMDNodes.
883
884/// Tracking metadata reference owned by Metadata.
885///
886/// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
887/// of \a Metadata, which has the option of registering itself for callbacks to
888/// re-unique itself.
889///
890/// In particular, this is used by \a MDNode.
892 Metadata *MD = nullptr;
893
894public:
895 MDOperand() = default;
896 MDOperand(const MDOperand &) = delete;
898 MD = Op.MD;
899 if (MD)
900 (void)MetadataTracking::retrack(Op.MD, MD);
901 Op.MD = nullptr;
902 }
903 MDOperand &operator=(const MDOperand &) = delete;
905 MD = Op.MD;
906 if (MD)
907 (void)MetadataTracking::retrack(Op.MD, MD);
908 Op.MD = nullptr;
909 return *this;
910 }
911
912 // Check if MDOperand is of type MDString and equals `Str`.
913 bool equalsStr(StringRef Str) const {
914 return isa_and_nonnull<MDString>(get()) &&
915 cast<MDString>(get())->getString() == Str;
916 }
917
918 ~MDOperand() { untrack(); }
919
920 Metadata *get() const { return MD; }
921 operator Metadata *() const { return get(); }
922 Metadata *operator->() const { return get(); }
923 Metadata &operator*() const { return *get(); }
924
925 void reset() {
926 untrack();
927 MD = nullptr;
928 }
930 untrack();
931 this->MD = MD;
932 track(Owner);
933 }
934
935private:
936 void track(Metadata *Owner) {
937 if (MD) {
938 if (Owner)
939 MetadataTracking::track(this, *MD, *Owner);
940 else
942 }
943 }
944
945 void untrack() {
946 assert(static_cast<void *>(this) == &MD && "Expected same address");
947 if (MD)
949 }
950};
951
952template <> struct simplify_type<MDOperand> {
954
955 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
956};
957
958template <> struct simplify_type<const MDOperand> {
960
961 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
962};
963
964/// Pointer to the context, with optional RAUW support.
965///
966/// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
967/// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
970
971public:
972 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
974 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
975 : Ptr(ReplaceableUses.release()) {
976 assert(getReplaceableUses() && "Expected non-null replaceable uses");
977 }
985
986 operator LLVMContext &() { return getContext(); }
987
988 /// Whether this contains RAUW support.
989 bool hasReplaceableUses() const {
991 }
992
994 if (hasReplaceableUses())
995 return getReplaceableUses()->getContext();
996 return *cast<LLVMContext *>(Ptr);
997 }
998
1000 if (hasReplaceableUses())
1002 return nullptr;
1003 }
1004
1005 /// Ensure that this has RAUW support, and then return it.
1007 if (!hasReplaceableUses())
1008 makeReplaceable(std::make_unique<ReplaceableMetadataImpl>(getContext()));
1009 return getReplaceableUses();
1010 }
1011
1012 /// Assign RAUW support to this.
1013 ///
1014 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
1015 /// not be null).
1016 void
1017 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
1018 assert(ReplaceableUses && "Expected non-null replaceable uses");
1019 assert(&ReplaceableUses->getContext() == &getContext() &&
1020 "Expected same context");
1021 delete getReplaceableUses();
1022 Ptr = ReplaceableUses.release();
1023 }
1024
1025 /// Drop RAUW support.
1026 ///
1027 /// Cede ownership of RAUW support, returning it.
1028 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
1029 assert(hasReplaceableUses() && "Expected to own replaceable uses");
1030 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
1032 Ptr = &ReplaceableUses->getContext();
1033 return ReplaceableUses;
1034 }
1035};
1036
1038 inline void operator()(MDNode *Node) const;
1039};
1040
1041#define HANDLE_MDNODE_LEAF(CLASS) \
1042 using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
1043#define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
1044#include "llvm/IR/Metadata.def"
1045
1046/// Metadata node.
1047///
1048/// Metadata nodes can be uniqued, like constants, or distinct. Temporary
1049/// metadata nodes (with full support for RAUW) can be used to delay uniquing
1050/// until forward references are known. The basic metadata node is an \a
1051/// MDTuple.
1052///
1053/// There is limited support for RAUW at construction time. At construction
1054/// time, if any operand is a temporary node (or an unresolved uniqued node,
1055/// which indicates a transitive temporary operand), the node itself will be
1056/// unresolved. As soon as all operands become resolved, it will drop RAUW
1057/// support permanently.
1058///
1059/// If an unresolved node is part of a cycle, \a resolveCycles() needs
1060/// to be called on some member of the cycle once all temporary nodes have been
1061/// replaced.
1062///
1063/// MDNodes can be large or small, as well as resizable or non-resizable.
1064/// Large MDNodes' operands are allocated in a separate storage vector,
1065/// whereas small MDNodes' operands are co-allocated. Distinct and temporary
1066/// MDnodes are resizable, but only MDTuples support this capability.
1067///
1068/// Clients can add operands to resizable MDNodes using push_back().
1069class MDNode : public Metadata {
1071 friend class LLVMContextImpl;
1072 friend class DIAssignID;
1073
1074 /// The header that is coallocated with an MDNode along with its "small"
1075 /// operands. It is located immediately before the main body of the node.
1076 /// The operands are in turn located immediately before the header.
1077 /// For resizable MDNodes, the space for the storage vector is also allocated
1078 /// immediately before the header, overlapping with the operands.
1079 /// Explicity set alignment because bitfields by default have an
1080 /// alignment of 1 on z/OS.
1081 struct alignas(alignof(size_t)) Header {
1082 size_t IsResizable : 1;
1083 size_t IsLarge : 1;
1084 size_t SmallSize : 4;
1085 size_t SmallNumOps : 4;
1086 size_t : sizeof(size_t) * CHAR_BIT - 10;
1087
1088 unsigned NumUnresolved = 0;
1089 using LargeStorageVector = SmallVector<MDOperand, 0>;
1090
1091 static constexpr size_t NumOpsFitInVector =
1092 sizeof(LargeStorageVector) / sizeof(MDOperand);
1093 static_assert(
1094 NumOpsFitInVector * sizeof(MDOperand) == sizeof(LargeStorageVector),
1095 "sizeof(LargeStorageVector) must be a multiple of sizeof(MDOperand)");
1096
1097 static constexpr size_t MaxSmallSize = 15;
1098
1099 static constexpr size_t getOpSize(unsigned NumOps) {
1100 return sizeof(MDOperand) * NumOps;
1101 }
1102 /// Returns the number of operands the node has space for based on its
1103 /// allocation characteristics.
1104 static size_t getSmallSize(size_t NumOps, bool IsResizable, bool IsLarge) {
1105 return IsLarge ? NumOpsFitInVector
1106 : std::max(NumOps, NumOpsFitInVector * IsResizable);
1107 }
1108 /// Returns the number of bytes allocated for operands and header.
1109 static size_t getAllocSize(StorageType Storage, size_t NumOps) {
1110 return getOpSize(
1111 getSmallSize(NumOps, isResizable(Storage), isLarge(NumOps))) +
1112 sizeof(Header);
1113 }
1114
1115 /// Only temporary and distinct nodes are resizable.
1116 static bool isResizable(StorageType Storage) { return Storage != Uniqued; }
1117 static bool isLarge(size_t NumOps) { return NumOps > MaxSmallSize; }
1118
1119 size_t getAllocSize() const {
1120 return getOpSize(SmallSize) + sizeof(Header);
1121 }
1122 void *getAllocation() {
1123 return reinterpret_cast<char *>(this + 1) -
1124 alignTo(getAllocSize(), alignof(uint64_t));
1125 }
1126
1127 void *getLargePtr() const {
1128 static_assert(alignof(LargeStorageVector) <= alignof(Header),
1129 "LargeStorageVector too strongly aligned");
1130 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
1131 sizeof(LargeStorageVector);
1132 }
1133
1134 LLVM_ABI void *getSmallPtr();
1135
1136 LargeStorageVector &getLarge() {
1137 assert(IsLarge);
1138 return *reinterpret_cast<LargeStorageVector *>(getLargePtr());
1139 }
1140
1141 const LargeStorageVector &getLarge() const {
1142 assert(IsLarge);
1143 return *reinterpret_cast<const LargeStorageVector *>(getLargePtr());
1144 }
1145
1146 LLVM_ABI void resizeSmall(size_t NumOps);
1147 LLVM_ABI void resizeSmallToLarge(size_t NumOps);
1148 LLVM_ABI void resize(size_t NumOps);
1149
1150 LLVM_ABI explicit Header(size_t NumOps, StorageType Storage);
1151 LLVM_ABI ~Header();
1152
1154 if (IsLarge)
1155 return getLarge();
1156 return MutableArrayRef(
1157 reinterpret_cast<MDOperand *>(this) - SmallSize, SmallNumOps);
1158 }
1159
1161 if (IsLarge)
1162 return getLarge();
1163 return ArrayRef(reinterpret_cast<const MDOperand *>(this) - SmallSize,
1164 SmallNumOps);
1165 }
1166
1167 unsigned getNumOperands() const {
1168 if (!IsLarge)
1169 return SmallNumOps;
1170 return getLarge().size();
1171 }
1172 };
1173
1174 Header &getHeader() { return *(reinterpret_cast<Header *>(this) - 1); }
1175
1176 const Header &getHeader() const {
1177 return *(reinterpret_cast<const Header *>(this) - 1);
1178 }
1179
1180 ContextAndReplaceableUses Context;
1181
1182protected:
1183 LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
1185 ~MDNode() = default;
1186
1187 LLVM_ABI void *operator new(size_t Size, size_t NumOps, StorageType Storage);
1188 LLVM_ABI void operator delete(void *Mem);
1189
1190 /// Required by std, but never called.
1191 void operator delete(void *, unsigned) {
1192 llvm_unreachable("Constructor throws?");
1193 }
1194
1195 /// Required by std, but never called.
1196 void operator delete(void *, unsigned, bool) {
1197 llvm_unreachable("Constructor throws?");
1198 }
1199
1201
1202 MDOperand *mutable_begin() { return getHeader().operands().begin(); }
1203 MDOperand *mutable_end() { return getHeader().operands().end(); }
1204
1206
1210
1211public:
1212 MDNode(const MDNode &) = delete;
1213 void operator=(const MDNode &) = delete;
1214 void *operator new(size_t) = delete;
1215
1216 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
1217 static inline MDTuple *getIfExists(LLVMContext &Context,
1219 static inline MDTuple *getDistinct(LLVMContext &Context,
1221 static inline TempMDTuple getTemporary(LLVMContext &Context,
1223
1224 /// Create a (temporary) clone of this.
1225 LLVM_ABI TempMDNode clone() const;
1226
1227 /// Deallocate a node created by getTemporary.
1228 ///
1229 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
1230 /// references will be reset.
1231 LLVM_ABI static void deleteTemporary(MDNode *N);
1232
1233 LLVMContext &getContext() const { return Context.getContext(); }
1234
1235 /// Replace a specific operand.
1236 LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New);
1237
1238 /// Check if node is fully resolved.
1239 ///
1240 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
1241 /// this always returns \c true.
1242 ///
1243 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
1244 /// support (because all operands are resolved).
1245 ///
1246 /// As forward declarations are resolved, their containers should get
1247 /// resolved automatically. However, if this (or one of its operands) is
1248 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
1249 bool isResolved() const { return !isTemporary() && !getNumUnresolved(); }
1250
1251 bool isUniqued() const { return Storage == Uniqued; }
1252 bool isDistinct() const { return Storage == Distinct; }
1253 bool isTemporary() const { return Storage == Temporary; }
1254
1255 bool isReplaceable() const { return isTemporary() || isAlwaysReplaceable(); }
1256 bool isAlwaysReplaceable() const { return getMetadataID() == DIAssignIDKind; }
1257
1258 /// Check if this is a valid generalized type metadata node.
1260 if (getNumOperands() < 2 || !isa<MDString>(getOperand(1)))
1261 return false;
1262 return cast<MDString>(getOperand(1))->getString().ends_with(".generalized");
1263 }
1264
1265 unsigned getNumTemporaryUses() const {
1266 assert(isTemporary() && "Only for temporaries");
1267 return Context.getReplaceableUses()->getNumUses();
1268 }
1269
1270 /// RAUW a temporary.
1271 ///
1272 /// \pre \a isTemporary() must be \c true.
1274 assert(isReplaceable() && "Expected temporary/replaceable node");
1275 if (Context.hasReplaceableUses())
1276 Context.getReplaceableUses()->replaceAllUsesWith(MD);
1277 }
1278
1279 /// Resolve cycles.
1280 ///
1281 /// Once all forward declarations have been resolved, force cycles to be
1282 /// resolved.
1283 ///
1284 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
1285 LLVM_ABI void resolveCycles();
1286
1287 /// Resolve a unique, unresolved node.
1288 LLVM_ABI void resolve();
1289
1290 /// Replace a temporary node with a permanent one.
1291 ///
1292 /// Try to create a uniqued version of \c N -- in place, if possible -- and
1293 /// return it. If \c N cannot be uniqued, return a distinct node instead.
1294 template <class T>
1295 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1296 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
1297 return cast<T>(N.release()->replaceWithPermanentImpl());
1298 }
1299
1300 /// Replace a temporary node with a uniqued one.
1301 ///
1302 /// Create a uniqued version of \c N -- in place, if possible -- and return
1303 /// it. Takes ownership of the temporary node.
1304 ///
1305 /// \pre N does not self-reference.
1306 template <class T>
1307 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1308 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
1309 return cast<T>(N.release()->replaceWithUniquedImpl());
1310 }
1311
1312 /// Replace a temporary node with a distinct one.
1313 ///
1314 /// Create a distinct version of \c N -- in place, if possible -- and return
1315 /// it. Takes ownership of the temporary node.
1316 template <class T>
1317 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1318 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
1319 return cast<T>(N.release()->replaceWithDistinctImpl());
1320 }
1321
1322 /// Print in tree shape.
1323 ///
1324 /// Prints definition of \c this in tree shape.
1325 ///
1326 /// If \c M is provided, metadata nodes will be numbered canonically;
1327 /// otherwise, pointer addresses are substituted.
1328 /// @{
1329 LLVM_ABI void printTree(raw_ostream &OS, const Module *M = nullptr) const;
1331 const Module *M = nullptr) const;
1332 /// @}
1333
1334 /// User-friendly dump in tree shape.
1335 ///
1336 /// If \c M is provided, metadata nodes will be numbered canonically;
1337 /// otherwise, pointer addresses are substituted.
1338 ///
1339 /// Note: this uses an explicit overload instead of default arguments so that
1340 /// the nullptr version is easy to call from a debugger.
1341 ///
1342 /// @{
1343 LLVM_ABI void dumpTree() const;
1344 LLVM_ABI void dumpTree(const Module *M) const;
1345 /// @}
1346
1347private:
1348 LLVM_ABI MDNode *replaceWithPermanentImpl();
1349 LLVM_ABI MDNode *replaceWithUniquedImpl();
1350 LLVM_ABI MDNode *replaceWithDistinctImpl();
1351
1352protected:
1353 /// Set an operand.
1354 ///
1355 /// Sets the operand directly, without worrying about uniquing.
1356 LLVM_ABI void setOperand(unsigned I, Metadata *New);
1357
1358 unsigned getNumUnresolved() const { return getHeader().NumUnresolved; }
1359
1360 void setNumUnresolved(unsigned N) { getHeader().NumUnresolved = N; }
1362 template <class T, class StoreT>
1363 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1364 template <class T> static T *storeImpl(T *N, StorageType Storage);
1365
1366 /// Resize the node to hold \a NumOps operands.
1367 ///
1368 /// \pre \a isTemporary() or \a isDistinct()
1369 /// \pre MetadataID == MDTupleKind
1370 void resize(size_t NumOps) {
1371 assert(!isUniqued() && "Resizing is not supported for uniqued nodes");
1372 assert(getMetadataID() == MDTupleKind &&
1373 "Resizing is not supported for this node kind");
1374 getHeader().resize(NumOps);
1375 }
1376
1377private:
1378 void handleChangedOperand(void *Ref, Metadata *New);
1379
1380 /// Drop RAUW support, if any.
1381 void dropReplaceableUses();
1382
1383 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1384 void decrementUnresolvedOperandCount();
1385 void countUnresolvedOperands();
1386
1387 /// Mutate this to be "uniqued".
1388 ///
1389 /// Mutate this so that \a isUniqued().
1390 /// \pre \a isTemporary().
1391 /// \pre already added to uniquing set.
1392 void makeUniqued();
1393
1394 /// Mutate this to be "distinct".
1395 ///
1396 /// Mutate this so that \a isDistinct().
1397 /// \pre \a isTemporary().
1398 void makeDistinct();
1399
1400 void deleteAsSubclass();
1401 MDNode *uniquify();
1402 void eraseFromStore();
1403
1404 template <class NodeTy> struct HasCachedHash;
1405 template <class NodeTy> static void dispatchRecalculateHash(NodeTy *N) {
1406 if constexpr (HasCachedHash<NodeTy>::value)
1407 N->recalculateHash();
1408 }
1409 template <class NodeTy> static void dispatchResetHash(NodeTy *N) {
1410 if constexpr (HasCachedHash<NodeTy>::value)
1411 N->setHash(0);
1412 }
1413
1414 /// Merge branch weights from two direct callsites.
1415 static MDNode *mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1416 const Instruction *AInstr,
1417 const Instruction *BInstr);
1418
1419public:
1420 using op_iterator = const MDOperand *;
1422
1424 return const_cast<MDNode *>(this)->mutable_begin();
1425 }
1426
1428 return const_cast<MDNode *>(this)->mutable_end();
1429 }
1430
1431 ArrayRef<MDOperand> operands() const { return getHeader().operands(); }
1432
1433 const MDOperand &getOperand(unsigned I) const {
1434 assert(I < getNumOperands() && "Out of range");
1435 return getHeader().operands()[I];
1436 }
1437
1438 /// Return number of MDNode operands.
1439 unsigned getNumOperands() const { return getHeader().getNumOperands(); }
1440
1441 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1442 static bool classof(const Metadata *MD) {
1443 switch (MD->getMetadataID()) {
1444 default:
1445 return false;
1446#define HANDLE_MDNODE_LEAF(CLASS) \
1447 case CLASS##Kind: \
1448 return true;
1449#include "llvm/IR/Metadata.def"
1450 }
1451 }
1452
1453 /// Check whether MDNode is a vtable access.
1454 LLVM_ABI bool isTBAAVtableAccess() const;
1455
1456 /// Methods for metadata merging.
1458 LLVM_ABI static MDNode *intersect(MDNode *A, MDNode *B);
1465 MDNode *B);
1467 /// Merge !prof metadata from two instructions.
1468 /// Currently only implemented with direct callsites with branch weights.
1470 const Instruction *AInstr,
1471 const Instruction *BInstr);
1475 const MDNode *B);
1476
1477 /// Convert !captures metadata to CaptureComponents. MD may be nullptr.
1479 /// Convert CaptureComponents to !captures metadata. The return value may be
1480 /// nullptr.
1483};
1484
1485/// Tuple of metadata.
1486///
1487/// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1488/// default based on their operands.
1489class MDTuple : public MDNode {
1490 friend class LLVMContextImpl;
1491 friend class MDNode;
1492
1493 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1495 : MDNode(C, MDTupleKind, Storage, Vals) {
1496 setHash(Hash);
1497 }
1498
1500
1501 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1502 void recalculateHash();
1503
1504 LLVM_ABI static MDTuple *getImpl(LLVMContext &Context,
1507 bool ShouldCreate = true);
1508
1509 TempMDTuple cloneImpl() const {
1510 ArrayRef<MDOperand> Operands = operands();
1512 }
1513
1514public:
1515 /// Get the hash, if any.
1516 unsigned getHash() const { return SubclassData32; }
1517
1518 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1519 return getImpl(Context, MDs, Uniqued);
1520 }
1521
1522 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1523 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1524 }
1525
1526 /// Return a distinct node.
1527 ///
1528 /// Return a distinct node -- i.e., a node that is not uniqued.
1529 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1530 return getImpl(Context, MDs, Distinct);
1531 }
1532
1533 /// Return a temporary node.
1534 ///
1535 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1536 /// not uniqued, may be RAUW'd, and must be manually deleted with
1537 /// deleteTemporary.
1538 static TempMDTuple getTemporary(LLVMContext &Context,
1540 return TempMDTuple(getImpl(Context, MDs, Temporary));
1541 }
1542
1543 /// Return a (temporary) clone of this.
1544 TempMDTuple clone() const { return cloneImpl(); }
1545
1546 /// Append an element to the tuple. This will resize the node.
1548 size_t NumOps = getNumOperands();
1549 resize(NumOps + 1);
1550 setOperand(NumOps, MD);
1551 }
1552
1553 /// Shrink the operands by 1.
1554 void pop_back() { resize(getNumOperands() - 1); }
1555
1556 static bool classof(const Metadata *MD) {
1557 return MD->getMetadataID() == MDTupleKind;
1558 }
1559};
1560
1562 return MDTuple::get(Context, MDs);
1563}
1564
1566 return MDTuple::getIfExists(Context, MDs);
1567}
1568
1570 return MDTuple::getDistinct(Context, MDs);
1571}
1572
1575 return MDTuple::getTemporary(Context, MDs);
1576}
1577
1581
1582/// This is a simple wrapper around an MDNode which provides a higher-level
1583/// interface by hiding the details of how alias analysis information is encoded
1584/// in its operands.
1586 const MDNode *Node = nullptr;
1587
1588public:
1589 AliasScopeNode() = default;
1590 explicit AliasScopeNode(const MDNode *N) : Node(N) {}
1591
1592 /// Get the MDNode for this AliasScopeNode.
1593 const MDNode *getNode() const { return Node; }
1594
1595 /// Get the MDNode for this AliasScopeNode's domain.
1596 const MDNode *getDomain() const {
1597 if (Node->getNumOperands() < 2)
1598 return nullptr;
1599 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
1600 }
1602 if (Node->getNumOperands() > 2)
1603 if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
1604 return N->getString();
1605 return StringRef();
1606 }
1607};
1608
1609/// Typed iterator through MDNode operands.
1610///
1611/// An iterator that transforms an \a MDNode::iterator into an iterator over a
1612/// particular Metadata subclass.
1613template <class T> class TypedMDOperandIterator {
1614 MDNode::op_iterator I = nullptr;
1615
1616public:
1617 using iterator_category = std::forward_iterator_tag;
1618 using value_type = T *;
1619 using difference_type = std::ptrdiff_t;
1620 using pointer = void;
1621 using reference = T *;
1622
1625
1626 T *operator*() const { return cast_or_null<T>(*I); }
1627
1629 ++I;
1630 return *this;
1631 }
1632
1634 TypedMDOperandIterator Temp(*this);
1635 ++I;
1636 return Temp;
1637 }
1638
1639 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1640 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1641};
1642
1643/// Typed, array-like tuple of metadata.
1644///
1645/// This is a wrapper for \a MDTuple that makes it act like an array holding a
1646/// particular type of metadata.
1647template <class T> class MDTupleTypedArrayWrapper {
1648 const MDTuple *N = nullptr;
1649
1650public:
1653
1654 template <class U>
1657 std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
1658 : N(Other.get()) {}
1659
1660 template <class U>
1663 std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
1664 : N(Other.get()) {}
1665
1666 explicit operator bool() const { return get(); }
1667 explicit operator MDTuple *() const { return get(); }
1668
1669 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1670 MDTuple *operator->() const { return get(); }
1671 MDTuple &operator*() const { return *get(); }
1672
1673 // FIXME: Fix callers and remove condition on N.
1674 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1675 bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1676 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1677
1678 // FIXME: Fix callers and remove condition on N.
1680
1681 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1682 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1683};
1684
1685#define HANDLE_METADATA(CLASS) \
1686 using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1687#include "llvm/IR/Metadata.def"
1688
1689/// Placeholder metadata for operands of distinct MDNodes.
1690///
1691/// This is a lightweight placeholder for an operand of a distinct node. It's
1692/// purpose is to help track forward references when creating a distinct node.
1693/// This allows distinct nodes involved in a cycle to be constructed before
1694/// their operands without requiring a heavyweight temporary node with
1695/// full-blown RAUW support.
1696///
1697/// Each placeholder supports only a single MDNode user. Clients should pass
1698/// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1699/// should be replaced with.
1700///
1701/// While it would be possible to implement move operators, they would be
1702/// fairly expensive. Leave them unimplemented to discourage their use
1703/// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1705 friend class MetadataTracking;
1706
1707 Metadata **Use = nullptr;
1708
1709public:
1711 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1713 }
1714
1718
1720 if (Use)
1721 *Use = nullptr;
1722 }
1723
1724 unsigned getID() const { return SubclassData32; }
1725
1726 /// Replace the use of this with MD.
1728 if (!Use)
1729 return;
1730 *Use = MD;
1731
1732 if (*Use)
1734
1735 Metadata *T = cast<Metadata>(this);
1737 assert(!Use && "Use is still being tracked despite being untracked!");
1738 }
1739};
1740
1741//===----------------------------------------------------------------------===//
1742/// A tuple of MDNodes.
1743///
1744/// Despite its name, a NamedMDNode isn't itself an MDNode.
1745///
1746/// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1747///
1748/// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1749class NamedMDNode : public ilist_node<NamedMDNode> {
1750 friend class LLVMContextImpl;
1751 friend class Module;
1752
1753 std::string Name;
1754 Module *Parent = nullptr;
1755 void *Operands; // SmallVector<TrackingMDRef, 4>
1756
1757 void setParent(Module *M) { Parent = M; }
1758
1759 explicit NamedMDNode(const Twine &N);
1760
1761 template <class T1> class op_iterator_impl {
1762 friend class NamedMDNode;
1763
1764 const NamedMDNode *Node = nullptr;
1765 unsigned Idx = 0;
1766
1767 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1768
1769 public:
1770 using iterator_category = std::bidirectional_iterator_tag;
1771 using value_type = T1;
1772 using difference_type = std::ptrdiff_t;
1773 using pointer = value_type *;
1774 using reference = value_type;
1775
1776 op_iterator_impl() = default;
1777
1778 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1779 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1780
1781 op_iterator_impl &operator++() {
1782 ++Idx;
1783 return *this;
1784 }
1785
1786 op_iterator_impl operator++(int) {
1787 op_iterator_impl tmp(*this);
1788 operator++();
1789 return tmp;
1790 }
1791
1792 op_iterator_impl &operator--() {
1793 --Idx;
1794 return *this;
1795 }
1796
1797 op_iterator_impl operator--(int) {
1798 op_iterator_impl tmp(*this);
1799 operator--();
1800 return tmp;
1801 }
1802
1803 T1 operator*() const { return Node->getOperand(Idx); }
1804 };
1805
1806public:
1807 NamedMDNode(const NamedMDNode &) = delete;
1809
1810 /// Drop all references and remove the node from parent module.
1812
1813 /// Remove all uses and clear node vector.
1815 /// Drop all references to this node's operands.
1816 LLVM_ABI void clearOperands();
1817
1818 /// Get the module that holds this named metadata collection.
1819 inline Module *getParent() { return Parent; }
1820 inline const Module *getParent() const { return Parent; }
1821
1822 LLVM_ABI MDNode *getOperand(unsigned i) const;
1823 LLVM_ABI unsigned getNumOperands() const;
1824 LLVM_ABI void addOperand(MDNode *M);
1825 LLVM_ABI void setOperand(unsigned I, MDNode *New);
1826 LLVM_ABI StringRef getName() const;
1827 LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug = false) const;
1829 bool IsForDebug = false) const;
1830 LLVM_ABI void dump() const;
1831
1832 // ---------------------------------------------------------------------------
1833 // Operand Iterator interface...
1834 //
1835 using op_iterator = op_iterator_impl<MDNode *>;
1836
1837 op_iterator op_begin() { return op_iterator(this, 0); }
1839
1840 using const_op_iterator = op_iterator_impl<const MDNode *>;
1841
1842 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1844
1846 return make_range(op_begin(), op_end());
1847 }
1849 return make_range(op_begin(), op_end());
1850 }
1851};
1852
1853// Create wrappers for C Binding types (see CBindingWrapping.h).
1855
1856} // end namespace llvm
1857
1858#endif // LLVM_IR_METADATA_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
#define X(NUM, ENUM, NAME)
Definition ELF.h:853
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEFINE_ISA_CONVERSION_FUNCTIONS(ty, ref)
#define LLVM_ABI
Definition Compiler.h:213
dxil translate DXIL Translate Metadata
static ManagedStatic< DebugCounterOwner > Owner
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
loop extract
#define I(x, y, z)
Definition MD5.cpp:57
bool operator==(const MergedFunctionsInfo &LHS, const MergedFunctionsInfo &RHS)
#define T
#define T1
This file defines the PointerUnion class, which is a discriminated union of pointer types.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
AliasScopeNode()=default
AliasScopeNode(const MDNode *N)
Definition Metadata.h:1590
const MDNode * getNode() const
Get the MDNode for this AliasScopeNode.
Definition Metadata.h:1593
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1596
StringRef getName() const
Definition Metadata.h:1601
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
friend class ValueAsMetadata
Definition Metadata.h:531
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
Constant * getValue() const
Definition Metadata.h:545
static ConstantAsMetadata * getIfExists(Constant *C)
Definition Metadata.h:541
static bool classof(const Metadata *MD)
Definition Metadata.h:549
This is an important base class in LLVM.
Definition Constant.h:43
ContextAndReplaceableUses & operator=(const ContextAndReplaceableUses &)=delete
ReplaceableMetadataImpl * getReplaceableUses() const
Definition Metadata.h:999
std::unique_ptr< ReplaceableMetadataImpl > takeReplaceableUses()
Drop RAUW support.
Definition Metadata.h:1028
ContextAndReplaceableUses & operator=(ContextAndReplaceableUses &&)=delete
ReplaceableMetadataImpl * getOrCreateReplaceableUses()
Ensure that this has RAUW support, and then return it.
Definition Metadata.h:1006
void makeReplaceable(std::unique_ptr< ReplaceableMetadataImpl > ReplaceableUses)
Assign RAUW support to this.
Definition Metadata.h:1017
ContextAndReplaceableUses(ContextAndReplaceableUses &&)=delete
ContextAndReplaceableUses(const ContextAndReplaceableUses &)=delete
LLVMContext & getContext() const
Definition Metadata.h:993
bool hasReplaceableUses() const
Whether this contains RAUW support.
Definition Metadata.h:989
ContextAndReplaceableUses(LLVMContext &Context)
Definition Metadata.h:972
ContextAndReplaceableUses(std::unique_ptr< ReplaceableMetadataImpl > ReplaceableUses)
Definition Metadata.h:973
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Base class for tracking ValueAsMetadata/DIArgLists with user lookups and Owner callbacks outside of V...
Definition Metadata.h:221
DebugValueUser(const DebugValueUser &X)
Definition Metadata.h:250
DebugValueUser & operator=(DebugValueUser &&X)
Definition Metadata.h:255
DebugValueUser()=default
LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue)
To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where Old is a pointer to one of the poi...
Definition Metadata.cpp:165
bool operator!=(const DebugValueUser &X) const
Definition Metadata.h:292
DebugValueUser(std::array< Metadata *, 3 > DebugValues)
Definition Metadata.h:242
bool operator==(const DebugValueUser &X) const
Definition Metadata.h:289
ArrayRef< Metadata * > getDebugValues() const
Definition Metadata.h:229
DebugValueUser & operator=(const DebugValueUser &X)
Definition Metadata.h:265
std::array< Metadata *, 3 > DebugValues
Definition Metadata.h:227
void resetDebugValue(size_t Idx, Metadata *DebugValue)
Definition Metadata.h:282
LLVM_ABI DbgVariableRecord * getUser()
Definition Metadata.cpp:158
DebugValueUser(DebugValueUser &&X)
Definition Metadata.h:246
void replaceUseWith(Metadata *MD)
Replace the use of this with MD.
Definition Metadata.h:1727
DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &)=delete
DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&)=delete
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
friend class ValueAsMetadata
Definition Metadata.h:555
static LocalAsMetadata * getIfExists(Value *Local)
Definition Metadata.h:567
static LocalAsMetadata * get(Value *Local)
Definition Metadata.h:563
static bool classof(const Metadata *MD)
Definition Metadata.h:571
Metadata node.
Definition Metadata.h:1069
friend class DIAssignID
Definition Metadata.h:1072
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
LLVM_ABI void printTree(raw_ostream &OS, const Module *M=nullptr) const
Print in tree shape.
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
iterator_range< MDOperand * > mutable_op_range
Definition Metadata.h:1205
LLVM_ABI void resolveCycles()
Resolve cycles.
Definition Metadata.cpp:857
LLVM_ABI bool isTBAAVtableAccess() const
Check whether MDNode is a vtable access.
static LLVM_ABI CaptureComponents toCaptureComponents(const MDNode *MD)
Convert !captures metadata to CaptureComponents. MD may be nullptr.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
mutable_op_range mutable_operands()
Definition Metadata.h:1207
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition Metadata.h:1273
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
static LLVM_ABI void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
LLVM_ABI void resolve()
Resolve a unique, unresolved node.
Definition Metadata.cpp:811
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1433
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
LLVM_ABI void storeDistinctInContext()
bool isTemporary() const
Definition Metadata.h:1253
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1573
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1431
op_iterator op_end() const
Definition Metadata.h:1427
bool hasGeneralizedMDString()
Check if this is a valid generalized type metadata node.
Definition Metadata.h:1259
MDNode(const MDNode &)=delete
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1561
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithDistinct(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a distinct one.
Definition Metadata.h:1318
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
static bool classof(const Metadata *MD)
Methods for support type inquiry through isa, cast, and dyn_cast:
Definition Metadata.h:1442
friend class ReplaceableMetadataImpl
Definition Metadata.h:1070
bool isUniqued() const
Definition Metadata.h:1251
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
void setNumUnresolved(unsigned N)
Definition Metadata.h:1360
void resize(size_t NumOps)
Resize the node to hold NumOps operands.
Definition Metadata.h:1370
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1439
MDOperand * mutable_begin()
Definition Metadata.h:1202
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:666
iterator_range< op_iterator > op_range
Definition Metadata.h:1421
friend class LLVMContextImpl
Definition Metadata.h:1071
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition Metadata.cpp:683
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
bool isDistinct() const
Definition Metadata.h:1252
unsigned getNumTemporaryUses() const
Definition Metadata.h:1265
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
bool isReplaceable() const
Definition Metadata.h:1255
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1249
op_iterator op_begin() const
Definition Metadata.h:1423
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericNoFPClass(MDNode *A, MDNode *B)
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
LLVMContext & getContext() const
Definition Metadata.h:1233
MDOperand * mutable_end()
Definition Metadata.h:1203
~MDNode()=default
static LLVM_ABI MDNode * fromCaptureComponents(LLVMContext &Ctx, CaptureComponents CC)
Convert CaptureComponents to !captures metadata.
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithPermanent(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a permanent one.
Definition Metadata.h:1296
LLVM_ABI void dropAllReferences()
Definition Metadata.cpp:923
void operator=(const MDNode &)=delete
const MDOperand * op_iterator
Definition Metadata.h:1420
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
Definition Metadata.h:1308
LLVM_ABI void dumpTree() const
User-friendly dump in tree shape.
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
unsigned getNumUnresolved() const
Definition Metadata.h:1358
bool isAlwaysReplaceable() const
Definition Metadata.h:1256
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
MDOperand()=default
bool equalsStr(StringRef Str) const
Definition Metadata.h:913
void reset(Metadata *MD, Metadata *Owner)
Definition Metadata.h:929
Metadata * operator->() const
Definition Metadata.h:922
MDOperand & operator=(const MDOperand &)=delete
Metadata & operator*() const
Definition Metadata.h:923
Metadata * get() const
Definition Metadata.h:920
MDOperand(const MDOperand &)=delete
MDOperand & operator=(MDOperand &&Op)
Definition Metadata.h:904
MDOperand(MDOperand &&Op)
Definition Metadata.h:897
A single uniqued string.
Definition Metadata.h:722
unsigned getLength() const
Definition Metadata.h:742
const unsigned char * bytes_begin() const
Definition Metadata.h:752
MDString(const MDString &)=delete
static MDString * get(LLVMContext &Context, const char *Str)
Definition Metadata.h:735
MDString & operator=(MDString &&)=delete
static bool classof(const Metadata *MD)
Methods for support type inquiry through isa, cast, and dyn_cast.
Definition Metadata.h:756
const unsigned char * bytes_end() const
Definition Metadata.h:753
iterator begin() const
Pointer to the first byte of the string.
Definition Metadata.h:747
MDString & operator=(const MDString &)=delete
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
static LLVM_ABI MDString * getIfExists(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:624
StringRef::iterator iterator
Definition Metadata.h:744
iterator end() const
Pointer to one byte past the end of the string.
Definition Metadata.h:750
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t<!std::is_convertible< U *, T * >::value > *=nullptr)
Definition Metadata.h:1661
MDTupleTypedArrayWrapper(const MDTuple *N)
Definition Metadata.h:1652
T * operator[](unsigned I) const
Definition Metadata.h:1676
MDTuple * operator->() const
Definition Metadata.h:1670
MDTuple & operator*() const
Definition Metadata.h:1671
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t< std::is_convertible< U *, T * >::value > *=nullptr)
Definition Metadata.h:1655
TypedMDOperandIterator< T > iterator
Definition Metadata.h:1679
Tuple of metadata.
Definition Metadata.h:1489
TempMDTuple clone() const
Return a (temporary) clone of this.
Definition Metadata.h:1544
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1529
static bool classof(const Metadata *MD)
Definition Metadata.h:1556
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition Metadata.h:1547
unsigned getHash() const
Get the hash, if any.
Definition Metadata.h:1516
friend class LLVMContextImpl
Definition Metadata.h:1490
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1518
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1522
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1538
friend class MDNode
Definition Metadata.h:1491
void pop_back()
Shrink the operands by 1.
Definition Metadata.h:1554
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:118
friend class ReplaceableMetadataImpl
Definition Metadata.h:185
friend class LLVMContextImpl
Definition Metadata.h:186
LLVM_ABI ~MetadataAsValue()
Definition Metadata.cpp:72
static bool classof(const Value *V)
Definition Metadata.h:204
Metadata * getMetadata() const
Definition Metadata.h:202
API for tracking metadata references through RAUW and deletion.
Definition Metadata.h:313
static LLVM_ABI bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition Metadata.cpp:253
static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner)
Track the reference to metadata for MetadataAsValue.
Definition Metadata.h:342
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition Metadata.h:358
PointerUnion< MetadataAsValue *, Metadata *, DebugValueUser * > OwnerTy
Definition Metadata.h:377
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition Metadata.h:369
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition Metadata.h:324
static bool track(void *Ref, Metadata &MD, Metadata &Owner)
Track the reference to metadata for Metadata.
Definition Metadata.h:333
static bool track(void *Ref, Metadata &MD, DebugValueUser &Owner)
Track the reference to metadata for DebugValueUser.
Definition Metadata.h:351
Root of the metadata hierarchy.
Definition Metadata.h:64
void handleChangedOperand(void *, Metadata *)
Default handling of a changed operand, which asserts.
Definition Metadata.h:99
StorageType
Active type of storage.
Definition Metadata.h:72
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
static constexpr const unsigned PoisonGeneratingIDs[]
Metadata IDs that may generate poison.
Definition Metadata.h:146
unsigned short SubclassData16
Definition Metadata.h:78
unsigned SubclassData32
Definition Metadata.h:79
~Metadata()=default
unsigned char Storage
Storage flag for non-uniqued, otherwise unowned, metadata.
Definition Metadata.h:75
friend class ReplaceableMetadataImpl
Definition Metadata.h:65
unsigned getMetadataID() const
Definition Metadata.h:104
unsigned char SubclassData1
Definition Metadata.h:77
LLVM_ABI void printAsOperand(raw_ostream &OS, const Module *M=nullptr) const
Print as operand.
Metadata(unsigned ID, StorageType Storage)
Definition Metadata.h:88
LLVM_ABI void dump() const
User-friendly dump.
Manage lifetime of a slot tracker for printing IR.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1749
const_op_iterator op_begin() const
Definition Metadata.h:1842
NamedMDNode(const NamedMDNode &)=delete
op_iterator_impl< const MDNode * > const_op_iterator
Definition Metadata.h:1840
friend class Module
Definition Metadata.h:1751
LLVM_ABI void dump() const
LLVM_ABI void setOperand(unsigned I, MDNode *New)
LLVM_ABI ~NamedMDNode()
LLVM_ABI StringRef getName() const
void dropAllReferences()
Remove all uses and clear node vector.
Definition Metadata.h:1814
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
const_op_iterator op_end() const
Definition Metadata.h:1843
iterator_range< const_op_iterator > operands() const
Definition Metadata.h:1848
op_iterator op_end()
Definition Metadata.h:1838
LLVM_ABI MDNode * getOperand(unsigned i) const
friend class LLVMContextImpl
Definition Metadata.h:1750
op_iterator op_begin()
Definition Metadata.h:1837
op_iterator_impl< MDNode * > op_iterator
Definition Metadata.h:1835
LLVM_ABI unsigned getNumOperands() const
const Module * getParent() const
Definition Metadata.h:1820
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
iterator_range< op_iterator > operands()
Definition Metadata.h:1845
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1819
LLVM_ABI void addOperand(MDNode *M)
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
Shared implementation of use-lists for replaceable metadata.
Definition Metadata.h:391
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:338
LLVM_ABI void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition Metadata.cpp:375
LLVM_ABI SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Returns the list of all DbgVariableRecord users of this.
Definition Metadata.cpp:279
ReplaceableMetadataImpl(LLVMContext &Context)
Definition Metadata.h:403
LLVMContext & getContext() const
Definition Metadata.h:409
unsigned getNumUses() const
Definition Metadata.h:429
LLVM_ABI void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition Metadata.cpp:428
LLVM_ABI SmallVector< Metadata * > getAllArgListUsers()
Returns the list of all DIArgList users of this.
Definition Metadata.cpp:257
MetadataTracking::OwnerTy OwnerTy
Definition Metadata.h:395
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMapEntryStorage - Holds the value in a StringMapEntry.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
const char * iterator
Definition StringRef.h:60
const unsigned char * bytes_end() const
Definition StringRef.h:125
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
const unsigned char * bytes_begin() const
Definition StringRef.h:122
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Typed iterator through MDNode operands.
Definition Metadata.h:1613
TypedMDOperandIterator operator++(int)
Definition Metadata.h:1633
std::ptrdiff_t difference_type
Definition Metadata.h:1619
bool operator==(const TypedMDOperandIterator &X) const
Definition Metadata.h:1639
TypedMDOperandIterator & operator++()
Definition Metadata.h:1628
std::forward_iterator_tag iterator_category
Definition Metadata.h:1617
TypedMDOperandIterator(MDNode::op_iterator I)
Definition Metadata.h:1624
bool operator!=(const TypedMDOperandIterator &X) const
Definition Metadata.h:1640
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:459
Type * getType() const
Definition Metadata.h:500
static LocalAsMetadata * getLocalIfExists(Value *Local)
Definition Metadata.h:495
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition Metadata.h:519
SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Definition Metadata.h:506
LLVMContext & getContext() const
Definition Metadata.h:501
static LLVM_ABI void handleDeletion(Value *V)
Definition Metadata.cpp:533
static LocalAsMetadata * getLocal(Value *Local)
Definition Metadata.h:485
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:509
static ConstantAsMetadata * getConstantIfExists(Value *C)
Definition Metadata.h:491
static ConstantAsMetadata * getConstant(Value *C)
Definition Metadata.h:481
static LLVM_ABI ValueAsMetadata * getIfExists(Value *V)
Definition Metadata.cpp:528
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition Metadata.cpp:552
friend class ReplaceableMetadataImpl
Definition Metadata.h:460
static bool classof(const Metadata *MD)
Definition Metadata.h:524
friend class LLVMContextImpl
Definition Metadata.h:461
SmallVector< Metadata * > getAllArgListUsers()
Definition Metadata.h:503
ValueAsMetadata(unsigned ID, Value *V)
Definition Metadata.h:471
Value * getValue() const
Definition Metadata.h:499
~ValueAsMetadata()=default
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:53
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
struct LLVMOpaqueNamedMDNode * LLVMNamedMDNodeRef
Represents an LLVM Named Metadata Node.
Definition Types.h:96
struct LLVMOpaqueMetadata * LLVMMetadataRef
Represents an LLVM Metadata.
Definition Types.h:89
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
static constexpr bool HasDereference
Definition Metadata.h:631
decltype(static_cast< V >(*std::declval< U & >())) check_has_dereference
Definition Metadata.h:628
Transitional API for extracting constants from Metadata.
Definition Metadata.h:624
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:709
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
Definition Metadata.h:651
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto cast_or_null(const Y &Val)
Definition Casting.h:714
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:397
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
Definition Metadata.h:59
LLVMConstants
Definition Metadata.h:53
@ DEBUG_METADATA_VERSION
Definition Metadata.h:54
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.
static LLVM_ABI MDNode * shiftTBAAStruct(MDNode *M, size_t off)
bool operator!=(const AAMDNodes &A) const
Definition Metadata.h:773
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:792
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:783
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:786
static LLVM_ABI MDNode * extendToTBAA(MDNode *TBAA, ssize_t len)
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
AAMDNodes shift(size_t Offset) const
Create a new AAMDNode that describes this AAMDNode after applying a constant offset to the start of t...
Definition Metadata.h:822
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:789
AAMDNodes intersect(const AAMDNodes &Other) const
Given two sets of AAMDNodes that apply to the same pointer, give the best AAMDNodes that are compatib...
Definition Metadata.h:809
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N, MDNode *NAS)
Definition Metadata.h:765
AAMDNodes extendTo(ssize_t Len) const
Create a new AAMDNode that describes this AAMDNode after extending it to apply to a series of bytes o...
Definition Metadata.h:836
bool operator==(const AAMDNodes &A) const
Definition Metadata.h:768
AAMDNodes()=default
static LLVM_ABI MDNode * shiftTBAA(MDNode *M, size_t off)
static unsigned getHashValue(const AAMDNodes &Val)
Definition Metadata.h:871
static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS)
Definition Metadata.h:879
An information struct used to provide DenseMap with the various necessary components for a given valu...
void operator()(MDNode *Node) const
Definition Metadata.h:1578
static SimpleType getSimplifiedValue(MDOperand &MD)
Definition Metadata.h:955
static SimpleType getSimplifiedValue(const MDOperand &MD)
Definition Metadata.h:961
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34