LLVM 24.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 {
65 friend class ReplaceableUses;
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 {
185 friend class ReplaceableUses;
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 // The slot holding the DIAssignID of a dbg_assign record.
229 static constexpr size_t AssignIDIdx = 2;
230
232
233public:
235 LLVM_ABI const DbgVariableRecord *getUser() const;
236 /// To be called by ReplaceableUses::replaceAllUsesWith, where `Old`
237 /// is a pointer to one of the pointers in `DebugValues` (so should be type
238 /// Metadata**), and `NewDebugValue` is the new Metadata* that is replacing
239 /// *Old.
240 /// For manually replacing elements of DebugValues,
241 /// `resetDebugValue(Idx, NewDebugValue)` should be used instead.
242 LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue);
243 DebugValueUser() = default;
244 explicit DebugValueUser(std::array<Metadata *, 3> DebugValues)
246 trackDebugValues();
247 }
249 DebugValues = X.DebugValues;
250 retrackDebugValues(X);
251 }
253 DebugValues = X.DebugValues;
254 trackDebugValues();
255 }
256
258 if (&X == this)
259 return *this;
260
261 untrackDebugValues();
262 DebugValues = X.DebugValues;
263 retrackDebugValues(X);
264 return *this;
265 }
266
268 if (&X == this)
269 return *this;
270
271 untrackDebugValues();
272 DebugValues = X.DebugValues;
273 trackDebugValues();
274 return *this;
275 }
276
277 ~DebugValueUser() { untrackDebugValues(); }
278
280 untrackDebugValues();
281 DebugValues.fill(nullptr);
282 }
283
284 void resetDebugValue(size_t Idx, Metadata *DebugValue) {
285 assert(Idx < 3 && "Invalid debug value index.");
286 untrackDebugValue(Idx);
287 DebugValues[Idx] = DebugValue;
288 trackDebugValue(Idx);
289 }
290
291 bool operator==(const DebugValueUser &X) const {
292 return DebugValues == X.DebugValues;
293 }
294 bool operator!=(const DebugValueUser &X) const {
295 return DebugValues != X.DebugValues;
296 }
297
298private:
299 LLVM_ABI void trackDebugValue(size_t Idx);
300 LLVM_ABI void trackDebugValues();
301
302 LLVM_ABI void untrackDebugValue(size_t Idx);
303 LLVM_ABI void untrackDebugValues();
304
305 LLVM_ABI void retrackDebugValues(DebugValueUser &X);
306};
307
308/// API for tracking metadata references through RAUW and deletion.
309///
310/// Shared API for updating \a Metadata pointers in subclasses that support
311/// RAUW.
312///
313/// This API is not meant to be used directly. See \a TrackingMDRef for a
314/// user-friendly tracking reference.
316public:
317 /// Track the reference to metadata.
318 ///
319 /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
320 /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
321 /// deleted, \c MD will be set to \c nullptr.
322 ///
323 /// If tracking isn't supported, \c *MD will not change.
324 ///
325 /// \return true iff tracking is supported by \c MD.
326 static bool track(Metadata *&MD) {
327 return track(&MD, *MD, static_cast<Metadata *>(nullptr));
328 }
329
330 /// Track the reference to metadata for \a Metadata.
331 ///
332 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
333 /// tell it that its operand changed. This could trigger \c Owner being
334 /// re-uniqued.
335 static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
336 return track(Ref, MD, &Owner);
337 }
338
339 /// Track the reference to metadata for \a MetadataAsValue.
340 ///
341 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
342 /// tell it that its operand changed. This could trigger \c Owner being
343 /// re-uniqued.
344 static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
345 return track(Ref, MD, &Owner);
346 }
347
348 /// Track the reference to metadata for \a DebugValueUser.
349 ///
350 /// As \a track(Metadata*&), but with support for calling back to \c Owner to
351 /// tell it that its operand changed. This could trigger \c Owner being
352 /// re-uniqued.
353 static bool track(void *Ref, Metadata &MD, DebugValueUser &Owner) {
354 return track(Ref, MD, &Owner);
355 }
356
357 /// Stop tracking a reference to metadata.
358 ///
359 /// Stops \c *MD from tracking \c MD.
360 static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
361 LLVM_ABI static void untrack(void *Ref, Metadata &MD);
362
363 /// Move tracking from one reference to another.
364 ///
365 /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
366 /// except that ownership callbacks are maintained.
367 ///
368 /// Note: it is an error if \c *MD does not equal \c New.
369 ///
370 /// \return true iff tracking is supported by \c MD.
371 static bool retrack(Metadata *&MD, Metadata *&New) {
372 return retrack(&MD, *MD, &New);
373 }
374 LLVM_ABI static bool retrack(void *Ref, Metadata &MD, void *New);
375
376 /// Check whether metadata is replaceable.
377 LLVM_ABI static bool isReplaceable(const Metadata &MD);
378
380
381private:
382 /// Track a reference to metadata for an owner.
383 ///
384 /// Generalized version of tracking.
385 LLVM_ABI static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
386};
387
388/// Shared implementation of use-lists for replaceable metadata.
389///
390/// Most metadata cannot be RAUW'ed. This is a shared implementation of
391/// use-lists and associated API for the three that support it (
392/// \a ValueAsMetadata, \a TempMDNode, and \a DIArgList).
394 friend class MetadataTracking;
395
396public:
398
399private:
400 uint64_t NextIndex = 0;
402
403protected:
405 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
406 }
407
408public:
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 ReplaceableUses *getOrCreate(Metadata &MD);
441
442 /// Get RAUW support on MD, if it exists.
443 static ReplaceableUses *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/// Replaceable metadata that remembers its \a LLVMContext, for owners with no
452/// other route to it.
454 LLVMContext &Context;
455
456public:
458 : Context(Context) {}
459
460 LLVMContext &getContext() const { return Context; }
461};
462
463/// Value wrapper in the Metadata hierarchy.
464///
465/// This is a custom value handle that allows other metadata to refer to
466/// classes in the Value hierarchy.
467///
468/// Because of full uniquing support, each value is only wrapped by a single \a
469/// ValueAsMetadata object, so the lookup maps are far more efficient than
470/// those using ValueHandleBase.
472 friend class ReplaceableUses;
473 friend class LLVMContextImpl;
474
475 Value *V;
476
477 /// Drop users without RAUW (during teardown).
478 void dropUsers() {
479 ReplaceableUses::resolveAllUses(/* ResolveUsers */ false);
480 }
481
482protected:
483 ValueAsMetadata(unsigned ID, Value *V) : Metadata(ID, Uniqued), V(V) {
484 assert(V && "Expected valid value");
485 }
486
487 ~ValueAsMetadata() = default;
488
489public:
490 LLVM_ABI static ValueAsMetadata *get(Value *V);
491
495
499
501
505
509
510 Value *getValue() const { return V; }
511 Type *getType() const { return V->getType(); }
512 LLVMContext &getContext() const { return V->getContext(); }
513
520
521 LLVM_ABI static void handleDeletion(Value *V);
522 LLVM_ABI static void handleRAUW(Value *From, Value *To);
523
524protected:
525 /// Handle collisions after \a Value::replaceAllUsesWith().
526 ///
527 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
528 /// \a Value gets RAUW'ed and the target already exists, this is used to
529 /// merge the two metadata nodes.
533
534public:
535 static bool classof(const Metadata *MD) {
536 return MD->getMetadataID() == LocalAsMetadataKind ||
537 MD->getMetadataID() == ConstantAsMetadataKind;
538 }
539};
540
541class ConstantAsMetadata : public ValueAsMetadata {
542 friend class ValueAsMetadata;
543
544 ConstantAsMetadata(Constant *C)
545 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
546
547public:
548 static ConstantAsMetadata *get(Constant *C) {
550 }
551
552 static ConstantAsMetadata *getIfExists(Constant *C) {
554 }
555
559
560 static bool classof(const Metadata *MD) {
561 return MD->getMetadataID() == ConstantAsMetadataKind;
562 }
563};
564
565class LocalAsMetadata : public ValueAsMetadata {
566 friend class ValueAsMetadata;
567
568 LocalAsMetadata(Value *Local)
569 : ValueAsMetadata(LocalAsMetadataKind, Local) {
570 assert(!isa<Constant>(Local) && "Expected local value");
571 }
572
573public:
574 static LocalAsMetadata *get(Value *Local) {
576 }
577
578 static LocalAsMetadata *getIfExists(Value *Local) {
580 }
581
582 static bool classof(const Metadata *MD) {
583 return MD->getMetadataID() == LocalAsMetadataKind;
584 }
585};
586
587/// Transitional API for extracting constants from Metadata.
588///
589/// This namespace contains transitional functions for metadata that points to
590/// \a Constants.
591///
592/// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
593/// operands could refer to any \a Value. There's was a lot of code like this:
594///
595/// \code
596/// MDNode *N = ...;
597/// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
598/// \endcode
599///
600/// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
601/// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
602/// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
603/// cast in the \a Value hierarchy. Besides creating boiler-plate, this
604/// requires subtle control flow changes.
605///
606/// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
607/// so that metadata can refer to numbers without traversing a bridge to the \a
608/// Value hierarchy. In this final state, the code above would look like this:
609///
610/// \code
611/// MDNode *N = ...;
612/// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
613/// \endcode
614///
615/// The API in this namespace supports the transition. \a MDInt doesn't exist
616/// yet, and even once it does, changing each metadata schema to use it is its
617/// own mini-project. In the meantime this API prevents us from introducing
618/// complex and bug-prone control flow that will disappear in the end. In
619/// particular, the above code looks like this:
620///
621/// \code
622/// MDNode *N = ...;
623/// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
624/// \endcode
625///
626/// The full set of provided functions includes:
627///
628/// mdconst::hasa <=> isa
629/// mdconst::extract <=> cast
630/// mdconst::extract_or_null <=> cast_or_null
631/// mdconst::dyn_extract <=> dyn_cast
632/// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
633///
634/// The target of the cast must be a subclass of \a Constant.
635namespace mdconst {
636
637namespace detail {
638template <typename U, typename V>
639using check_has_dereference = decltype(static_cast<V>(*std::declval<U &>()));
640
641template <typename U, typename V>
642static constexpr bool HasDereference =
644
645template <class V, class M> struct IsValidPointer {
646 static const bool value = std::is_base_of<Constant, V>::value &&
648};
649template <class V, class M> struct IsValidReference {
650 static const bool value = std::is_base_of<Constant, V>::value &&
651 std::is_convertible<M, const Metadata &>::value;
652};
653
654} // end namespace detail
655
656/// Check whether Metadata has a Value.
657///
658/// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
659/// type \c X.
660template <class X, class Y>
661inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, bool>
662hasa(Y &&MD) {
663 assert(MD && "Null pointer sent into hasa");
664 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
665 return isa<X>(V->getValue());
666 return false;
667}
668template <class X, class Y>
669inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, bool>
670hasa(Y &MD) {
671 return hasa(&MD);
672}
673
674/// Extract a Value from Metadata.
675///
676/// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
677template <class X, class Y>
678inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
679extract(Y &&MD) {
681}
682template <class X, class Y>
683inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, X *>
684extract(Y &MD) {
685 return extract(&MD);
686}
687
688/// Extract a Value from Metadata, allowing null.
689///
690/// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
691/// from \c MD, allowing \c MD to be null.
692template <class X, class Y>
693inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
695 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
696 return cast<X>(V->getValue());
697 return nullptr;
698}
699
700/// Extract a Value from Metadata, if any.
701///
702/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
703/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
704/// Value it does contain is of the wrong subclass.
705template <class X, class Y>
706inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
708 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
709 return dyn_cast<X>(V->getValue());
710 return nullptr;
711}
712
713/// Extract a Value from Metadata, if any, allowing null.
714///
715/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
716/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
717/// Value it does contain is of the wrong subclass, allowing \c MD to be null.
718template <class X, class Y>
719inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
721 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
722 return dyn_cast<X>(V->getValue());
723 return nullptr;
724}
725
726} // end namespace mdconst
727
728//===----------------------------------------------------------------------===//
729/// A single uniqued string.
730///
731/// These are used to efficiently contain a byte sequence for metadata.
732/// MDString is always unnamed.
733class MDString : public Metadata {
734 friend class StringMapEntryStorage<MDString>;
735
736 StringMapEntry<MDString> *Entry = nullptr;
737
738 MDString() : Metadata(MDStringKind, Uniqued) {}
739
740public:
741 MDString(const MDString &) = delete;
742 MDString &operator=(MDString &&) = delete;
743 MDString &operator=(const MDString &) = delete;
744
745 LLVM_ABI static MDString *get(LLVMContext &Context, StringRef Str);
746 static MDString *get(LLVMContext &Context, const char *Str) {
747 return get(Context, Str ? StringRef(Str) : StringRef());
748 }
749 LLVM_ABI static MDString *getIfExists(LLVMContext &Context, StringRef Str);
750
752
753 unsigned getLength() const { return (unsigned)getString().size(); }
754
756
757 /// Pointer to the first byte of the string.
758 iterator begin() const { return getString().begin(); }
759
760 /// Pointer to one byte past the end of the string.
761 iterator end() const { return getString().end(); }
762
763 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
764 const unsigned char *bytes_end() const { return getString().bytes_end(); }
765
766 /// Methods for support type inquiry through isa, cast, and dyn_cast.
767 static bool classof(const Metadata *MD) {
768 return MD->getMetadataID() == MDStringKind;
769 }
770};
771
772/// A collection of metadata nodes that might be associated with a
773/// memory access used by the alias-analysis infrastructure.
774struct AAMDNodes {
775 explicit AAMDNodes() = default;
776 explicit AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N, MDNode *NAS)
777 : TBAA(T), TBAAStruct(TS), Scope(S), NoAlias(N), NoAliasAddrSpace(NAS) {}
778
779 bool operator==(const AAMDNodes &A) const {
780 return TBAA == A.TBAA && TBAAStruct == A.TBAAStruct && Scope == A.Scope &&
781 NoAlias == A.NoAlias && NoAliasAddrSpace == A.NoAliasAddrSpace;
782 }
783
784 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
785
786 explicit operator bool() const {
787 return TBAA || TBAAStruct || Scope || NoAlias || NoAliasAddrSpace;
788 }
789
790 /// The tag for type-based alias analysis.
791 MDNode *TBAA = nullptr;
792
793 /// The tag for type-based alias analysis (tbaa struct).
794 MDNode *TBAAStruct = nullptr;
795
796 /// The tag for alias scope specification (used with noalias).
797 MDNode *Scope = nullptr;
798
799 /// The tag specifying the noalias scope.
800 MDNode *NoAlias = nullptr;
801
802 /// The tag specifying the noalias address spaces.
804
805 // Shift tbaa Metadata node to start off bytes later
806 LLVM_ABI static MDNode *shiftTBAA(MDNode *M, size_t off);
807
808 // Shift tbaa.struct Metadata node to start off bytes later
809 LLVM_ABI static MDNode *shiftTBAAStruct(MDNode *M, size_t off);
810
811 // Extend tbaa Metadata node to apply to a series of bytes of length len.
812 // A size of -1 denotes an unknown size.
813 LLVM_ABI static MDNode *extendToTBAA(MDNode *TBAA, ssize_t len);
814
815 /// Given two sets of AAMDNodes that apply to the same pointer,
816 /// give the best AAMDNodes that are compatible with both (i.e. a set of
817 /// nodes whose allowable aliasing conclusions are a subset of those
818 /// allowable by both of the inputs). However, for efficiency
819 /// reasons, do not create any new MDNodes.
821 AAMDNodes Result;
822 Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
823 Result.TBAAStruct = Other.TBAAStruct == TBAAStruct ? TBAAStruct : nullptr;
824 Result.Scope = Other.Scope == Scope ? Scope : nullptr;
825 Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
826 Result.NoAliasAddrSpace =
827 Other.NoAliasAddrSpace == NoAliasAddrSpace ? NoAliasAddrSpace : nullptr;
828 return Result;
829 }
830
831 /// Create a new AAMDNode that describes this AAMDNode after applying a
832 /// constant offset to the start of the pointer.
833 AAMDNodes shift(size_t Offset) const {
834 AAMDNodes Result;
835 Result.TBAA = TBAA ? shiftTBAA(TBAA, Offset) : nullptr;
836 Result.TBAAStruct =
838 Result.Scope = Scope;
839 Result.NoAlias = NoAlias;
840 Result.NoAliasAddrSpace = NoAliasAddrSpace;
841 return Result;
842 }
843
844 /// Create a new AAMDNode that describes this AAMDNode after extending it to
845 /// apply to a series of bytes of length Len. A size of -1 denotes an unknown
846 /// size.
847 AAMDNodes extendTo(ssize_t Len) const {
848 AAMDNodes Result;
849 Result.TBAA = TBAA ? extendToTBAA(TBAA, Len) : nullptr;
850 // tbaa.struct contains (offset, size, type) triples. Extending the length
851 // of the tbaa.struct doesn't require changing this (though more information
852 // could be provided by adding more triples at subsequent lengths).
853 Result.TBAAStruct = TBAAStruct;
854 Result.Scope = Scope;
855 Result.NoAlias = NoAlias;
856 Result.NoAliasAddrSpace = NoAliasAddrSpace;
857 return Result;
858 }
859
860 /// Given two sets of AAMDNodes applying to potentially different locations,
861 /// determine the best AAMDNodes that apply to both.
862 LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const;
863
864 /// Determine the best AAMDNodes after concatenating two different locations
865 /// together. Different from `merge`, where different locations should
866 /// overlap each other, `concat` puts non-overlapping locations together.
868
869 /// Create a new AAMDNode for accessing \p AccessSize bytes of this AAMDNode.
870 /// If this AAMDNode has !tbaa.struct and \p AccessSize matches the size of
871 /// the field at offset 0, get the TBAA tag describing the accessed field.
872 /// If such an AAMDNode already embeds !tbaa, the existing one is retrieved.
873 /// Finally, !tbaa.struct is zeroed out.
874 LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize);
875 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
876 const DataLayout &DL);
877 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, unsigned AccessSize);
878};
879
880// Specialize DenseMapInfo for AAMDNodes.
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 ReplaceableUsesWithContext.
981
982public:
983 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
985 std::unique_ptr<ReplaceableUsesWithContext> 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())
1020 std::make_unique<ReplaceableUsesWithContext>(getContext()));
1021 return getReplaceableUses();
1022 }
1023
1024 /// Assign RAUW support to this.
1025 ///
1026 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
1027 /// not be null).
1028 void
1029 makeReplaceable(std::unique_ptr<ReplaceableUsesWithContext> ReplaceableUses) {
1030 assert(ReplaceableUses && "Expected non-null replaceable uses");
1031 assert(&ReplaceableUses->getContext() == &getContext() &&
1032 "Expected same context");
1033 delete getReplaceableUses();
1034 Ptr = ReplaceableUses.release();
1035 }
1036
1037 /// Drop RAUW support.
1038 ///
1039 /// Cede ownership of RAUW support, returning it.
1040 std::unique_ptr<ReplaceableUsesWithContext> takeReplaceableUses() {
1041 assert(hasReplaceableUses() && "Expected to own replaceable uses");
1042 std::unique_ptr<ReplaceableUsesWithContext> ReplaceableUses(
1044 Ptr = &ReplaceableUses->getContext();
1045 return ReplaceableUses;
1046 }
1047};
1048
1050 inline void operator()(MDNode *Node) const;
1051};
1052
1053#define HANDLE_MDNODE_LEAF(CLASS) \
1054 using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
1055#define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
1056#include "llvm/IR/Metadata.def"
1057
1058/// Metadata node.
1059///
1060/// Metadata nodes can be uniqued, like constants, or distinct. Temporary
1061/// metadata nodes (with full support for RAUW) can be used to delay uniquing
1062/// until forward references are known. The basic metadata node is an \a
1063/// MDTuple.
1064///
1065/// There is limited support for RAUW at construction time. At construction
1066/// time, if any operand is a temporary node (or an unresolved uniqued node,
1067/// which indicates a transitive temporary operand), the node itself will be
1068/// unresolved. As soon as all operands become resolved, it will drop RAUW
1069/// support permanently.
1070///
1071/// If an unresolved node is part of a cycle, \a resolveCycles() needs
1072/// to be called on some member of the cycle once all temporary nodes have been
1073/// replaced.
1074///
1075/// MDNodes can be large or small, as well as resizable or non-resizable.
1076/// Large MDNodes' operands are allocated in a separate storage vector,
1077/// whereas small MDNodes' operands are co-allocated. Distinct and temporary
1078/// MDnodes are resizable, but only MDTuples support this capability.
1079///
1080/// Clients can add operands to resizable MDNodes using push_back().
1081class MDNode : public Metadata {
1082 friend class ReplaceableUses;
1083 friend class LLVMContextImpl;
1084 friend class DIAssignID;
1085
1086 /// The header that is coallocated with an MDNode along with its "small"
1087 /// operands. It is located immediately before the main body of the node.
1088 /// The operands are in turn located immediately before the header.
1089 /// For resizable MDNodes, the space for the storage vector is also allocated
1090 /// immediately before the header, overlapping with the operands.
1091 /// Explicity set alignment because bitfields by default have an
1092 /// alignment of 1 on z/OS.
1093 struct alignas(alignof(size_t)) Header {
1094 uint32_t IsResizable : 1;
1095 uint32_t IsLarge : 1;
1096 uint32_t SmallSize : 4;
1097 uint32_t SmallNumOps : 4;
1098 uint32_t MetadataPrintID;
1099
1100 unsigned NumUnresolved = 0;
1101 using LargeStorageVector = SmallVector<MDOperand, 0>;
1102
1103 static constexpr size_t NumOpsFitInVector =
1104 sizeof(LargeStorageVector) / sizeof(MDOperand);
1105 static_assert(
1106 NumOpsFitInVector * sizeof(MDOperand) == sizeof(LargeStorageVector),
1107 "sizeof(LargeStorageVector) must be a multiple of sizeof(MDOperand)");
1108
1109 static constexpr size_t MaxSmallSize = 15;
1110
1111 static constexpr size_t getOpSize(unsigned NumOps) {
1112 return sizeof(MDOperand) * NumOps;
1113 }
1114 /// Returns the number of operands the node has space for based on its
1115 /// allocation characteristics.
1116 static size_t getSmallSize(size_t NumOps, bool IsResizable, bool IsLarge) {
1117 return IsLarge ? NumOpsFitInVector
1118 : std::max(NumOps, NumOpsFitInVector * IsResizable);
1119 }
1120 /// Returns the number of bytes allocated for operands and header.
1121 static size_t getAllocSize(StorageType Storage, size_t NumOps) {
1122 return getOpSize(
1123 getSmallSize(NumOps, isResizable(Storage), isLarge(NumOps))) +
1124 sizeof(Header);
1125 }
1126
1127 /// Only temporary and distinct nodes are resizable.
1128 static bool isResizable(StorageType Storage) { return Storage != Uniqued; }
1129 static bool isLarge(size_t NumOps) { return NumOps > MaxSmallSize; }
1130
1131 size_t getAllocSize() const {
1132 return getOpSize(SmallSize) + sizeof(Header);
1133 }
1134 void *getAllocation() {
1135 return reinterpret_cast<char *>(this + 1) -
1136 alignTo(getAllocSize(), alignof(uint64_t));
1137 }
1138
1139 void *getLargePtr() const {
1140 static_assert(alignof(LargeStorageVector) <= alignof(Header),
1141 "LargeStorageVector too strongly aligned");
1142 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
1143 sizeof(LargeStorageVector);
1144 }
1145
1146 LLVM_ABI void *getSmallPtr();
1147
1148 LargeStorageVector &getLarge() {
1149 assert(IsLarge);
1150 return *reinterpret_cast<LargeStorageVector *>(getLargePtr());
1151 }
1152
1153 const LargeStorageVector &getLarge() const {
1154 assert(IsLarge);
1155 return *reinterpret_cast<const LargeStorageVector *>(getLargePtr());
1156 }
1157
1158 LLVM_ABI void resizeSmall(size_t NumOps);
1159 LLVM_ABI void resizeSmallToLarge(size_t NumOps);
1160 LLVM_ABI void resize(size_t NumOps);
1161
1162 LLVM_ABI explicit Header(size_t NumOps, StorageType Storage);
1163 LLVM_ABI ~Header();
1164
1166 if (IsLarge)
1167 return getLarge();
1168 return MutableArrayRef(
1169 reinterpret_cast<MDOperand *>(this) - SmallSize, SmallNumOps);
1170 }
1171
1173 if (IsLarge)
1174 return getLarge();
1175 return ArrayRef(reinterpret_cast<const MDOperand *>(this) - SmallSize,
1176 SmallNumOps);
1177 }
1178
1179 unsigned getNumOperands() const {
1180 if (!IsLarge)
1181 return SmallNumOps;
1182 return getLarge().size();
1183 }
1184 };
1185
1186 Header &getHeader() { return *(reinterpret_cast<Header *>(this) - 1); }
1187
1188 const Header &getHeader() const {
1189 return *(reinterpret_cast<const Header *>(this) - 1);
1190 }
1191
1192 ContextAndReplaceableUses Context;
1193
1194protected:
1195 LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
1197 ~MDNode() = default;
1198
1199 LLVM_ABI void *operator new(size_t Size, size_t NumOps, StorageType Storage);
1200 LLVM_ABI void operator delete(void *Mem);
1201
1202 /// Required by std, but never called.
1203 void operator delete(void *, unsigned) {
1204 llvm_unreachable("Constructor throws?");
1205 }
1206
1207 /// Required by std, but never called.
1208 void operator delete(void *, unsigned, bool) {
1209 llvm_unreachable("Constructor throws?");
1210 }
1211
1213
1214 MDOperand *mutable_begin() { return getHeader().operands().begin(); }
1215 MDOperand *mutable_end() { return getHeader().operands().end(); }
1216
1218
1222
1223public:
1224 MDNode(const MDNode &) = delete;
1225 void operator=(const MDNode &) = delete;
1226 void *operator new(size_t) = delete;
1227
1228 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
1229 static inline MDTuple *getIfExists(LLVMContext &Context,
1231 static inline MDTuple *getDistinct(LLVMContext &Context,
1233 static inline TempMDTuple getTemporary(LLVMContext &Context,
1235
1236 /// Create a (temporary) clone of this.
1237 LLVM_ABI TempMDNode clone() const;
1238
1239 /// Deallocate a node created by getTemporary.
1240 ///
1241 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
1242 /// references will be reset.
1243 LLVM_ABI static void deleteTemporary(MDNode *N);
1244
1245 LLVMContext &getContext() const { return Context.getContext(); }
1246
1247 /// Replace a specific operand.
1248 LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New);
1249
1250 /// Check if node is fully resolved.
1251 ///
1252 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
1253 /// this always returns \c true.
1254 ///
1255 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
1256 /// support (because all operands are resolved).
1257 ///
1258 /// As forward declarations are resolved, their containers should get
1259 /// resolved automatically. However, if this (or one of its operands) is
1260 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
1261 bool isResolved() const { return !isTemporary() && !getNumUnresolved(); }
1262
1263 bool isUniqued() const { return Storage == Uniqued; }
1264 bool isDistinct() const { return Storage == Distinct; }
1265 bool isTemporary() const { return Storage == Temporary; }
1266
1267 bool isReplaceable() const { return isTemporary(); }
1268
1269 unsigned getNumTemporaryUses() const {
1270 assert(isTemporary() && "Only for temporaries");
1271 return Context.getReplaceableUses()->getNumUses();
1272 }
1273
1274 /// RAUW a temporary.
1275 ///
1276 /// \pre \a isTemporary() must be \c true.
1278 assert(isReplaceable() && "Expected temporary/replaceable node");
1279 if (Context.hasReplaceableUses())
1280 Context.getReplaceableUses()->replaceAllUsesWith(MD);
1281 }
1282
1283 /// Resolve cycles.
1284 ///
1285 /// Once all forward declarations have been resolved, force cycles to be
1286 /// resolved.
1287 ///
1288 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
1289 LLVM_ABI void resolveCycles();
1290
1291 /// Resolve a unique, unresolved node.
1292 LLVM_ABI void resolve();
1293
1294 /// Replace a temporary node with a permanent one.
1295 ///
1296 /// Try to create a uniqued version of \c N -- in place, if possible -- and
1297 /// return it. If \c N cannot be uniqued, return a distinct node instead.
1298 template <class T>
1299 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1300 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
1301 return cast<T>(N.release()->replaceWithPermanentImpl());
1302 }
1303
1304 /// Replace a temporary node with a uniqued one.
1305 ///
1306 /// Create a uniqued version of \c N -- in place, if possible -- and return
1307 /// it. Takes ownership of the temporary node.
1308 ///
1309 /// \pre N does not self-reference.
1310 template <class T>
1311 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1312 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
1313 return cast<T>(N.release()->replaceWithUniquedImpl());
1314 }
1315
1316 /// Replace a temporary node with a distinct one.
1317 ///
1318 /// Create a distinct version of \c N -- in place, if possible -- and return
1319 /// it. Takes ownership of the temporary node.
1320 template <class T>
1321 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1322 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
1323 return cast<T>(N.release()->replaceWithDistinctImpl());
1324 }
1325
1326 /// Print in tree shape.
1327 ///
1328 /// Prints definition of \c this in tree shape.
1329 ///
1330 /// If \c M is provided, metadata nodes will be numbered canonically;
1331 /// otherwise, pointer addresses are substituted.
1332 /// @{
1333 LLVM_ABI void printTree(raw_ostream &OS, const Module *M = nullptr) const;
1335 const Module *M = nullptr) const;
1336 /// @}
1337
1338 /// User-friendly dump in tree shape.
1339 ///
1340 /// If \c M is provided, metadata nodes will be numbered canonically;
1341 /// otherwise, pointer addresses are substituted.
1342 ///
1343 /// Note: this uses an explicit overload instead of default arguments so that
1344 /// the nullptr version is easy to call from a debugger.
1345 ///
1346 /// @{
1347 LLVM_ABI void dumpTree() const;
1348 LLVM_ABI void dumpTree(const Module *M) const;
1349 /// @}
1350
1351private:
1352 LLVM_ABI MDNode *replaceWithPermanentImpl();
1353 LLVM_ABI MDNode *replaceWithUniquedImpl();
1354 LLVM_ABI MDNode *replaceWithDistinctImpl();
1355
1356protected:
1357 /// Set an operand.
1358 ///
1359 /// Sets the operand directly, without worrying about uniquing.
1360 LLVM_ABI void setOperand(unsigned I, Metadata *New);
1361
1362 unsigned getNumUnresolved() const { return getHeader().NumUnresolved; }
1363
1364 void setNumUnresolved(unsigned N) { getHeader().NumUnresolved = N; }
1366 template <class T, class StoreT>
1367 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1368 template <class T> static T *storeImpl(T *N, StorageType Storage);
1369
1370 /// Resize the node to hold \a NumOps operands.
1371 ///
1372 /// \pre \a isTemporary() or \a isDistinct()
1373 /// \pre MetadataID == MDTupleKind
1374 void resize(size_t NumOps) {
1375 assert(!isUniqued() && "Resizing is not supported for uniqued nodes");
1376 assert(getMetadataID() == MDTupleKind &&
1377 "Resizing is not supported for this node kind");
1378 getHeader().resize(NumOps);
1379 }
1380
1381private:
1382 void handleChangedOperand(void *Ref, Metadata *New);
1383
1384 /// Drop RAUW support, if any.
1385 void dropReplaceableUses();
1386
1387 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1388 void decrementUnresolvedOperandCount();
1389 void countUnresolvedOperands();
1390
1391 /// Mutate this to be "uniqued".
1392 ///
1393 /// Mutate this so that \a isUniqued().
1394 /// \pre \a isTemporary().
1395 /// \pre already added to uniquing set.
1396 void makeUniqued();
1397
1398 /// Mutate this to be "distinct".
1399 ///
1400 /// Mutate this so that \a isDistinct().
1401 /// \pre \a isTemporary().
1402 void makeDistinct();
1403
1404 void deleteAsSubclass();
1405 MDNode *uniquify();
1406 void eraseFromStore();
1407
1408 template <class NodeTy> struct HasCachedHash;
1409 template <class NodeTy> static void dispatchRecalculateHash(NodeTy *N) {
1410 if constexpr (HasCachedHash<NodeTy>::value)
1411 N->recalculateHash();
1412 }
1413 template <class NodeTy> static void dispatchResetHash(NodeTy *N) {
1414 if constexpr (HasCachedHash<NodeTy>::value)
1415 N->setHash(0);
1416 }
1417
1418 /// Merge branch weights from two direct callsites.
1419 static MDNode *mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1420 const Instruction *AInstr,
1421 const Instruction *BInstr);
1422
1423public:
1424 using op_iterator = const MDOperand *;
1426
1428 return const_cast<MDNode *>(this)->mutable_begin();
1429 }
1430
1432 return const_cast<MDNode *>(this)->mutable_end();
1433 }
1434
1435 ArrayRef<MDOperand> operands() const { return getHeader().operands(); }
1436
1437 const MDOperand &getOperand(unsigned I) const {
1438 assert(I < getNumOperands() && "Out of range");
1439 return getHeader().operands()[I];
1440 }
1441
1442 /// Return number of MDNode operands.
1443 unsigned getNumOperands() const { return getHeader().getNumOperands(); }
1444
1445 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1446 static bool classof(const Metadata *MD) {
1447 switch (MD->getMetadataID()) {
1448 default:
1449 return false;
1450#define HANDLE_MDNODE_LEAF(CLASS) \
1451 case CLASS##Kind: \
1452 return true;
1453#include "llvm/IR/Metadata.def"
1454 }
1455 }
1456
1457 /// Check whether MDNode is a vtable access.
1458 LLVM_ABI bool isTBAAVtableAccess() const;
1459
1460 /// Methods for metadata merging.
1462 LLVM_ABI static MDNode *intersect(MDNode *A, MDNode *B);
1469 MDNode *B);
1471 /// Merge !prof metadata from two instructions.
1472 /// Currently only implemented with direct callsites with branch weights.
1474 const Instruction *AInstr,
1475 const Instruction *BInstr);
1479 const MDNode *B);
1481 const MDNode *B);
1482
1483 /// Convert !captures metadata to CaptureComponents. MD may be nullptr.
1485 /// Convert CaptureComponents to !captures metadata. The return value may be
1486 /// nullptr.
1489};
1490
1491/// Tuple of metadata.
1492///
1493/// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1494/// default based on their operands.
1495class MDTuple : public MDNode {
1496 friend class LLVMContextImpl;
1497 friend class MDNode;
1498
1499 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1501 : MDNode(C, MDTupleKind, Storage, Vals) {
1502 setHash(Hash);
1503 }
1504
1506
1507 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1508 void recalculateHash();
1509
1510 LLVM_ABI static MDTuple *getImpl(LLVMContext &Context,
1513 bool ShouldCreate = true);
1514
1515 TempMDTuple cloneImpl() const {
1518 }
1519
1520public:
1521 /// Get the hash, if any.
1522 unsigned getHash() const { return SubclassData32; }
1523
1524 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1525 return getImpl(Context, MDs, Uniqued);
1526 }
1527
1528 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1529 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1530 }
1531
1532 /// Return a distinct node.
1533 ///
1534 /// Return a distinct node -- i.e., a node that is not uniqued.
1535 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1536 return getImpl(Context, MDs, Distinct);
1537 }
1538
1539 /// Return a temporary node.
1540 ///
1541 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1542 /// not uniqued, may be RAUW'd, and must be manually deleted with
1543 /// deleteTemporary.
1544 static TempMDTuple getTemporary(LLVMContext &Context,
1546 return TempMDTuple(getImpl(Context, MDs, Temporary));
1547 }
1548
1549 /// Return a (temporary) clone of this.
1550 TempMDTuple clone() const { return cloneImpl(); }
1551
1552 /// Append an element to the tuple. This will resize the node.
1554 size_t NumOps = getNumOperands();
1555 resize(NumOps + 1);
1556 setOperand(NumOps, MD);
1557 }
1558
1559 /// Shrink the operands by 1.
1560 void pop_back() { resize(getNumOperands() - 1); }
1561
1562 /// Filter out tuple elements that do not satisfy predicate.
1563 /// Return this if no elements should be filtered out (without re-uniquing).
1564 template <typename T> MDTuple *filter(T &&Pred) {
1566 // Exit if no nodes should be removed.
1567 if (llvm::all_of(Ops, Pred))
1568 return this;
1569 return get(getContext(),
1571 }
1572
1573 static bool classof(const Metadata *MD) {
1574 return MD->getMetadataID() == MDTupleKind;
1575 }
1576};
1577
1579 return MDTuple::get(Context, MDs);
1580}
1581
1583 return MDTuple::getIfExists(Context, MDs);
1584}
1585
1587 return MDTuple::getDistinct(Context, MDs);
1588}
1589
1592 return MDTuple::getTemporary(Context, MDs);
1593}
1594
1598
1599/// This is a simple wrapper around an MDNode which provides a higher-level
1600/// interface by hiding the details of how alias analysis information is encoded
1601/// in its operands.
1603 const MDNode *Node = nullptr;
1604
1605public:
1606 AliasScopeNode() = default;
1607 explicit AliasScopeNode(const MDNode *N) : Node(N) {}
1608
1609 /// Get the MDNode for this AliasScopeNode.
1610 const MDNode *getNode() const { return Node; }
1611
1612 /// Get the MDNode for this AliasScopeNode's domain.
1613 const MDNode *getDomain() const {
1614 if (Node->getNumOperands() < 2)
1615 return nullptr;
1616 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
1617 }
1619 if (Node->getNumOperands() > 2)
1620 if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
1621 return N->getString();
1622 return StringRef();
1623 }
1624};
1625
1626/// Typed iterator through MDNode operands.
1627///
1628/// An iterator that transforms an \a MDNode::iterator into an iterator over a
1629/// particular Metadata subclass.
1630template <class T> class TypedMDOperandIterator {
1631 MDNode::op_iterator I = nullptr;
1632
1633public:
1634 using iterator_category = std::forward_iterator_tag;
1635 using value_type = T *;
1636 using difference_type = std::ptrdiff_t;
1637 using pointer = void;
1638 using reference = T *;
1639
1642
1643 T *operator*() const { return cast_or_null<T>(*I); }
1644
1646 ++I;
1647 return *this;
1648 }
1649
1651 TypedMDOperandIterator Temp(*this);
1652 ++I;
1653 return Temp;
1654 }
1655
1656 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1657 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1658};
1659
1660/// Typed, array-like tuple of metadata.
1661///
1662/// This is a wrapper for \a MDTuple that makes it act like an array holding a
1663/// particular type of metadata.
1664template <class T> class MDTupleTypedArrayWrapper {
1665 const MDTuple *N = nullptr;
1666
1667public:
1670
1671 template <class U>
1674 std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
1675 : N(Other.get()) {}
1676
1677 template <class U>
1680 std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
1681 : N(Other.get()) {}
1682
1683 explicit operator bool() const { return get(); }
1684 explicit operator MDTuple *() const { return get(); }
1685
1686 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1687 MDTuple *operator->() const { return get(); }
1688 MDTuple &operator*() const { return *get(); }
1689
1690 // FIXME: Fix callers and remove condition on N.
1691 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1692 bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1693 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1694
1695 // FIXME: Fix callers and remove condition on N.
1697
1698 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1699 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1700};
1701
1702#define HANDLE_METADATA(CLASS) \
1703 using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1704#include "llvm/IR/Metadata.def"
1705
1706/// Placeholder metadata for operands of distinct MDNodes.
1707///
1708/// This is a lightweight placeholder for an operand of a distinct node. It's
1709/// purpose is to help track forward references when creating a distinct node.
1710/// This allows distinct nodes involved in a cycle to be constructed before
1711/// their operands without requiring a heavyweight temporary node with
1712/// full-blown RAUW support.
1713///
1714/// Each placeholder supports only a single MDNode user. Clients should pass
1715/// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1716/// should be replaced with.
1717///
1718/// While it would be possible to implement move operators, they would be
1719/// fairly expensive. Leave them unimplemented to discourage their use
1720/// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1722 friend class MetadataTracking;
1723
1724 Metadata **Use = nullptr;
1725
1726public:
1727 explicit DistinctMDOperandPlaceholder(unsigned ID)
1728 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1729 SubclassData32 = ID;
1730 }
1731
1735
1737 if (Use)
1738 *Use = nullptr;
1739 }
1740
1741 unsigned getID() const { return SubclassData32; }
1742
1743 /// Replace the use of this with MD.
1745 if (!Use)
1746 return;
1747 *Use = MD;
1748
1749 if (*Use)
1751
1752 Metadata *T = cast<Metadata>(this);
1754 assert(!Use && "Use is still being tracked despite being untracked!");
1755 }
1756};
1757
1758//===----------------------------------------------------------------------===//
1759/// A tuple of MDNodes.
1760///
1761/// Despite its name, a NamedMDNode isn't itself an MDNode.
1762///
1763/// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1764///
1765/// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1766class NamedMDNode : public ilist_node<NamedMDNode> {
1767 friend class LLVMContextImpl;
1768 friend class Module;
1769
1770 std::string Name;
1771 Module *Parent = nullptr;
1772 void *Operands; // SmallVector<TrackingMDRef, 4>
1773
1774 void setParent(Module *M) { Parent = M; }
1775
1776 explicit NamedMDNode(const Twine &N);
1777
1778 template <class T1> class op_iterator_impl {
1779 friend class NamedMDNode;
1780
1781 const NamedMDNode *Node = nullptr;
1782 unsigned Idx = 0;
1783
1784 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1785
1786 public:
1787 using iterator_category = std::bidirectional_iterator_tag;
1788 using value_type = T1;
1789 using difference_type = std::ptrdiff_t;
1790 using pointer = value_type *;
1791 using reference = value_type;
1792
1793 op_iterator_impl() = default;
1794
1795 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1796 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1797
1798 op_iterator_impl &operator++() {
1799 ++Idx;
1800 return *this;
1801 }
1802
1803 op_iterator_impl operator++(int) {
1804 op_iterator_impl tmp(*this);
1805 operator++();
1806 return tmp;
1807 }
1808
1809 op_iterator_impl &operator--() {
1810 --Idx;
1811 return *this;
1812 }
1813
1814 op_iterator_impl operator--(int) {
1815 op_iterator_impl tmp(*this);
1816 operator--();
1817 return tmp;
1818 }
1819
1820 T1 operator*() const { return Node->getOperand(Idx); }
1821 };
1822
1823public:
1824 NamedMDNode(const NamedMDNode &) = delete;
1826
1827 /// Drop all references and remove the node from parent module.
1829
1830 /// Remove all uses and clear node vector.
1832 /// Drop all references to this node's operands.
1833 LLVM_ABI void clearOperands();
1834
1835 /// Get the module that holds this named metadata collection.
1836 inline Module *getParent() { return Parent; }
1837 inline const Module *getParent() const { return Parent; }
1838
1839 LLVM_ABI MDNode *getOperand(unsigned i) const;
1840 LLVM_ABI unsigned getNumOperands() const;
1841 LLVM_ABI void addOperand(MDNode *M);
1842 LLVM_ABI void setOperand(unsigned I, MDNode *New);
1843 LLVM_ABI StringRef getName() const;
1844 LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug = false) const;
1846 bool IsForDebug = false) const;
1847 LLVM_ABI void dump() const;
1848
1849 // ---------------------------------------------------------------------------
1850 // Operand Iterator interface...
1851 //
1852 using op_iterator = op_iterator_impl<MDNode *>;
1853
1854 op_iterator op_begin() { return op_iterator(this, 0); }
1856
1857 using const_op_iterator = op_iterator_impl<const MDNode *>;
1858
1859 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1861
1863 return make_range(op_begin(), op_end());
1864 }
1866 return make_range(op_begin(), op_end());
1867 }
1868};
1869
1870// Create wrappers for C Binding types (see CBindingWrapping.h).
1872
1873} // end namespace llvm
1874
1875#endif // LLVM_IR_METADATA_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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:215
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
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#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.
SI Fold Operands
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:1607
const MDNode * getNode() const
Get the MDNode for this AliasScopeNode.
Definition Metadata.h:1610
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1613
StringRef getName() const
Definition Metadata.h:1618
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
friend class ValueAsMetadata
Definition Metadata.h:542
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
Constant * getValue() const
Definition Metadata.h:556
static ConstantAsMetadata * getIfExists(Constant *C)
Definition Metadata.h:552
static bool classof(const Metadata *MD)
Definition Metadata.h:560
This is an important base class in LLVM.
Definition Constant.h:43
ContextAndReplaceableUses & operator=(const ContextAndReplaceableUses &)=delete
ReplaceableUsesWithContext * getReplaceableUses() const
Definition Metadata.h:1010
ReplaceableUsesWithContext * getOrCreateReplaceableUses()
Ensure that this has RAUW support, and then return it.
Definition Metadata.h:1017
ContextAndReplaceableUses & operator=(ContextAndReplaceableUses &&)=delete
ContextAndReplaceableUses(ContextAndReplaceableUses &&)=delete
ContextAndReplaceableUses(const ContextAndReplaceableUses &)=delete
LLVMContext & getContext() const
Definition Metadata.h:1004
ContextAndReplaceableUses(std::unique_ptr< ReplaceableUsesWithContext > ReplaceableUses)
Definition Metadata.h:984
std::unique_ptr< ReplaceableUsesWithContext > takeReplaceableUses()
Drop RAUW support.
Definition Metadata.h:1040
bool hasReplaceableUses() const
Whether this contains RAUW support.
Definition Metadata.h:1000
ContextAndReplaceableUses(LLVMContext &Context)
Definition Metadata.h:983
void makeReplaceable(std::unique_ptr< ReplaceableUsesWithContext > ReplaceableUses)
Assign RAUW support to this.
Definition Metadata.h:1029
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:252
DebugValueUser & operator=(DebugValueUser &&X)
Definition Metadata.h:257
DebugValueUser()=default
static constexpr size_t AssignIDIdx
Definition Metadata.h:229
LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue)
To be called by ReplaceableUses::replaceAllUsesWith, where Old is a pointer to one of the pointers in...
Definition Metadata.cpp:162
bool operator!=(const DebugValueUser &X) const
Definition Metadata.h:294
DebugValueUser(std::array< Metadata *, 3 > DebugValues)
Definition Metadata.h:244
bool operator==(const DebugValueUser &X) const
Definition Metadata.h:291
ArrayRef< Metadata * > getDebugValues() const
Definition Metadata.h:231
DebugValueUser & operator=(const DebugValueUser &X)
Definition Metadata.h:267
std::array< Metadata *, 3 > DebugValues
Definition Metadata.h:227
void resetDebugValue(size_t Idx, Metadata *DebugValue)
Definition Metadata.h:284
LLVM_ABI DbgVariableRecord * getUser()
Definition Metadata.cpp:155
DebugValueUser(DebugValueUser &&X)
Definition Metadata.h:248
void replaceUseWith(Metadata *MD)
Replace the use of this with MD.
Definition Metadata.h:1744
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:566
static LocalAsMetadata * getIfExists(Value *Local)
Definition Metadata.h:578
static LocalAsMetadata * get(Value *Local)
Definition Metadata.h:574
static bool classof(const Metadata *MD)
Definition Metadata.h:582
Metadata node.
Definition Metadata.h:1081
friend class DIAssignID
Definition Metadata.h:1084
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:1217
LLVM_ABI void resolveCycles()
Resolve cycles.
Definition Metadata.cpp:847
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:1586
mutable_op_range mutable_operands()
Definition Metadata.h:1219
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition Metadata.h:1277
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:801
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
LLVM_ABI void storeDistinctInContext()
bool isTemporary() const
Definition Metadata.h:1265
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1590
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
op_iterator op_end() const
Definition Metadata.h:1431
MDNode(const MDNode &)=delete
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1578
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:1322
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:1446
bool isUniqued() const
Definition Metadata.h:1263
static LLVM_ABI MDNode * getMergedAllocTokenMetadata(const MDNode *A, const MDNode *B)
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
void setNumUnresolved(unsigned N)
Definition Metadata.h:1364
void resize(size_t NumOps)
Resize the node to hold NumOps operands.
Definition Metadata.h:1374
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
MDOperand * mutable_begin()
Definition Metadata.h:1214
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:651
iterator_range< op_iterator > op_range
Definition Metadata.h:1425
friend class LLVMContextImpl
Definition Metadata.h:1083
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition Metadata.cpp:670
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
bool isDistinct() const
Definition Metadata.h:1264
unsigned getNumTemporaryUses() const
Definition Metadata.h:1269
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
bool isReplaceable() const
Definition Metadata.h:1267
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1261
op_iterator op_begin() const
Definition Metadata.h:1427
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:1245
MDOperand * mutable_end()
Definition Metadata.h:1215
~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:1582
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:1300
LLVM_ABI void dropAllReferences()
Definition Metadata.cpp:913
void operator=(const MDNode &)=delete
friend class ReplaceableUses
Definition Metadata.h:1082
const MDOperand * op_iterator
Definition Metadata.h:1424
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:1312
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:1362
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:733
unsigned getLength() const
Definition Metadata.h:753
const unsigned char * bytes_begin() const
Definition Metadata.h:763
MDString(const MDString &)=delete
static MDString * get(LLVMContext &Context, const char *Str)
Definition Metadata.h:746
MDString & operator=(MDString &&)=delete
static bool classof(const Metadata *MD)
Methods for support type inquiry through isa, cast, and dyn_cast.
Definition Metadata.h:767
const unsigned char * bytes_end() const
Definition Metadata.h:764
iterator begin() const
Pointer to the first byte of the string.
Definition Metadata.h:758
MDString & operator=(const MDString &)=delete
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
static LLVM_ABI MDString * getIfExists(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:607
StringRef::iterator iterator
Definition Metadata.h:755
iterator end() const
Pointer to one byte past the end of the string.
Definition Metadata.h:761
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t<!std::is_convertible< U *, T * >::value > *=nullptr)
Definition Metadata.h:1678
MDTupleTypedArrayWrapper(const MDTuple *N)
Definition Metadata.h:1669
T * operator[](unsigned I) const
Definition Metadata.h:1693
MDTuple * operator->() const
Definition Metadata.h:1687
MDTuple & operator*() const
Definition Metadata.h:1688
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t< std::is_convertible< U *, T * >::value > *=nullptr)
Definition Metadata.h:1672
TypedMDOperandIterator< T > iterator
Definition Metadata.h:1696
Tuple of metadata.
Definition Metadata.h:1495
TempMDTuple clone() const
Return a (temporary) clone of this.
Definition Metadata.h:1550
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1535
static bool classof(const Metadata *MD)
Definition Metadata.h:1573
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition Metadata.h:1553
unsigned getHash() const
Get the hash, if any.
Definition Metadata.h:1522
friend class LLVMContextImpl
Definition Metadata.h:1496
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1524
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1528
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1544
friend class MDNode
Definition Metadata.h:1497
void pop_back()
Shrink the operands by 1.
Definition Metadata.h:1560
MDTuple * filter(T &&Pred)
Filter out tuple elements that do not satisfy predicate.
Definition Metadata.h:1564
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:107
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:115
friend class LLVMContextImpl
Definition Metadata.h:186
LLVM_ABI ~MetadataAsValue()
Definition Metadata.cpp:69
static bool classof(const Value *V)
Definition Metadata.h:204
Metadata * getMetadata() const
Definition Metadata.h:202
friend class ReplaceableUses
Definition Metadata.h:185
API for tracking metadata references through RAUW and deletion.
Definition Metadata.h:315
static LLVM_ABI bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition Metadata.cpp:256
static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner)
Track the reference to metadata for MetadataAsValue.
Definition Metadata.h:344
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition Metadata.h:360
PointerUnion< MetadataAsValue *, Metadata *, DebugValueUser * > OwnerTy
Definition Metadata.h:379
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition Metadata.h:371
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition Metadata.h:326
static bool track(void *Ref, Metadata &MD, Metadata &Owner)
Track the reference to metadata for Metadata.
Definition Metadata.h:335
static bool track(void *Ref, Metadata &MD, DebugValueUser &Owner)
Track the reference to metadata for DebugValueUser.
Definition Metadata.h:353
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
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.
friend class ReplaceableUses
Definition Metadata.h:65
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:68
A tuple of MDNodes.
Definition Metadata.h:1766
const_op_iterator op_begin() const
Definition Metadata.h:1859
NamedMDNode(const NamedMDNode &)=delete
op_iterator_impl< const MDNode * > const_op_iterator
Definition Metadata.h:1857
friend class Module
Definition Metadata.h:1768
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:1831
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:1860
iterator_range< const_op_iterator > operands() const
Definition Metadata.h:1865
op_iterator op_end()
Definition Metadata.h:1855
LLVM_ABI MDNode * getOperand(unsigned i) const
friend class LLVMContextImpl
Definition Metadata.h:1767
op_iterator op_begin()
Definition Metadata.h:1854
op_iterator_impl< MDNode * > op_iterator
Definition Metadata.h:1852
LLVM_ABI unsigned getNumOperands() const
const Module * getParent() const
Definition Metadata.h:1837
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
iterator_range< op_iterator > operands()
Definition Metadata.h:1862
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1836
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...
Replaceable metadata that remembers its LLVMContext, for owners with no other route to it.
Definition Metadata.h:453
ReplaceableUsesWithContext(LLVMContext &Context)
Definition Metadata.h:457
LLVMContext & getContext() const
Definition Metadata.h:460
Shared implementation of use-lists for replaceable metadata.
Definition Metadata.h:393
friend class MetadataTracking
Definition Metadata.h:394
ReplaceableUses & operator=(const ReplaceableUses &)=delete
MetadataTracking::OwnerTy OwnerTy
Definition Metadata.h:397
LLVM_ABI SmallVector< Metadata * > getAllArgListUsers()
Returns the list of all DIArgList users of this.
Definition Metadata.cpp:260
LLVM_ABI SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Returns the list of all DbgVariableRecord users of this.
Definition Metadata.cpp:282
LLVM_ABI void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition Metadata.cpp:430
LLVM_ABI void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition Metadata.cpp:377
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:340
unsigned getNumUses() const
Definition Metadata.h:429
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:1630
TypedMDOperandIterator operator++(int)
Definition Metadata.h:1650
std::ptrdiff_t difference_type
Definition Metadata.h:1636
bool operator==(const TypedMDOperandIterator &X) const
Definition Metadata.h:1656
TypedMDOperandIterator & operator++()
Definition Metadata.h:1645
std::forward_iterator_tag iterator_category
Definition Metadata.h:1634
TypedMDOperandIterator(MDNode::op_iterator I)
Definition Metadata.h:1641
bool operator!=(const TypedMDOperandIterator &X) const
Definition Metadata.h:1657
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:471
Type * getType() const
Definition Metadata.h:511
static LocalAsMetadata * getLocalIfExists(Value *Local)
Definition Metadata.h:506
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition Metadata.h:530
SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Definition Metadata.h:517
LLVMContext & getContext() const
Definition Metadata.h:512
static LLVM_ABI void handleDeletion(Value *V)
Definition Metadata.cpp:538
static LocalAsMetadata * getLocal(Value *Local)
Definition Metadata.h:496
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:514
static ConstantAsMetadata * getConstantIfExists(Value *C)
Definition Metadata.h:502
static ConstantAsMetadata * getConstant(Value *C)
Definition Metadata.h:492
static LLVM_ABI ValueAsMetadata * getIfExists(Value *V)
Definition Metadata.cpp:533
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition Metadata.cpp:557
static bool classof(const Metadata *MD)
Definition Metadata.h:535
friend class LLVMContextImpl
Definition Metadata.h:473
SmallVector< Metadata * > getAllArgListUsers()
Definition Metadata.h:514
ValueAsMetadata(unsigned ID, Value *V)
Definition Metadata.h:483
friend class ReplaceableUses
Definition Metadata.h:472
Value * getValue() const
Definition Metadata.h:510
~ValueAsMetadata()=default
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:54
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.
static constexpr bool HasDereference
Definition Metadata.h:642
decltype(static_cast< V >(*std::declval< U & >())) check_has_dereference
Definition Metadata.h:639
Transitional API for extracting constants from Metadata.
Definition Metadata.h:635
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:720
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
Definition Metadata.h:662
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:694
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Store
The extracted value is stored (ExtractElement only).
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
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
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:400
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
SmallVector< Out, Size > to_vector_of(R &&Range)
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:774
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:784
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:803
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:794
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:797
static LLVM_ABI MDNode * extendToTBAA(MDNode *TBAA, ssize_t len)
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
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:833
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:800
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:820
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:776
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:847
bool operator==(const AAMDNodes &A) const
Definition Metadata.h:779
AAMDNodes()=default
static LLVM_ABI MDNode * shiftTBAA(MDNode *M, size_t off)
static unsigned getHashValue(const AAMDNodes &Val)
Definition Metadata.h:882
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:1595
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