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) {
669 return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
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.
870template<>
872 static inline AAMDNodes getEmptyKey() {
873 return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), nullptr, nullptr,
874 nullptr, nullptr);
875 }
876
877 static inline AAMDNodes getTombstoneKey() {
879 nullptr, nullptr, nullptr);
880 }
881
889
890 static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
891 return LHS == RHS;
892 }
893};
894
895/// Tracking metadata reference owned by Metadata.
896///
897/// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
898/// of \a Metadata, which has the option of registering itself for callbacks to
899/// re-unique itself.
900///
901/// In particular, this is used by \a MDNode.
903 Metadata *MD = nullptr;
904
905public:
906 MDOperand() = default;
907 MDOperand(const MDOperand &) = delete;
909 MD = Op.MD;
910 if (MD)
911 (void)MetadataTracking::retrack(Op.MD, MD);
912 Op.MD = nullptr;
913 }
914 MDOperand &operator=(const MDOperand &) = delete;
916 MD = Op.MD;
917 if (MD)
918 (void)MetadataTracking::retrack(Op.MD, MD);
919 Op.MD = nullptr;
920 return *this;
921 }
922
923 // Check if MDOperand is of type MDString and equals `Str`.
924 bool equalsStr(StringRef Str) const {
925 return isa_and_nonnull<MDString>(get()) &&
926 cast<MDString>(get())->getString() == Str;
927 }
928
929 ~MDOperand() { untrack(); }
930
931 Metadata *get() const { return MD; }
932 operator Metadata *() const { return get(); }
933 Metadata *operator->() const { return get(); }
934 Metadata &operator*() const { return *get(); }
935
936 void reset() {
937 untrack();
938 MD = nullptr;
939 }
941 untrack();
942 this->MD = MD;
943 track(Owner);
944 }
945
946private:
947 void track(Metadata *Owner) {
948 if (MD) {
949 if (Owner)
950 MetadataTracking::track(this, *MD, *Owner);
951 else
953 }
954 }
955
956 void untrack() {
957 assert(static_cast<void *>(this) == &MD && "Expected same address");
958 if (MD)
960 }
961};
962
963template <> struct simplify_type<MDOperand> {
965
966 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
967};
968
969template <> struct simplify_type<const MDOperand> {
971
972 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
973};
974
975/// Pointer to the context, with optional RAUW support.
976///
977/// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
978/// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
981
982public:
983 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
985 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
986 : Ptr(ReplaceableUses.release()) {
987 assert(getReplaceableUses() && "Expected non-null replaceable uses");
988 }
996
997 operator LLVMContext &() { return getContext(); }
998
999 /// Whether this contains RAUW support.
1000 bool hasReplaceableUses() const {
1002 }
1003
1005 if (hasReplaceableUses())
1006 return getReplaceableUses()->getContext();
1007 return *cast<LLVMContext *>(Ptr);
1008 }
1009
1011 if (hasReplaceableUses())
1013 return nullptr;
1014 }
1015
1016 /// Ensure that this has RAUW support, and then return it.
1018 if (!hasReplaceableUses())
1019 makeReplaceable(std::make_unique<ReplaceableMetadataImpl>(getContext()));
1020 return getReplaceableUses();
1021 }
1022
1023 /// Assign RAUW support to this.
1024 ///
1025 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
1026 /// not be null).
1027 void
1028 makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
1029 assert(ReplaceableUses && "Expected non-null replaceable uses");
1030 assert(&ReplaceableUses->getContext() == &getContext() &&
1031 "Expected same context");
1032 delete getReplaceableUses();
1033 Ptr = ReplaceableUses.release();
1034 }
1035
1036 /// Drop RAUW support.
1037 ///
1038 /// Cede ownership of RAUW support, returning it.
1039 std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
1040 assert(hasReplaceableUses() && "Expected to own replaceable uses");
1041 std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
1043 Ptr = &ReplaceableUses->getContext();
1044 return ReplaceableUses;
1045 }
1046};
1047
1049 inline void operator()(MDNode *Node) const;
1050};
1051
1052#define HANDLE_MDNODE_LEAF(CLASS) \
1053 using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
1054#define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
1055#include "llvm/IR/Metadata.def"
1056
1057/// Metadata node.
1058///
1059/// Metadata nodes can be uniqued, like constants, or distinct. Temporary
1060/// metadata nodes (with full support for RAUW) can be used to delay uniquing
1061/// until forward references are known. The basic metadata node is an \a
1062/// MDTuple.
1063///
1064/// There is limited support for RAUW at construction time. At construction
1065/// time, if any operand is a temporary node (or an unresolved uniqued node,
1066/// which indicates a transitive temporary operand), the node itself will be
1067/// unresolved. As soon as all operands become resolved, it will drop RAUW
1068/// support permanently.
1069///
1070/// If an unresolved node is part of a cycle, \a resolveCycles() needs
1071/// to be called on some member of the cycle once all temporary nodes have been
1072/// replaced.
1073///
1074/// MDNodes can be large or small, as well as resizable or non-resizable.
1075/// Large MDNodes' operands are allocated in a separate storage vector,
1076/// whereas small MDNodes' operands are co-allocated. Distinct and temporary
1077/// MDnodes are resizable, but only MDTuples support this capability.
1078///
1079/// Clients can add operands to resizable MDNodes using push_back().
1080class MDNode : public Metadata {
1082 friend class LLVMContextImpl;
1083 friend class DIAssignID;
1084
1085 /// The header that is coallocated with an MDNode along with its "small"
1086 /// operands. It is located immediately before the main body of the node.
1087 /// The operands are in turn located immediately before the header.
1088 /// For resizable MDNodes, the space for the storage vector is also allocated
1089 /// immediately before the header, overlapping with the operands.
1090 /// Explicity set alignment because bitfields by default have an
1091 /// alignment of 1 on z/OS.
1092 struct alignas(alignof(size_t)) Header {
1093 size_t IsResizable : 1;
1094 size_t IsLarge : 1;
1095 size_t SmallSize : 4;
1096 size_t SmallNumOps : 4;
1097 size_t : sizeof(size_t) * CHAR_BIT - 10;
1098
1099 unsigned NumUnresolved = 0;
1100 using LargeStorageVector = SmallVector<MDOperand, 0>;
1101
1102 static constexpr size_t NumOpsFitInVector =
1103 sizeof(LargeStorageVector) / sizeof(MDOperand);
1104 static_assert(
1105 NumOpsFitInVector * sizeof(MDOperand) == sizeof(LargeStorageVector),
1106 "sizeof(LargeStorageVector) must be a multiple of sizeof(MDOperand)");
1107
1108 static constexpr size_t MaxSmallSize = 15;
1109
1110 static constexpr size_t getOpSize(unsigned NumOps) {
1111 return sizeof(MDOperand) * NumOps;
1112 }
1113 /// Returns the number of operands the node has space for based on its
1114 /// allocation characteristics.
1115 static size_t getSmallSize(size_t NumOps, bool IsResizable, bool IsLarge) {
1116 return IsLarge ? NumOpsFitInVector
1117 : std::max(NumOps, NumOpsFitInVector * IsResizable);
1118 }
1119 /// Returns the number of bytes allocated for operands and header.
1120 static size_t getAllocSize(StorageType Storage, size_t NumOps) {
1121 return getOpSize(
1122 getSmallSize(NumOps, isResizable(Storage), isLarge(NumOps))) +
1123 sizeof(Header);
1124 }
1125
1126 /// Only temporary and distinct nodes are resizable.
1127 static bool isResizable(StorageType Storage) { return Storage != Uniqued; }
1128 static bool isLarge(size_t NumOps) { return NumOps > MaxSmallSize; }
1129
1130 size_t getAllocSize() const {
1131 return getOpSize(SmallSize) + sizeof(Header);
1132 }
1133 void *getAllocation() {
1134 return reinterpret_cast<char *>(this + 1) -
1135 alignTo(getAllocSize(), alignof(uint64_t));
1136 }
1137
1138 void *getLargePtr() const {
1139 static_assert(alignof(LargeStorageVector) <= alignof(Header),
1140 "LargeStorageVector too strongly aligned");
1141 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
1142 sizeof(LargeStorageVector);
1143 }
1144
1145 LLVM_ABI void *getSmallPtr();
1146
1147 LargeStorageVector &getLarge() {
1148 assert(IsLarge);
1149 return *reinterpret_cast<LargeStorageVector *>(getLargePtr());
1150 }
1151
1152 const LargeStorageVector &getLarge() const {
1153 assert(IsLarge);
1154 return *reinterpret_cast<const LargeStorageVector *>(getLargePtr());
1155 }
1156
1157 LLVM_ABI void resizeSmall(size_t NumOps);
1158 LLVM_ABI void resizeSmallToLarge(size_t NumOps);
1159 LLVM_ABI void resize(size_t NumOps);
1160
1161 LLVM_ABI explicit Header(size_t NumOps, StorageType Storage);
1162 LLVM_ABI ~Header();
1163
1165 if (IsLarge)
1166 return getLarge();
1167 return MutableArrayRef(
1168 reinterpret_cast<MDOperand *>(this) - SmallSize, SmallNumOps);
1169 }
1170
1172 if (IsLarge)
1173 return getLarge();
1174 return ArrayRef(reinterpret_cast<const MDOperand *>(this) - SmallSize,
1175 SmallNumOps);
1176 }
1177
1178 unsigned getNumOperands() const {
1179 if (!IsLarge)
1180 return SmallNumOps;
1181 return getLarge().size();
1182 }
1183 };
1184
1185 Header &getHeader() { return *(reinterpret_cast<Header *>(this) - 1); }
1186
1187 const Header &getHeader() const {
1188 return *(reinterpret_cast<const Header *>(this) - 1);
1189 }
1190
1191 ContextAndReplaceableUses Context;
1192
1193protected:
1194 LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
1196 ~MDNode() = default;
1197
1198 LLVM_ABI void *operator new(size_t Size, size_t NumOps, StorageType Storage);
1199 LLVM_ABI void operator delete(void *Mem);
1200
1201 /// Required by std, but never called.
1202 void operator delete(void *, unsigned) {
1203 llvm_unreachable("Constructor throws?");
1204 }
1205
1206 /// Required by std, but never called.
1207 void operator delete(void *, unsigned, bool) {
1208 llvm_unreachable("Constructor throws?");
1209 }
1210
1212
1213 MDOperand *mutable_begin() { return getHeader().operands().begin(); }
1214 MDOperand *mutable_end() { return getHeader().operands().end(); }
1215
1217
1221
1222public:
1223 MDNode(const MDNode &) = delete;
1224 void operator=(const MDNode &) = delete;
1225 void *operator new(size_t) = delete;
1226
1227 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
1228 static inline MDTuple *getIfExists(LLVMContext &Context,
1230 static inline MDTuple *getDistinct(LLVMContext &Context,
1232 static inline TempMDTuple getTemporary(LLVMContext &Context,
1234
1235 /// Create a (temporary) clone of this.
1236 LLVM_ABI TempMDNode clone() const;
1237
1238 /// Deallocate a node created by getTemporary.
1239 ///
1240 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
1241 /// references will be reset.
1242 LLVM_ABI static void deleteTemporary(MDNode *N);
1243
1244 LLVMContext &getContext() const { return Context.getContext(); }
1245
1246 /// Replace a specific operand.
1247 LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New);
1248
1249 /// Check if node is fully resolved.
1250 ///
1251 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
1252 /// this always returns \c true.
1253 ///
1254 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
1255 /// support (because all operands are resolved).
1256 ///
1257 /// As forward declarations are resolved, their containers should get
1258 /// resolved automatically. However, if this (or one of its operands) is
1259 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
1260 bool isResolved() const { return !isTemporary() && !getNumUnresolved(); }
1261
1262 bool isUniqued() const { return Storage == Uniqued; }
1263 bool isDistinct() const { return Storage == Distinct; }
1264 bool isTemporary() const { return Storage == Temporary; }
1265
1266 bool isReplaceable() const { return isTemporary() || isAlwaysReplaceable(); }
1267 bool isAlwaysReplaceable() const { return getMetadataID() == DIAssignIDKind; }
1268
1269 /// Check if this is a valid generalized type metadata node.
1271 if (getNumOperands() < 2 || !isa<MDString>(getOperand(1)))
1272 return false;
1273 return cast<MDString>(getOperand(1))->getString().ends_with(".generalized");
1274 }
1275
1276 unsigned getNumTemporaryUses() const {
1277 assert(isTemporary() && "Only for temporaries");
1278 return Context.getReplaceableUses()->getNumUses();
1279 }
1280
1281 /// RAUW a temporary.
1282 ///
1283 /// \pre \a isTemporary() must be \c true.
1285 assert(isReplaceable() && "Expected temporary/replaceable node");
1286 if (Context.hasReplaceableUses())
1287 Context.getReplaceableUses()->replaceAllUsesWith(MD);
1288 }
1289
1290 /// Resolve cycles.
1291 ///
1292 /// Once all forward declarations have been resolved, force cycles to be
1293 /// resolved.
1294 ///
1295 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
1296 LLVM_ABI void resolveCycles();
1297
1298 /// Resolve a unique, unresolved node.
1299 LLVM_ABI void resolve();
1300
1301 /// Replace a temporary node with a permanent one.
1302 ///
1303 /// Try to create a uniqued version of \c N -- in place, if possible -- and
1304 /// return it. If \c N cannot be uniqued, return a distinct node instead.
1305 template <class T>
1306 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1307 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
1308 return cast<T>(N.release()->replaceWithPermanentImpl());
1309 }
1310
1311 /// Replace a temporary node with a uniqued one.
1312 ///
1313 /// Create a uniqued version of \c N -- in place, if possible -- and return
1314 /// it. Takes ownership of the temporary node.
1315 ///
1316 /// \pre N does not self-reference.
1317 template <class T>
1318 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1319 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
1320 return cast<T>(N.release()->replaceWithUniquedImpl());
1321 }
1322
1323 /// Replace a temporary node with a distinct one.
1324 ///
1325 /// Create a distinct version of \c N -- in place, if possible -- and return
1326 /// it. Takes ownership of the temporary node.
1327 template <class T>
1328 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1329 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
1330 return cast<T>(N.release()->replaceWithDistinctImpl());
1331 }
1332
1333 /// Print in tree shape.
1334 ///
1335 /// Prints definition of \c this in tree shape.
1336 ///
1337 /// If \c M is provided, metadata nodes will be numbered canonically;
1338 /// otherwise, pointer addresses are substituted.
1339 /// @{
1340 LLVM_ABI void printTree(raw_ostream &OS, const Module *M = nullptr) const;
1342 const Module *M = nullptr) const;
1343 /// @}
1344
1345 /// User-friendly dump in tree shape.
1346 ///
1347 /// If \c M is provided, metadata nodes will be numbered canonically;
1348 /// otherwise, pointer addresses are substituted.
1349 ///
1350 /// Note: this uses an explicit overload instead of default arguments so that
1351 /// the nullptr version is easy to call from a debugger.
1352 ///
1353 /// @{
1354 LLVM_ABI void dumpTree() const;
1355 LLVM_ABI void dumpTree(const Module *M) const;
1356 /// @}
1357
1358private:
1359 LLVM_ABI MDNode *replaceWithPermanentImpl();
1360 LLVM_ABI MDNode *replaceWithUniquedImpl();
1361 LLVM_ABI MDNode *replaceWithDistinctImpl();
1362
1363protected:
1364 /// Set an operand.
1365 ///
1366 /// Sets the operand directly, without worrying about uniquing.
1367 LLVM_ABI void setOperand(unsigned I, Metadata *New);
1368
1369 unsigned getNumUnresolved() const { return getHeader().NumUnresolved; }
1370
1371 void setNumUnresolved(unsigned N) { getHeader().NumUnresolved = N; }
1373 template <class T, class StoreT>
1374 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1375 template <class T> static T *storeImpl(T *N, StorageType Storage);
1376
1377 /// Resize the node to hold \a NumOps operands.
1378 ///
1379 /// \pre \a isTemporary() or \a isDistinct()
1380 /// \pre MetadataID == MDTupleKind
1381 void resize(size_t NumOps) {
1382 assert(!isUniqued() && "Resizing is not supported for uniqued nodes");
1383 assert(getMetadataID() == MDTupleKind &&
1384 "Resizing is not supported for this node kind");
1385 getHeader().resize(NumOps);
1386 }
1387
1388private:
1389 void handleChangedOperand(void *Ref, Metadata *New);
1390
1391 /// Drop RAUW support, if any.
1392 void dropReplaceableUses();
1393
1394 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1395 void decrementUnresolvedOperandCount();
1396 void countUnresolvedOperands();
1397
1398 /// Mutate this to be "uniqued".
1399 ///
1400 /// Mutate this so that \a isUniqued().
1401 /// \pre \a isTemporary().
1402 /// \pre already added to uniquing set.
1403 void makeUniqued();
1404
1405 /// Mutate this to be "distinct".
1406 ///
1407 /// Mutate this so that \a isDistinct().
1408 /// \pre \a isTemporary().
1409 void makeDistinct();
1410
1411 void deleteAsSubclass();
1412 MDNode *uniquify();
1413 void eraseFromStore();
1414
1415 template <class NodeTy> struct HasCachedHash;
1416 template <class NodeTy> static void dispatchRecalculateHash(NodeTy *N) {
1417 if constexpr (HasCachedHash<NodeTy>::value)
1418 N->recalculateHash();
1419 }
1420 template <class NodeTy> static void dispatchResetHash(NodeTy *N) {
1421 if constexpr (HasCachedHash<NodeTy>::value)
1422 N->setHash(0);
1423 }
1424
1425 /// Merge branch weights from two direct callsites.
1426 static MDNode *mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1427 const Instruction *AInstr,
1428 const Instruction *BInstr);
1429
1430public:
1431 using op_iterator = const MDOperand *;
1433
1435 return const_cast<MDNode *>(this)->mutable_begin();
1436 }
1437
1439 return const_cast<MDNode *>(this)->mutable_end();
1440 }
1441
1442 ArrayRef<MDOperand> operands() const { return getHeader().operands(); }
1443
1444 const MDOperand &getOperand(unsigned I) const {
1445 assert(I < getNumOperands() && "Out of range");
1446 return getHeader().operands()[I];
1447 }
1448
1449 /// Return number of MDNode operands.
1450 unsigned getNumOperands() const { return getHeader().getNumOperands(); }
1451
1452 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1453 static bool classof(const Metadata *MD) {
1454 switch (MD->getMetadataID()) {
1455 default:
1456 return false;
1457#define HANDLE_MDNODE_LEAF(CLASS) \
1458 case CLASS##Kind: \
1459 return true;
1460#include "llvm/IR/Metadata.def"
1461 }
1462 }
1463
1464 /// Check whether MDNode is a vtable access.
1465 LLVM_ABI bool isTBAAVtableAccess() const;
1466
1467 /// Methods for metadata merging.
1469 LLVM_ABI static MDNode *intersect(MDNode *A, MDNode *B);
1476 MDNode *B);
1478 /// Merge !prof metadata from two instructions.
1479 /// Currently only implemented with direct callsites with branch weights.
1481 const Instruction *AInstr,
1482 const Instruction *BInstr);
1486 const MDNode *B);
1487
1488 /// Convert !captures metadata to CaptureComponents. MD may be nullptr.
1490 /// Convert CaptureComponents to !captures metadata. The return value may be
1491 /// nullptr.
1494};
1495
1496/// Tuple of metadata.
1497///
1498/// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1499/// default based on their operands.
1500class MDTuple : public MDNode {
1501 friend class LLVMContextImpl;
1502 friend class MDNode;
1503
1504 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1506 : MDNode(C, MDTupleKind, Storage, Vals) {
1507 setHash(Hash);
1508 }
1509
1511
1512 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1513 void recalculateHash();
1514
1515 LLVM_ABI static MDTuple *getImpl(LLVMContext &Context,
1518 bool ShouldCreate = true);
1519
1520 TempMDTuple cloneImpl() const {
1521 ArrayRef<MDOperand> Operands = operands();
1523 }
1524
1525public:
1526 /// Get the hash, if any.
1527 unsigned getHash() const { return SubclassData32; }
1528
1529 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1530 return getImpl(Context, MDs, Uniqued);
1531 }
1532
1533 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1534 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1535 }
1536
1537 /// Return a distinct node.
1538 ///
1539 /// Return a distinct node -- i.e., a node that is not uniqued.
1540 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1541 return getImpl(Context, MDs, Distinct);
1542 }
1543
1544 /// Return a temporary node.
1545 ///
1546 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1547 /// not uniqued, may be RAUW'd, and must be manually deleted with
1548 /// deleteTemporary.
1549 static TempMDTuple getTemporary(LLVMContext &Context,
1551 return TempMDTuple(getImpl(Context, MDs, Temporary));
1552 }
1553
1554 /// Return a (temporary) clone of this.
1555 TempMDTuple clone() const { return cloneImpl(); }
1556
1557 /// Append an element to the tuple. This will resize the node.
1559 size_t NumOps = getNumOperands();
1560 resize(NumOps + 1);
1561 setOperand(NumOps, MD);
1562 }
1563
1564 /// Shrink the operands by 1.
1565 void pop_back() { resize(getNumOperands() - 1); }
1566
1567 static bool classof(const Metadata *MD) {
1568 return MD->getMetadataID() == MDTupleKind;
1569 }
1570};
1571
1573 return MDTuple::get(Context, MDs);
1574}
1575
1577 return MDTuple::getIfExists(Context, MDs);
1578}
1579
1581 return MDTuple::getDistinct(Context, MDs);
1582}
1583
1586 return MDTuple::getTemporary(Context, MDs);
1587}
1588
1592
1593/// This is a simple wrapper around an MDNode which provides a higher-level
1594/// interface by hiding the details of how alias analysis information is encoded
1595/// in its operands.
1597 const MDNode *Node = nullptr;
1598
1599public:
1600 AliasScopeNode() = default;
1601 explicit AliasScopeNode(const MDNode *N) : Node(N) {}
1602
1603 /// Get the MDNode for this AliasScopeNode.
1604 const MDNode *getNode() const { return Node; }
1605
1606 /// Get the MDNode for this AliasScopeNode's domain.
1607 const MDNode *getDomain() const {
1608 if (Node->getNumOperands() < 2)
1609 return nullptr;
1610 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
1611 }
1613 if (Node->getNumOperands() > 2)
1614 if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
1615 return N->getString();
1616 return StringRef();
1617 }
1618};
1619
1620/// Typed iterator through MDNode operands.
1621///
1622/// An iterator that transforms an \a MDNode::iterator into an iterator over a
1623/// particular Metadata subclass.
1624template <class T> class TypedMDOperandIterator {
1625 MDNode::op_iterator I = nullptr;
1626
1627public:
1628 using iterator_category = std::input_iterator_tag;
1629 using value_type = T *;
1630 using difference_type = std::ptrdiff_t;
1631 using pointer = void;
1632 using reference = T *;
1633
1636
1637 T *operator*() const { return cast_or_null<T>(*I); }
1638
1640 ++I;
1641 return *this;
1642 }
1643
1645 TypedMDOperandIterator Temp(*this);
1646 ++I;
1647 return Temp;
1648 }
1649
1650 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1651 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1652};
1653
1654/// Typed, array-like tuple of metadata.
1655///
1656/// This is a wrapper for \a MDTuple that makes it act like an array holding a
1657/// particular type of metadata.
1658template <class T> class MDTupleTypedArrayWrapper {
1659 const MDTuple *N = nullptr;
1660
1661public:
1664
1665 template <class U>
1668 std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
1669 : N(Other.get()) {}
1670
1671 template <class U>
1674 std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
1675 : N(Other.get()) {}
1676
1677 explicit operator bool() const { return get(); }
1678 explicit operator MDTuple *() const { return get(); }
1679
1680 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1681 MDTuple *operator->() const { return get(); }
1682 MDTuple &operator*() const { return *get(); }
1683
1684 // FIXME: Fix callers and remove condition on N.
1685 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1686 bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1687 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1688
1689 // FIXME: Fix callers and remove condition on N.
1691
1692 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1693 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1694};
1695
1696#define HANDLE_METADATA(CLASS) \
1697 using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1698#include "llvm/IR/Metadata.def"
1699
1700/// Placeholder metadata for operands of distinct MDNodes.
1701///
1702/// This is a lightweight placeholder for an operand of a distinct node. It's
1703/// purpose is to help track forward references when creating a distinct node.
1704/// This allows distinct nodes involved in a cycle to be constructed before
1705/// their operands without requiring a heavyweight temporary node with
1706/// full-blown RAUW support.
1707///
1708/// Each placeholder supports only a single MDNode user. Clients should pass
1709/// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1710/// should be replaced with.
1711///
1712/// While it would be possible to implement move operators, they would be
1713/// fairly expensive. Leave them unimplemented to discourage their use
1714/// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1716 friend class MetadataTracking;
1717
1718 Metadata **Use = nullptr;
1719
1720public:
1722 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1724 }
1725
1729
1731 if (Use)
1732 *Use = nullptr;
1733 }
1734
1735 unsigned getID() const { return SubclassData32; }
1736
1737 /// Replace the use of this with MD.
1739 if (!Use)
1740 return;
1741 *Use = MD;
1742
1743 if (*Use)
1745
1746 Metadata *T = cast<Metadata>(this);
1748 assert(!Use && "Use is still being tracked despite being untracked!");
1749 }
1750};
1751
1752//===----------------------------------------------------------------------===//
1753/// A tuple of MDNodes.
1754///
1755/// Despite its name, a NamedMDNode isn't itself an MDNode.
1756///
1757/// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1758///
1759/// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1760class NamedMDNode : public ilist_node<NamedMDNode> {
1761 friend class LLVMContextImpl;
1762 friend class Module;
1763
1764 std::string Name;
1765 Module *Parent = nullptr;
1766 void *Operands; // SmallVector<TrackingMDRef, 4>
1767
1768 void setParent(Module *M) { Parent = M; }
1769
1770 explicit NamedMDNode(const Twine &N);
1771
1772 template <class T1> class op_iterator_impl {
1773 friend class NamedMDNode;
1774
1775 const NamedMDNode *Node = nullptr;
1776 unsigned Idx = 0;
1777
1778 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1779
1780 public:
1781 using iterator_category = std::bidirectional_iterator_tag;
1782 using value_type = T1;
1783 using difference_type = std::ptrdiff_t;
1784 using pointer = value_type *;
1785 using reference = value_type;
1786
1787 op_iterator_impl() = default;
1788
1789 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1790 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
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 op_iterator_impl &operator--() {
1804 --Idx;
1805 return *this;
1806 }
1807
1808 op_iterator_impl operator--(int) {
1809 op_iterator_impl tmp(*this);
1810 operator--();
1811 return tmp;
1812 }
1813
1814 T1 operator*() const { return Node->getOperand(Idx); }
1815 };
1816
1817public:
1818 NamedMDNode(const NamedMDNode &) = delete;
1820
1821 /// Drop all references and remove the node from parent module.
1823
1824 /// Remove all uses and clear node vector.
1826 /// Drop all references to this node's operands.
1827 LLVM_ABI void clearOperands();
1828
1829 /// Get the module that holds this named metadata collection.
1830 inline Module *getParent() { return Parent; }
1831 inline const Module *getParent() const { return Parent; }
1832
1833 LLVM_ABI MDNode *getOperand(unsigned i) const;
1834 LLVM_ABI unsigned getNumOperands() const;
1835 LLVM_ABI void addOperand(MDNode *M);
1836 LLVM_ABI void setOperand(unsigned I, MDNode *New);
1837 LLVM_ABI StringRef getName() const;
1838 LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug = false) const;
1840 bool IsForDebug = false) const;
1841 LLVM_ABI void dump() const;
1842
1843 // ---------------------------------------------------------------------------
1844 // Operand Iterator interface...
1845 //
1846 using op_iterator = op_iterator_impl<MDNode *>;
1847
1848 op_iterator op_begin() { return op_iterator(this, 0); }
1850
1851 using const_op_iterator = op_iterator_impl<const MDNode *>;
1852
1853 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1855
1857 return make_range(op_begin(), op_end());
1858 }
1860 return make_range(op_begin(), op_end());
1861 }
1862};
1863
1864// Create wrappers for C Binding types (see CBindingWrapping.h).
1866
1867} // end namespace llvm
1868
1869#endif // LLVM_IR_METADATA_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
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.
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")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
Value * RHS
Value * LHS
AliasScopeNode()=default
AliasScopeNode(const MDNode *N)
Definition Metadata.h:1601
const MDNode * getNode() const
Get the MDNode for this AliasScopeNode.
Definition Metadata.h:1604
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1607
StringRef getName() const
Definition Metadata.h:1612
ArrayRef - 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:1010
std::unique_ptr< ReplaceableMetadataImpl > takeReplaceableUses()
Drop RAUW support.
Definition Metadata.h:1039
ContextAndReplaceableUses & operator=(ContextAndReplaceableUses &&)=delete
ReplaceableMetadataImpl * getOrCreateReplaceableUses()
Ensure that this has RAUW support, and then return it.
Definition Metadata.h:1017
void makeReplaceable(std::unique_ptr< ReplaceableMetadataImpl > ReplaceableUses)
Assign RAUW support to this.
Definition Metadata.h:1028
ContextAndReplaceableUses(ContextAndReplaceableUses &&)=delete
ContextAndReplaceableUses(const ContextAndReplaceableUses &)=delete
LLVMContext & getContext() const
Definition Metadata.h:1004
bool hasReplaceableUses() const
Whether this contains RAUW support.
Definition Metadata.h:1000
ContextAndReplaceableUses(LLVMContext &Context)
Definition Metadata.h:983
ContextAndReplaceableUses(std::unique_ptr< ReplaceableMetadataImpl > ReplaceableUses)
Definition Metadata.h:984
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:1738
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:1080
friend class DIAssignID
Definition Metadata.h:1083
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:1216
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:1580
mutable_op_range mutable_operands()
Definition Metadata.h:1218
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition Metadata.h:1284
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:1444
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
LLVM_ABI void storeDistinctInContext()
bool isTemporary() const
Definition Metadata.h:1264
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1584
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
op_iterator op_end() const
Definition Metadata.h:1438
bool hasGeneralizedMDString()
Check if this is a valid generalized type metadata node.
Definition Metadata.h:1270
MDNode(const MDNode &)=delete
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
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:1329
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:1453
friend class ReplaceableMetadataImpl
Definition Metadata.h:1081
bool isUniqued() const
Definition Metadata.h:1262
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
void setNumUnresolved(unsigned N)
Definition Metadata.h:1371
void resize(size_t NumOps)
Resize the node to hold NumOps operands.
Definition Metadata.h:1381
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1450
MDOperand * mutable_begin()
Definition Metadata.h:1213
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:1432
friend class LLVMContextImpl
Definition Metadata.h:1082
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:1263
unsigned getNumTemporaryUses() const
Definition Metadata.h:1276
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
bool isReplaceable() const
Definition Metadata.h:1266
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1260
op_iterator op_begin() const
Definition Metadata.h:1434
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:1244
MDOperand * mutable_end()
Definition Metadata.h:1214
~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:1576
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:1307
LLVM_ABI void dropAllReferences()
Definition Metadata.cpp:923
void operator=(const MDNode &)=delete
const MDOperand * op_iterator
Definition Metadata.h:1431
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:1319
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:1369
bool isAlwaysReplaceable() const
Definition Metadata.h:1267
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
MDOperand()=default
bool equalsStr(StringRef Str) const
Definition Metadata.h:924
void reset(Metadata *MD, Metadata *Owner)
Definition Metadata.h:940
Metadata * operator->() const
Definition Metadata.h:933
MDOperand & operator=(const MDOperand &)=delete
Metadata & operator*() const
Definition Metadata.h:934
Metadata * get() const
Definition Metadata.h:931
MDOperand(const MDOperand &)=delete
MDOperand & operator=(MDOperand &&Op)
Definition Metadata.h:915
MDOperand(MDOperand &&Op)
Definition Metadata.h:908
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:1672
MDTupleTypedArrayWrapper(const MDTuple *N)
Definition Metadata.h:1663
T * operator[](unsigned I) const
Definition Metadata.h:1687
MDTuple * operator->() const
Definition Metadata.h:1681
MDTuple & operator*() const
Definition Metadata.h:1682
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t< std::is_convertible< U *, T * >::value > *=nullptr)
Definition Metadata.h:1666
TypedMDOperandIterator< T > iterator
Definition Metadata.h:1690
Tuple of metadata.
Definition Metadata.h:1500
TempMDTuple clone() const
Return a (temporary) clone of this.
Definition Metadata.h:1555
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1540
static bool classof(const Metadata *MD)
Definition Metadata.h:1567
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition Metadata.h:1558
unsigned getHash() const
Get the hash, if any.
Definition Metadata.h:1527
friend class LLVMContextImpl
Definition Metadata.h:1501
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1533
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
friend class MDNode
Definition Metadata.h:1502
void pop_back()
Shrink the operands by 1.
Definition Metadata.h:1565
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:1760
const_op_iterator op_begin() const
Definition Metadata.h:1853
NamedMDNode(const NamedMDNode &)=delete
op_iterator_impl< const MDNode * > const_op_iterator
Definition Metadata.h:1851
friend class Module
Definition Metadata.h:1762
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:1825
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:1854
iterator_range< const_op_iterator > operands() const
Definition Metadata.h:1859
op_iterator op_end()
Definition Metadata.h:1849
LLVM_ABI MDNode * getOperand(unsigned i) const
friend class LLVMContextImpl
Definition Metadata.h:1761
op_iterator op_begin()
Definition Metadata.h:1848
op_iterator_impl< MDNode * > op_iterator
Definition Metadata.h:1846
LLVM_ABI unsigned getNumOperands() const
const Module * getParent() const
Definition Metadata.h:1831
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
iterator_range< op_iterator > operands()
Definition Metadata.h:1856
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1830
LLVM_ABI void addOperand(MDNode *M)
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
const char * iterator
Definition StringRef.h:59
const unsigned char * bytes_end() const
Definition StringRef.h:127
iterator begin() const
Definition StringRef.h:112
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
iterator end() const
Definition StringRef.h:114
const unsigned char * bytes_begin() const
Definition StringRef.h:124
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:45
Typed iterator through MDNode operands.
Definition Metadata.h:1624
TypedMDOperandIterator operator++(int)
Definition Metadata.h:1644
std::ptrdiff_t difference_type
Definition Metadata.h:1630
std::input_iterator_tag iterator_category
Definition Metadata.h:1628
bool operator==(const TypedMDOperandIterator &X) const
Definition Metadata.h:1650
TypedMDOperandIterator & operator++()
Definition Metadata.h:1639
TypedMDOperandIterator(MDNode::op_iterator I)
Definition Metadata.h:1635
bool operator!=(const TypedMDOperandIterator &X) const
Definition Metadata.h:1651
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.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
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
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:310
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:392
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
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 AAMDNodes getEmptyKey()
Definition Metadata.h:872
static unsigned getHashValue(const AAMDNodes &Val)
Definition Metadata.h:882
static AAMDNodes getTombstoneKey()
Definition Metadata.h:877
static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS)
Definition Metadata.h:890
An information struct used to provide DenseMap with the various necessary components for a given valu...
void operator()(MDNode *Node) const
Definition Metadata.h:1589
static SimpleType getSimplifiedValue(MDOperand &MD)
Definition Metadata.h:966
static SimpleType getSimplifiedValue(const MDOperand &MD)
Definition Metadata.h:972
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34