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
230
231public:
233 LLVM_ABI const DbgVariableRecord *getUser() const;
234 /// To be called by ReplaceableUses::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 uint64_t NextIndex = 0;
400
401protected:
403 assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
404 }
405
406public:
408
409 /// Replace all uses of this with MD.
410 ///
411 /// Replace all uses of this with \c MD, which is allowed to be null.
413 /// Replace all uses of the constant with Undef in debug info metadata
414 LLVM_ABI static void SalvageDebugInfo(const Constant &C);
415 /// Returns the list of all DIArgList users of this.
417 /// Returns the list of all DbgVariableRecord users of this.
419
420 /// Resolve all uses of this.
421 ///
422 /// Resolve all uses of this, turning off RAUW permanently. If \c
423 /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
424 /// is resolved.
425 LLVM_ABI void resolveAllUses(bool ResolveUsers = true);
426
427 unsigned getNumUses() const { return UseMap.size(); }
428
429private:
430 void addRef(void *Ref, OwnerTy Owner);
431 void dropRef(void *Ref);
432 void moveRef(void *Ref, void *New, const Metadata &MD);
433
434 /// Lazily construct RAUW support on MD.
435 ///
436 /// If this is an unresolved MDNode, RAUW support will be created on-demand.
437 /// ValueAsMetadata always has RAUW support.
438 static ReplaceableUses *getOrCreate(Metadata &MD);
439
440 /// Get RAUW support on MD, if it exists.
441 static ReplaceableUses *getIfExists(Metadata &MD);
442
443 /// Check whether this node will support RAUW.
444 ///
445 /// Returns \c true unless getOrCreate() would return null.
446 static bool isReplaceable(const Metadata &MD);
447};
448
449/// Replaceable metadata that remembers its \a LLVMContext, for owners with no
450/// other route to it.
452 LLVMContext &Context;
453
454public:
456 : Context(Context) {}
457
458 LLVMContext &getContext() const { return Context; }
459};
460
461/// Value wrapper in the Metadata hierarchy.
462///
463/// This is a custom value handle that allows other metadata to refer to
464/// classes in the Value hierarchy.
465///
466/// Because of full uniquing support, each value is only wrapped by a single \a
467/// ValueAsMetadata object, so the lookup maps are far more efficient than
468/// those using ValueHandleBase.
470 friend class ReplaceableUses;
471 friend class LLVMContextImpl;
472
473 Value *V;
474
475 /// Drop users without RAUW (during teardown).
476 void dropUsers() {
477 ReplaceableUses::resolveAllUses(/* ResolveUsers */ false);
478 }
479
480protected:
481 ValueAsMetadata(unsigned ID, Value *V) : Metadata(ID, Uniqued), V(V) {
482 assert(V && "Expected valid value");
483 }
484
485 ~ValueAsMetadata() = default;
486
487public:
488 LLVM_ABI static ValueAsMetadata *get(Value *V);
489
493
497
499
503
507
508 Value *getValue() const { return V; }
509 Type *getType() const { return V->getType(); }
510 LLVMContext &getContext() const { return V->getContext(); }
511
518
519 LLVM_ABI static void handleDeletion(Value *V);
520 LLVM_ABI static void handleRAUW(Value *From, Value *To);
521
522protected:
523 /// Handle collisions after \a Value::replaceAllUsesWith().
524 ///
525 /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
526 /// \a Value gets RAUW'ed and the target already exists, this is used to
527 /// merge the two metadata nodes.
531
532public:
533 static bool classof(const Metadata *MD) {
534 return MD->getMetadataID() == LocalAsMetadataKind ||
535 MD->getMetadataID() == ConstantAsMetadataKind;
536 }
537};
538
539class ConstantAsMetadata : public ValueAsMetadata {
540 friend class ValueAsMetadata;
541
542 ConstantAsMetadata(Constant *C)
543 : ValueAsMetadata(ConstantAsMetadataKind, C) {}
544
545public:
546 static ConstantAsMetadata *get(Constant *C) {
548 }
549
550 static ConstantAsMetadata *getIfExists(Constant *C) {
552 }
553
557
558 static bool classof(const Metadata *MD) {
559 return MD->getMetadataID() == ConstantAsMetadataKind;
560 }
561};
562
563class LocalAsMetadata : public ValueAsMetadata {
564 friend class ValueAsMetadata;
565
566 LocalAsMetadata(Value *Local)
567 : ValueAsMetadata(LocalAsMetadataKind, Local) {
568 assert(!isa<Constant>(Local) && "Expected local value");
569 }
570
571public:
572 static LocalAsMetadata *get(Value *Local) {
574 }
575
576 static LocalAsMetadata *getIfExists(Value *Local) {
578 }
579
580 static bool classof(const Metadata *MD) {
581 return MD->getMetadataID() == LocalAsMetadataKind;
582 }
583};
584
585/// Transitional API for extracting constants from Metadata.
586///
587/// This namespace contains transitional functions for metadata that points to
588/// \a Constants.
589///
590/// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
591/// operands could refer to any \a Value. There's was a lot of code like this:
592///
593/// \code
594/// MDNode *N = ...;
595/// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
596/// \endcode
597///
598/// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
599/// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
600/// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
601/// cast in the \a Value hierarchy. Besides creating boiler-plate, this
602/// requires subtle control flow changes.
603///
604/// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
605/// so that metadata can refer to numbers without traversing a bridge to the \a
606/// Value hierarchy. In this final state, the code above would look like this:
607///
608/// \code
609/// MDNode *N = ...;
610/// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
611/// \endcode
612///
613/// The API in this namespace supports the transition. \a MDInt doesn't exist
614/// yet, and even once it does, changing each metadata schema to use it is its
615/// own mini-project. In the meantime this API prevents us from introducing
616/// complex and bug-prone control flow that will disappear in the end. In
617/// particular, the above code looks like this:
618///
619/// \code
620/// MDNode *N = ...;
621/// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
622/// \endcode
623///
624/// The full set of provided functions includes:
625///
626/// mdconst::hasa <=> isa
627/// mdconst::extract <=> cast
628/// mdconst::extract_or_null <=> cast_or_null
629/// mdconst::dyn_extract <=> dyn_cast
630/// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
631///
632/// The target of the cast must be a subclass of \a Constant.
633namespace mdconst {
634
635namespace detail {
636template <typename U, typename V>
637using check_has_dereference = decltype(static_cast<V>(*std::declval<U &>()));
638
639template <typename U, typename V>
640static constexpr bool HasDereference =
642
643template <class V, class M> struct IsValidPointer {
644 static const bool value = std::is_base_of<Constant, V>::value &&
646};
647template <class V, class M> struct IsValidReference {
648 static const bool value = std::is_base_of<Constant, V>::value &&
649 std::is_convertible<M, const Metadata &>::value;
650};
651
652} // end namespace detail
653
654/// Check whether Metadata has a Value.
655///
656/// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
657/// type \c X.
658template <class X, class Y>
659inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, bool>
660hasa(Y &&MD) {
661 assert(MD && "Null pointer sent into hasa");
662 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
663 return isa<X>(V->getValue());
664 return false;
665}
666template <class X, class Y>
667inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, bool>
668hasa(Y &MD) {
669 return hasa(&MD);
670}
671
672/// Extract a Value from Metadata.
673///
674/// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
675template <class X, class Y>
676inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
677extract(Y &&MD) {
679}
680template <class X, class Y>
681inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, X *>
682extract(Y &MD) {
683 return extract(&MD);
684}
685
686/// Extract a Value from Metadata, allowing null.
687///
688/// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
689/// from \c MD, allowing \c MD to be null.
690template <class X, class Y>
691inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
693 if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
694 return cast<X>(V->getValue());
695 return nullptr;
696}
697
698/// Extract a Value from Metadata, if any.
699///
700/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
701/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
702/// Value it does contain is of the wrong subclass.
703template <class X, class Y>
704inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
706 if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
707 return dyn_cast<X>(V->getValue());
708 return nullptr;
709}
710
711/// Extract a Value from Metadata, if any, allowing null.
712///
713/// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
714/// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
715/// Value it does contain is of the wrong subclass, allowing \c MD to be null.
716template <class X, class Y>
717inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
719 if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
720 return dyn_cast<X>(V->getValue());
721 return nullptr;
722}
723
724} // end namespace mdconst
725
726//===----------------------------------------------------------------------===//
727/// A single uniqued string.
728///
729/// These are used to efficiently contain a byte sequence for metadata.
730/// MDString is always unnamed.
731class MDString : public Metadata {
732 friend class StringMapEntryStorage<MDString>;
733
734 StringMapEntry<MDString> *Entry = nullptr;
735
736 MDString() : Metadata(MDStringKind, Uniqued) {}
737
738public:
739 MDString(const MDString &) = delete;
740 MDString &operator=(MDString &&) = delete;
741 MDString &operator=(const MDString &) = delete;
742
743 LLVM_ABI static MDString *get(LLVMContext &Context, StringRef Str);
744 static MDString *get(LLVMContext &Context, const char *Str) {
745 return get(Context, Str ? StringRef(Str) : StringRef());
746 }
747 LLVM_ABI static MDString *getIfExists(LLVMContext &Context, StringRef Str);
748
750
751 unsigned getLength() const { return (unsigned)getString().size(); }
752
754
755 /// Pointer to the first byte of the string.
756 iterator begin() const { return getString().begin(); }
757
758 /// Pointer to one byte past the end of the string.
759 iterator end() const { return getString().end(); }
760
761 const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
762 const unsigned char *bytes_end() const { return getString().bytes_end(); }
763
764 /// Methods for support type inquiry through isa, cast, and dyn_cast.
765 static bool classof(const Metadata *MD) {
766 return MD->getMetadataID() == MDStringKind;
767 }
768};
769
770/// A collection of metadata nodes that might be associated with a
771/// memory access used by the alias-analysis infrastructure.
772struct AAMDNodes {
773 explicit AAMDNodes() = default;
774 explicit AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N, MDNode *NAS)
775 : TBAA(T), TBAAStruct(TS), Scope(S), NoAlias(N), NoAliasAddrSpace(NAS) {}
776
777 bool operator==(const AAMDNodes &A) const {
778 return TBAA == A.TBAA && TBAAStruct == A.TBAAStruct && Scope == A.Scope &&
779 NoAlias == A.NoAlias && NoAliasAddrSpace == A.NoAliasAddrSpace;
780 }
781
782 bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
783
784 explicit operator bool() const {
785 return TBAA || TBAAStruct || Scope || NoAlias || NoAliasAddrSpace;
786 }
787
788 /// The tag for type-based alias analysis.
789 MDNode *TBAA = nullptr;
790
791 /// The tag for type-based alias analysis (tbaa struct).
792 MDNode *TBAAStruct = nullptr;
793
794 /// The tag for alias scope specification (used with noalias).
795 MDNode *Scope = nullptr;
796
797 /// The tag specifying the noalias scope.
798 MDNode *NoAlias = nullptr;
799
800 /// The tag specifying the noalias address spaces.
802
803 // Shift tbaa Metadata node to start off bytes later
804 LLVM_ABI static MDNode *shiftTBAA(MDNode *M, size_t off);
805
806 // Shift tbaa.struct Metadata node to start off bytes later
807 LLVM_ABI static MDNode *shiftTBAAStruct(MDNode *M, size_t off);
808
809 // Extend tbaa Metadata node to apply to a series of bytes of length len.
810 // A size of -1 denotes an unknown size.
811 LLVM_ABI static MDNode *extendToTBAA(MDNode *TBAA, ssize_t len);
812
813 /// Given two sets of AAMDNodes that apply to the same pointer,
814 /// give the best AAMDNodes that are compatible with both (i.e. a set of
815 /// nodes whose allowable aliasing conclusions are a subset of those
816 /// allowable by both of the inputs). However, for efficiency
817 /// reasons, do not create any new MDNodes.
819 AAMDNodes Result;
820 Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
821 Result.TBAAStruct = Other.TBAAStruct == TBAAStruct ? TBAAStruct : nullptr;
822 Result.Scope = Other.Scope == Scope ? Scope : nullptr;
823 Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
824 Result.NoAliasAddrSpace =
825 Other.NoAliasAddrSpace == NoAliasAddrSpace ? NoAliasAddrSpace : nullptr;
826 return Result;
827 }
828
829 /// Create a new AAMDNode that describes this AAMDNode after applying a
830 /// constant offset to the start of the pointer.
831 AAMDNodes shift(size_t Offset) const {
832 AAMDNodes Result;
833 Result.TBAA = TBAA ? shiftTBAA(TBAA, Offset) : nullptr;
834 Result.TBAAStruct =
836 Result.Scope = Scope;
837 Result.NoAlias = NoAlias;
838 Result.NoAliasAddrSpace = NoAliasAddrSpace;
839 return Result;
840 }
841
842 /// Create a new AAMDNode that describes this AAMDNode after extending it to
843 /// apply to a series of bytes of length Len. A size of -1 denotes an unknown
844 /// size.
845 AAMDNodes extendTo(ssize_t Len) const {
846 AAMDNodes Result;
847 Result.TBAA = TBAA ? extendToTBAA(TBAA, Len) : nullptr;
848 // tbaa.struct contains (offset, size, type) triples. Extending the length
849 // of the tbaa.struct doesn't require changing this (though more information
850 // could be provided by adding more triples at subsequent lengths).
851 Result.TBAAStruct = TBAAStruct;
852 Result.Scope = Scope;
853 Result.NoAlias = NoAlias;
854 Result.NoAliasAddrSpace = NoAliasAddrSpace;
855 return Result;
856 }
857
858 /// Given two sets of AAMDNodes applying to potentially different locations,
859 /// determine the best AAMDNodes that apply to both.
860 LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const;
861
862 /// Determine the best AAMDNodes after concatenating two different locations
863 /// together. Different from `merge`, where different locations should
864 /// overlap each other, `concat` puts non-overlapping locations together.
866
867 /// Create a new AAMDNode for accessing \p AccessSize bytes of this AAMDNode.
868 /// If this AAMDNode has !tbaa.struct and \p AccessSize matches the size of
869 /// the field at offset 0, get the TBAA tag describing the accessed field.
870 /// If such an AAMDNode already embeds !tbaa, the existing one is retrieved.
871 /// Finally, !tbaa.struct is zeroed out.
872 LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize);
873 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
874 const DataLayout &DL);
875 LLVM_ABI AAMDNodes adjustForAccess(size_t Offset, unsigned AccessSize);
876};
877
878// Specialize DenseMapInfo for AAMDNodes.
892
893/// Tracking metadata reference owned by Metadata.
894///
895/// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
896/// of \a Metadata, which has the option of registering itself for callbacks to
897/// re-unique itself.
898///
899/// In particular, this is used by \a MDNode.
901 Metadata *MD = nullptr;
902
903public:
904 MDOperand() = default;
905 MDOperand(const MDOperand &) = delete;
907 MD = Op.MD;
908 if (MD)
909 (void)MetadataTracking::retrack(Op.MD, MD);
910 Op.MD = nullptr;
911 }
912 MDOperand &operator=(const MDOperand &) = delete;
914 MD = Op.MD;
915 if (MD)
916 (void)MetadataTracking::retrack(Op.MD, MD);
917 Op.MD = nullptr;
918 return *this;
919 }
920
921 // Check if MDOperand is of type MDString and equals `Str`.
922 bool equalsStr(StringRef Str) const {
923 return isa_and_nonnull<MDString>(get()) &&
924 cast<MDString>(get())->getString() == Str;
925 }
926
927 ~MDOperand() { untrack(); }
928
929 Metadata *get() const { return MD; }
930 operator Metadata *() const { return get(); }
931 Metadata *operator->() const { return get(); }
932 Metadata &operator*() const { return *get(); }
933
934 void reset() {
935 untrack();
936 MD = nullptr;
937 }
939 untrack();
940 this->MD = MD;
941 track(Owner);
942 }
943
944private:
945 void track(Metadata *Owner) {
946 if (MD) {
947 if (Owner)
948 MetadataTracking::track(this, *MD, *Owner);
949 else
951 }
952 }
953
954 void untrack() {
955 assert(static_cast<void *>(this) == &MD && "Expected same address");
956 if (MD)
958 }
959};
960
961template <> struct simplify_type<MDOperand> {
963
964 static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
965};
966
967template <> struct simplify_type<const MDOperand> {
969
970 static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
971};
972
973/// Pointer to the context, with optional RAUW support.
974///
975/// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
976/// to \a ReplaceableUsesWithContext.
979
980public:
981 ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
983 std::unique_ptr<ReplaceableUsesWithContext> ReplaceableUses)
984 : Ptr(ReplaceableUses.release()) {
985 assert(getReplaceableUses() && "Expected non-null replaceable uses");
986 }
994
995 operator LLVMContext &() { return getContext(); }
996
997 /// Whether this contains RAUW support.
998 bool hasReplaceableUses() const {
1000 }
1001
1003 if (hasReplaceableUses())
1004 return getReplaceableUses()->getContext();
1005 return *cast<LLVMContext *>(Ptr);
1006 }
1007
1009 if (hasReplaceableUses())
1011 return nullptr;
1012 }
1013
1014 /// Ensure that this has RAUW support, and then return it.
1016 if (!hasReplaceableUses())
1018 std::make_unique<ReplaceableUsesWithContext>(getContext()));
1019 return getReplaceableUses();
1020 }
1021
1022 /// Assign RAUW support to this.
1023 ///
1024 /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
1025 /// not be null).
1026 void
1027 makeReplaceable(std::unique_ptr<ReplaceableUsesWithContext> ReplaceableUses) {
1028 assert(ReplaceableUses && "Expected non-null replaceable uses");
1029 assert(&ReplaceableUses->getContext() == &getContext() &&
1030 "Expected same context");
1031 delete getReplaceableUses();
1032 Ptr = ReplaceableUses.release();
1033 }
1034
1035 /// Drop RAUW support.
1036 ///
1037 /// Cede ownership of RAUW support, returning it.
1038 std::unique_ptr<ReplaceableUsesWithContext> takeReplaceableUses() {
1039 assert(hasReplaceableUses() && "Expected to own replaceable uses");
1040 std::unique_ptr<ReplaceableUsesWithContext> ReplaceableUses(
1042 Ptr = &ReplaceableUses->getContext();
1043 return ReplaceableUses;
1044 }
1045};
1046
1048 inline void operator()(MDNode *Node) const;
1049};
1050
1051#define HANDLE_MDNODE_LEAF(CLASS) \
1052 using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
1053#define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
1054#include "llvm/IR/Metadata.def"
1055
1056/// Metadata node.
1057///
1058/// Metadata nodes can be uniqued, like constants, or distinct. Temporary
1059/// metadata nodes (with full support for RAUW) can be used to delay uniquing
1060/// until forward references are known. The basic metadata node is an \a
1061/// MDTuple.
1062///
1063/// There is limited support for RAUW at construction time. At construction
1064/// time, if any operand is a temporary node (or an unresolved uniqued node,
1065/// which indicates a transitive temporary operand), the node itself will be
1066/// unresolved. As soon as all operands become resolved, it will drop RAUW
1067/// support permanently.
1068///
1069/// If an unresolved node is part of a cycle, \a resolveCycles() needs
1070/// to be called on some member of the cycle once all temporary nodes have been
1071/// replaced.
1072///
1073/// MDNodes can be large or small, as well as resizable or non-resizable.
1074/// Large MDNodes' operands are allocated in a separate storage vector,
1075/// whereas small MDNodes' operands are co-allocated. Distinct and temporary
1076/// MDnodes are resizable, but only MDTuples support this capability.
1077///
1078/// Clients can add operands to resizable MDNodes using push_back().
1079class MDNode : public Metadata {
1080 friend class ReplaceableUses;
1081 friend class LLVMContextImpl;
1082 friend class DIAssignID;
1083
1084 /// The header that is coallocated with an MDNode along with its "small"
1085 /// operands. It is located immediately before the main body of the node.
1086 /// The operands are in turn located immediately before the header.
1087 /// For resizable MDNodes, the space for the storage vector is also allocated
1088 /// immediately before the header, overlapping with the operands.
1089 /// Explicity set alignment because bitfields by default have an
1090 /// alignment of 1 on z/OS.
1091 struct alignas(alignof(size_t)) Header {
1092 uint32_t IsResizable : 1;
1093 uint32_t IsLarge : 1;
1094 uint32_t SmallSize : 4;
1095 uint32_t SmallNumOps : 4;
1096 uint32_t MetadataPrintID;
1097
1098 unsigned NumUnresolved = 0;
1099 using LargeStorageVector = SmallVector<MDOperand, 0>;
1100
1101 static constexpr size_t NumOpsFitInVector =
1102 sizeof(LargeStorageVector) / sizeof(MDOperand);
1103 static_assert(
1104 NumOpsFitInVector * sizeof(MDOperand) == sizeof(LargeStorageVector),
1105 "sizeof(LargeStorageVector) must be a multiple of sizeof(MDOperand)");
1106
1107 static constexpr size_t MaxSmallSize = 15;
1108
1109 static constexpr size_t getOpSize(unsigned NumOps) {
1110 return sizeof(MDOperand) * NumOps;
1111 }
1112 /// Returns the number of operands the node has space for based on its
1113 /// allocation characteristics.
1114 static size_t getSmallSize(size_t NumOps, bool IsResizable, bool IsLarge) {
1115 return IsLarge ? NumOpsFitInVector
1116 : std::max(NumOps, NumOpsFitInVector * IsResizable);
1117 }
1118 /// Returns the number of bytes allocated for operands and header.
1119 static size_t getAllocSize(StorageType Storage, size_t NumOps) {
1120 return getOpSize(
1121 getSmallSize(NumOps, isResizable(Storage), isLarge(NumOps))) +
1122 sizeof(Header);
1123 }
1124
1125 /// Only temporary and distinct nodes are resizable.
1126 static bool isResizable(StorageType Storage) { return Storage != Uniqued; }
1127 static bool isLarge(size_t NumOps) { return NumOps > MaxSmallSize; }
1128
1129 size_t getAllocSize() const {
1130 return getOpSize(SmallSize) + sizeof(Header);
1131 }
1132 void *getAllocation() {
1133 return reinterpret_cast<char *>(this + 1) -
1134 alignTo(getAllocSize(), alignof(uint64_t));
1135 }
1136
1137 void *getLargePtr() const {
1138 static_assert(alignof(LargeStorageVector) <= alignof(Header),
1139 "LargeStorageVector too strongly aligned");
1140 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
1141 sizeof(LargeStorageVector);
1142 }
1143
1144 LLVM_ABI void *getSmallPtr();
1145
1146 LargeStorageVector &getLarge() {
1147 assert(IsLarge);
1148 return *reinterpret_cast<LargeStorageVector *>(getLargePtr());
1149 }
1150
1151 const LargeStorageVector &getLarge() const {
1152 assert(IsLarge);
1153 return *reinterpret_cast<const LargeStorageVector *>(getLargePtr());
1154 }
1155
1156 LLVM_ABI void resizeSmall(size_t NumOps);
1157 LLVM_ABI void resizeSmallToLarge(size_t NumOps);
1158 LLVM_ABI void resize(size_t NumOps);
1159
1160 LLVM_ABI explicit Header(size_t NumOps, StorageType Storage);
1161 LLVM_ABI ~Header();
1162
1164 if (IsLarge)
1165 return getLarge();
1166 return MutableArrayRef(
1167 reinterpret_cast<MDOperand *>(this) - SmallSize, SmallNumOps);
1168 }
1169
1171 if (IsLarge)
1172 return getLarge();
1173 return ArrayRef(reinterpret_cast<const MDOperand *>(this) - SmallSize,
1174 SmallNumOps);
1175 }
1176
1177 unsigned getNumOperands() const {
1178 if (!IsLarge)
1179 return SmallNumOps;
1180 return getLarge().size();
1181 }
1182 };
1183
1184 Header &getHeader() { return *(reinterpret_cast<Header *>(this) - 1); }
1185
1186 const Header &getHeader() const {
1187 return *(reinterpret_cast<const Header *>(this) - 1);
1188 }
1189
1190 ContextAndReplaceableUses Context;
1191
1192protected:
1193 LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
1195 ~MDNode() = default;
1196
1197 LLVM_ABI void *operator new(size_t Size, size_t NumOps, StorageType Storage);
1198 LLVM_ABI void operator delete(void *Mem);
1199
1200 /// Required by std, but never called.
1201 void operator delete(void *, unsigned) {
1202 llvm_unreachable("Constructor throws?");
1203 }
1204
1205 /// Required by std, but never called.
1206 void operator delete(void *, unsigned, bool) {
1207 llvm_unreachable("Constructor throws?");
1208 }
1209
1211
1212 MDOperand *mutable_begin() { return getHeader().operands().begin(); }
1213 MDOperand *mutable_end() { return getHeader().operands().end(); }
1214
1216
1220
1221public:
1222 MDNode(const MDNode &) = delete;
1223 void operator=(const MDNode &) = delete;
1224 void *operator new(size_t) = delete;
1225
1226 static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
1227 static inline MDTuple *getIfExists(LLVMContext &Context,
1229 static inline MDTuple *getDistinct(LLVMContext &Context,
1231 static inline TempMDTuple getTemporary(LLVMContext &Context,
1233
1234 /// Create a (temporary) clone of this.
1235 LLVM_ABI TempMDNode clone() const;
1236
1237 /// Deallocate a node created by getTemporary.
1238 ///
1239 /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
1240 /// references will be reset.
1241 LLVM_ABI static void deleteTemporary(MDNode *N);
1242
1243 LLVMContext &getContext() const { return Context.getContext(); }
1244
1245 /// Replace a specific operand.
1246 LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New);
1247
1248 /// Check if node is fully resolved.
1249 ///
1250 /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
1251 /// this always returns \c true.
1252 ///
1253 /// If \a isUniqued(), returns \c true if this has already dropped RAUW
1254 /// support (because all operands are resolved).
1255 ///
1256 /// As forward declarations are resolved, their containers should get
1257 /// resolved automatically. However, if this (or one of its operands) is
1258 /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
1259 bool isResolved() const { return !isTemporary() && !getNumUnresolved(); }
1260
1261 bool isUniqued() const { return Storage == Uniqued; }
1262 bool isDistinct() const { return Storage == Distinct; }
1263 bool isTemporary() const { return Storage == Temporary; }
1264
1265 bool isReplaceable() const { return isTemporary() || isAlwaysReplaceable(); }
1266 bool isAlwaysReplaceable() const { return getMetadataID() == DIAssignIDKind; }
1267
1268 unsigned getNumTemporaryUses() const {
1269 assert(isTemporary() && "Only for temporaries");
1270 return Context.getReplaceableUses()->getNumUses();
1271 }
1272
1273 /// RAUW a temporary.
1274 ///
1275 /// \pre \a isTemporary() must be \c true.
1277 assert(isReplaceable() && "Expected temporary/replaceable node");
1278 if (Context.hasReplaceableUses())
1279 Context.getReplaceableUses()->replaceAllUsesWith(MD);
1280 }
1281
1282 /// Resolve cycles.
1283 ///
1284 /// Once all forward declarations have been resolved, force cycles to be
1285 /// resolved.
1286 ///
1287 /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
1288 LLVM_ABI void resolveCycles();
1289
1290 /// Resolve a unique, unresolved node.
1291 LLVM_ABI void resolve();
1292
1293 /// Replace a temporary node with a permanent one.
1294 ///
1295 /// Try to create a uniqued version of \c N -- in place, if possible -- and
1296 /// return it. If \c N cannot be uniqued, return a distinct node instead.
1297 template <class T>
1298 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1299 replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
1300 return cast<T>(N.release()->replaceWithPermanentImpl());
1301 }
1302
1303 /// Replace a temporary node with a uniqued one.
1304 ///
1305 /// Create a uniqued version of \c N -- in place, if possible -- and return
1306 /// it. Takes ownership of the temporary node.
1307 ///
1308 /// \pre N does not self-reference.
1309 template <class T>
1310 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1311 replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
1312 return cast<T>(N.release()->replaceWithUniquedImpl());
1313 }
1314
1315 /// Replace a temporary node with a distinct one.
1316 ///
1317 /// Create a distinct version of \c N -- in place, if possible -- and return
1318 /// it. Takes ownership of the temporary node.
1319 template <class T>
1320 static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1321 replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
1322 return cast<T>(N.release()->replaceWithDistinctImpl());
1323 }
1324
1325 /// Print in tree shape.
1326 ///
1327 /// Prints definition of \c this in tree shape.
1328 ///
1329 /// If \c M is provided, metadata nodes will be numbered canonically;
1330 /// otherwise, pointer addresses are substituted.
1331 /// @{
1332 LLVM_ABI void printTree(raw_ostream &OS, const Module *M = nullptr) const;
1334 const Module *M = nullptr) const;
1335 /// @}
1336
1337 /// User-friendly dump in tree shape.
1338 ///
1339 /// If \c M is provided, metadata nodes will be numbered canonically;
1340 /// otherwise, pointer addresses are substituted.
1341 ///
1342 /// Note: this uses an explicit overload instead of default arguments so that
1343 /// the nullptr version is easy to call from a debugger.
1344 ///
1345 /// @{
1346 LLVM_ABI void dumpTree() const;
1347 LLVM_ABI void dumpTree(const Module *M) const;
1348 /// @}
1349
1350private:
1351 LLVM_ABI MDNode *replaceWithPermanentImpl();
1352 LLVM_ABI MDNode *replaceWithUniquedImpl();
1353 LLVM_ABI MDNode *replaceWithDistinctImpl();
1354
1355protected:
1356 /// Set an operand.
1357 ///
1358 /// Sets the operand directly, without worrying about uniquing.
1359 LLVM_ABI void setOperand(unsigned I, Metadata *New);
1360
1361 unsigned getNumUnresolved() const { return getHeader().NumUnresolved; }
1362
1363 void setNumUnresolved(unsigned N) { getHeader().NumUnresolved = N; }
1365 template <class T, class StoreT>
1366 static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1367 template <class T> static T *storeImpl(T *N, StorageType Storage);
1368
1369 /// Resize the node to hold \a NumOps operands.
1370 ///
1371 /// \pre \a isTemporary() or \a isDistinct()
1372 /// \pre MetadataID == MDTupleKind
1373 void resize(size_t NumOps) {
1374 assert(!isUniqued() && "Resizing is not supported for uniqued nodes");
1375 assert(getMetadataID() == MDTupleKind &&
1376 "Resizing is not supported for this node kind");
1377 getHeader().resize(NumOps);
1378 }
1379
1380private:
1381 void handleChangedOperand(void *Ref, Metadata *New);
1382
1383 /// Drop RAUW support, if any.
1384 void dropReplaceableUses();
1385
1386 void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1387 void decrementUnresolvedOperandCount();
1388 void countUnresolvedOperands();
1389
1390 /// Mutate this to be "uniqued".
1391 ///
1392 /// Mutate this so that \a isUniqued().
1393 /// \pre \a isTemporary().
1394 /// \pre already added to uniquing set.
1395 void makeUniqued();
1396
1397 /// Mutate this to be "distinct".
1398 ///
1399 /// Mutate this so that \a isDistinct().
1400 /// \pre \a isTemporary().
1401 void makeDistinct();
1402
1403 void deleteAsSubclass();
1404 MDNode *uniquify();
1405 void eraseFromStore();
1406
1407 template <class NodeTy> struct HasCachedHash;
1408 template <class NodeTy> static void dispatchRecalculateHash(NodeTy *N) {
1409 if constexpr (HasCachedHash<NodeTy>::value)
1410 N->recalculateHash();
1411 }
1412 template <class NodeTy> static void dispatchResetHash(NodeTy *N) {
1413 if constexpr (HasCachedHash<NodeTy>::value)
1414 N->setHash(0);
1415 }
1416
1417 /// Merge branch weights from two direct callsites.
1418 static MDNode *mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1419 const Instruction *AInstr,
1420 const Instruction *BInstr);
1421
1422public:
1423 using op_iterator = const MDOperand *;
1425
1427 return const_cast<MDNode *>(this)->mutable_begin();
1428 }
1429
1431 return const_cast<MDNode *>(this)->mutable_end();
1432 }
1433
1434 ArrayRef<MDOperand> operands() const { return getHeader().operands(); }
1435
1436 const MDOperand &getOperand(unsigned I) const {
1437 assert(I < getNumOperands() && "Out of range");
1438 return getHeader().operands()[I];
1439 }
1440
1441 /// Return number of MDNode operands.
1442 unsigned getNumOperands() const { return getHeader().getNumOperands(); }
1443
1444 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1445 static bool classof(const Metadata *MD) {
1446 switch (MD->getMetadataID()) {
1447 default:
1448 return false;
1449#define HANDLE_MDNODE_LEAF(CLASS) \
1450 case CLASS##Kind: \
1451 return true;
1452#include "llvm/IR/Metadata.def"
1453 }
1454 }
1455
1456 /// Check whether MDNode is a vtable access.
1457 LLVM_ABI bool isTBAAVtableAccess() const;
1458
1459 /// Methods for metadata merging.
1461 LLVM_ABI static MDNode *intersect(MDNode *A, MDNode *B);
1468 MDNode *B);
1470 /// Merge !prof metadata from two instructions.
1471 /// Currently only implemented with direct callsites with branch weights.
1473 const Instruction *AInstr,
1474 const Instruction *BInstr);
1478 const MDNode *B);
1480 const MDNode *B);
1481
1482 /// Convert !captures metadata to CaptureComponents. MD may be nullptr.
1484 /// Convert CaptureComponents to !captures metadata. The return value may be
1485 /// nullptr.
1488};
1489
1490/// Tuple of metadata.
1491///
1492/// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
1493/// default based on their operands.
1494class MDTuple : public MDNode {
1495 friend class LLVMContextImpl;
1496 friend class MDNode;
1497
1498 MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1500 : MDNode(C, MDTupleKind, Storage, Vals) {
1501 setHash(Hash);
1502 }
1503
1505
1506 void setHash(unsigned Hash) { SubclassData32 = Hash; }
1507 void recalculateHash();
1508
1509 LLVM_ABI static MDTuple *getImpl(LLVMContext &Context,
1512 bool ShouldCreate = true);
1513
1514 TempMDTuple cloneImpl() const {
1517 }
1518
1519public:
1520 /// Get the hash, if any.
1521 unsigned getHash() const { return SubclassData32; }
1522
1523 static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1524 return getImpl(Context, MDs, Uniqued);
1525 }
1526
1527 static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1528 return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1529 }
1530
1531 /// Return a distinct node.
1532 ///
1533 /// Return a distinct node -- i.e., a node that is not uniqued.
1534 static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1535 return getImpl(Context, MDs, Distinct);
1536 }
1537
1538 /// Return a temporary node.
1539 ///
1540 /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1541 /// not uniqued, may be RAUW'd, and must be manually deleted with
1542 /// deleteTemporary.
1543 static TempMDTuple getTemporary(LLVMContext &Context,
1545 return TempMDTuple(getImpl(Context, MDs, Temporary));
1546 }
1547
1548 /// Return a (temporary) clone of this.
1549 TempMDTuple clone() const { return cloneImpl(); }
1550
1551 /// Append an element to the tuple. This will resize the node.
1553 size_t NumOps = getNumOperands();
1554 resize(NumOps + 1);
1555 setOperand(NumOps, MD);
1556 }
1557
1558 /// Shrink the operands by 1.
1559 void pop_back() { resize(getNumOperands() - 1); }
1560
1561 /// Filter out tuple elements that do not satisfy predicate.
1562 /// Return this if no elements should be filtered out (without re-uniquing).
1563 template <typename T> MDTuple *filter(T &&Pred) {
1565 // Exit if no nodes should be removed.
1566 if (llvm::all_of(Ops, Pred))
1567 return this;
1568 return get(getContext(),
1570 }
1571
1572 static bool classof(const Metadata *MD) {
1573 return MD->getMetadataID() == MDTupleKind;
1574 }
1575};
1576
1578 return MDTuple::get(Context, MDs);
1579}
1580
1582 return MDTuple::getIfExists(Context, MDs);
1583}
1584
1586 return MDTuple::getDistinct(Context, MDs);
1587}
1588
1591 return MDTuple::getTemporary(Context, MDs);
1592}
1593
1597
1598/// This is a simple wrapper around an MDNode which provides a higher-level
1599/// interface by hiding the details of how alias analysis information is encoded
1600/// in its operands.
1602 const MDNode *Node = nullptr;
1603
1604public:
1605 AliasScopeNode() = default;
1606 explicit AliasScopeNode(const MDNode *N) : Node(N) {}
1607
1608 /// Get the MDNode for this AliasScopeNode.
1609 const MDNode *getNode() const { return Node; }
1610
1611 /// Get the MDNode for this AliasScopeNode's domain.
1612 const MDNode *getDomain() const {
1613 if (Node->getNumOperands() < 2)
1614 return nullptr;
1615 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
1616 }
1618 if (Node->getNumOperands() > 2)
1619 if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
1620 return N->getString();
1621 return StringRef();
1622 }
1623};
1624
1625/// Typed iterator through MDNode operands.
1626///
1627/// An iterator that transforms an \a MDNode::iterator into an iterator over a
1628/// particular Metadata subclass.
1629template <class T> class TypedMDOperandIterator {
1630 MDNode::op_iterator I = nullptr;
1631
1632public:
1633 using iterator_category = std::forward_iterator_tag;
1634 using value_type = T *;
1635 using difference_type = std::ptrdiff_t;
1636 using pointer = void;
1637 using reference = T *;
1638
1641
1642 T *operator*() const { return cast_or_null<T>(*I); }
1643
1645 ++I;
1646 return *this;
1647 }
1648
1650 TypedMDOperandIterator Temp(*this);
1651 ++I;
1652 return Temp;
1653 }
1654
1655 bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1656 bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1657};
1658
1659/// Typed, array-like tuple of metadata.
1660///
1661/// This is a wrapper for \a MDTuple that makes it act like an array holding a
1662/// particular type of metadata.
1663template <class T> class MDTupleTypedArrayWrapper {
1664 const MDTuple *N = nullptr;
1665
1666public:
1669
1670 template <class U>
1673 std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
1674 : N(Other.get()) {}
1675
1676 template <class U>
1679 std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
1680 : N(Other.get()) {}
1681
1682 explicit operator bool() const { return get(); }
1683 explicit operator MDTuple *() const { return get(); }
1684
1685 MDTuple *get() const { return const_cast<MDTuple *>(N); }
1686 MDTuple *operator->() const { return get(); }
1687 MDTuple &operator*() const { return *get(); }
1688
1689 // FIXME: Fix callers and remove condition on N.
1690 unsigned size() const { return N ? N->getNumOperands() : 0u; }
1691 bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1692 T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1693
1694 // FIXME: Fix callers and remove condition on N.
1696
1697 iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1698 iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1699};
1700
1701#define HANDLE_METADATA(CLASS) \
1702 using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1703#include "llvm/IR/Metadata.def"
1704
1705/// Placeholder metadata for operands of distinct MDNodes.
1706///
1707/// This is a lightweight placeholder for an operand of a distinct node. It's
1708/// purpose is to help track forward references when creating a distinct node.
1709/// This allows distinct nodes involved in a cycle to be constructed before
1710/// their operands without requiring a heavyweight temporary node with
1711/// full-blown RAUW support.
1712///
1713/// Each placeholder supports only a single MDNode user. Clients should pass
1714/// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1715/// should be replaced with.
1716///
1717/// While it would be possible to implement move operators, they would be
1718/// fairly expensive. Leave them unimplemented to discourage their use
1719/// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1721 friend class MetadataTracking;
1722
1723 Metadata **Use = nullptr;
1724
1725public:
1726 explicit DistinctMDOperandPlaceholder(unsigned ID)
1727 : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1728 SubclassData32 = ID;
1729 }
1730
1734
1736 if (Use)
1737 *Use = nullptr;
1738 }
1739
1740 unsigned getID() const { return SubclassData32; }
1741
1742 /// Replace the use of this with MD.
1744 if (!Use)
1745 return;
1746 *Use = MD;
1747
1748 if (*Use)
1750
1751 Metadata *T = cast<Metadata>(this);
1753 assert(!Use && "Use is still being tracked despite being untracked!");
1754 }
1755};
1756
1757//===----------------------------------------------------------------------===//
1758/// A tuple of MDNodes.
1759///
1760/// Despite its name, a NamedMDNode isn't itself an MDNode.
1761///
1762/// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1763///
1764/// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1765class NamedMDNode : public ilist_node<NamedMDNode> {
1766 friend class LLVMContextImpl;
1767 friend class Module;
1768
1769 std::string Name;
1770 Module *Parent = nullptr;
1771 void *Operands; // SmallVector<TrackingMDRef, 4>
1772
1773 void setParent(Module *M) { Parent = M; }
1774
1775 explicit NamedMDNode(const Twine &N);
1776
1777 template <class T1> class op_iterator_impl {
1778 friend class NamedMDNode;
1779
1780 const NamedMDNode *Node = nullptr;
1781 unsigned Idx = 0;
1782
1783 op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1784
1785 public:
1786 using iterator_category = std::bidirectional_iterator_tag;
1787 using value_type = T1;
1788 using difference_type = std::ptrdiff_t;
1789 using pointer = value_type *;
1790 using reference = value_type;
1791
1792 op_iterator_impl() = default;
1793
1794 bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1795 bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1796
1797 op_iterator_impl &operator++() {
1798 ++Idx;
1799 return *this;
1800 }
1801
1802 op_iterator_impl operator++(int) {
1803 op_iterator_impl tmp(*this);
1804 operator++();
1805 return tmp;
1806 }
1807
1808 op_iterator_impl &operator--() {
1809 --Idx;
1810 return *this;
1811 }
1812
1813 op_iterator_impl operator--(int) {
1814 op_iterator_impl tmp(*this);
1815 operator--();
1816 return tmp;
1817 }
1818
1819 T1 operator*() const { return Node->getOperand(Idx); }
1820 };
1821
1822public:
1823 NamedMDNode(const NamedMDNode &) = delete;
1825
1826 /// Drop all references and remove the node from parent module.
1828
1829 /// Remove all uses and clear node vector.
1831 /// Drop all references to this node's operands.
1832 LLVM_ABI void clearOperands();
1833
1834 /// Get the module that holds this named metadata collection.
1835 inline Module *getParent() { return Parent; }
1836 inline const Module *getParent() const { return Parent; }
1837
1838 LLVM_ABI MDNode *getOperand(unsigned i) const;
1839 LLVM_ABI unsigned getNumOperands() const;
1840 LLVM_ABI void addOperand(MDNode *M);
1841 LLVM_ABI void setOperand(unsigned I, MDNode *New);
1842 LLVM_ABI StringRef getName() const;
1843 LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug = false) const;
1845 bool IsForDebug = false) const;
1846 LLVM_ABI void dump() const;
1847
1848 // ---------------------------------------------------------------------------
1849 // Operand Iterator interface...
1850 //
1851 using op_iterator = op_iterator_impl<MDNode *>;
1852
1853 op_iterator op_begin() { return op_iterator(this, 0); }
1855
1856 using const_op_iterator = op_iterator_impl<const MDNode *>;
1857
1858 const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1860
1862 return make_range(op_begin(), op_end());
1863 }
1865 return make_range(op_begin(), op_end());
1866 }
1867};
1868
1869// Create wrappers for C Binding types (see CBindingWrapping.h).
1871
1872} // end namespace llvm
1873
1874#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:1606
const MDNode * getNode() const
Get the MDNode for this AliasScopeNode.
Definition Metadata.h:1609
const MDNode * getDomain() const
Get the MDNode for this AliasScopeNode's domain.
Definition Metadata.h:1612
StringRef getName() const
Definition Metadata.h:1617
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
friend class ValueAsMetadata
Definition Metadata.h:540
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:546
Constant * getValue() const
Definition Metadata.h:554
static ConstantAsMetadata * getIfExists(Constant *C)
Definition Metadata.h:550
static bool classof(const Metadata *MD)
Definition Metadata.h:558
This is an important base class in LLVM.
Definition Constant.h:43
ContextAndReplaceableUses & operator=(const ContextAndReplaceableUses &)=delete
ReplaceableUsesWithContext * getReplaceableUses() const
Definition Metadata.h:1008
ReplaceableUsesWithContext * getOrCreateReplaceableUses()
Ensure that this has RAUW support, and then return it.
Definition Metadata.h:1015
ContextAndReplaceableUses & operator=(ContextAndReplaceableUses &&)=delete
ContextAndReplaceableUses(ContextAndReplaceableUses &&)=delete
ContextAndReplaceableUses(const ContextAndReplaceableUses &)=delete
LLVMContext & getContext() const
Definition Metadata.h:1002
ContextAndReplaceableUses(std::unique_ptr< ReplaceableUsesWithContext > ReplaceableUses)
Definition Metadata.h:982
std::unique_ptr< ReplaceableUsesWithContext > takeReplaceableUses()
Drop RAUW support.
Definition Metadata.h:1038
bool hasReplaceableUses() const
Whether this contains RAUW support.
Definition Metadata.h:998
ContextAndReplaceableUses(LLVMContext &Context)
Definition Metadata.h:981
void makeReplaceable(std::unique_ptr< ReplaceableUsesWithContext > ReplaceableUses)
Assign RAUW support to this.
Definition Metadata.h:1027
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 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: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:155
DebugValueUser(DebugValueUser &&X)
Definition Metadata.h:246
void replaceUseWith(Metadata *MD)
Replace the use of this with MD.
Definition Metadata.h:1743
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:564
static LocalAsMetadata * getIfExists(Value *Local)
Definition Metadata.h:576
static LocalAsMetadata * get(Value *Local)
Definition Metadata.h:572
static bool classof(const Metadata *MD)
Definition Metadata.h:580
Metadata node.
Definition Metadata.h:1079
friend class DIAssignID
Definition Metadata.h:1082
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:1215
LLVM_ABI void resolveCycles()
Resolve cycles.
Definition Metadata.cpp:837
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:1585
mutable_op_range mutable_operands()
Definition Metadata.h:1217
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition Metadata.h:1276
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:791
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1436
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
LLVM_ABI void storeDistinctInContext()
bool isTemporary() const
Definition Metadata.h:1263
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1589
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1434
op_iterator op_end() const
Definition Metadata.h:1430
MDNode(const MDNode &)=delete
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1577
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:1321
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:1445
bool isUniqued() const
Definition Metadata.h:1261
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:1363
void resize(size_t NumOps)
Resize the node to hold NumOps operands.
Definition Metadata.h:1373
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1442
MDOperand * mutable_begin()
Definition Metadata.h:1212
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:641
iterator_range< op_iterator > op_range
Definition Metadata.h:1424
friend class LLVMContextImpl
Definition Metadata.h:1081
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition Metadata.cpp:660
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
bool isDistinct() const
Definition Metadata.h:1262
unsigned getNumTemporaryUses() const
Definition Metadata.h:1268
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
bool isReplaceable() const
Definition Metadata.h:1265
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1259
op_iterator op_begin() const
Definition Metadata.h:1426
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:1243
MDOperand * mutable_end()
Definition Metadata.h:1213
~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:1581
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:1299
LLVM_ABI void dropAllReferences()
Definition Metadata.cpp:903
void operator=(const MDNode &)=delete
friend class ReplaceableUses
Definition Metadata.h:1080
const MDOperand * op_iterator
Definition Metadata.h:1423
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:1311
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:1361
bool isAlwaysReplaceable() const
Definition Metadata.h:1266
Tracking metadata reference owned by Metadata.
Definition Metadata.h:900
MDOperand()=default
bool equalsStr(StringRef Str) const
Definition Metadata.h:922
void reset(Metadata *MD, Metadata *Owner)
Definition Metadata.h:938
Metadata * operator->() const
Definition Metadata.h:931
MDOperand & operator=(const MDOperand &)=delete
Metadata & operator*() const
Definition Metadata.h:932
Metadata * get() const
Definition Metadata.h:929
MDOperand(const MDOperand &)=delete
MDOperand & operator=(MDOperand &&Op)
Definition Metadata.h:913
MDOperand(MDOperand &&Op)
Definition Metadata.h:906
A single uniqued string.
Definition Metadata.h:731
unsigned getLength() const
Definition Metadata.h:751
const unsigned char * bytes_begin() const
Definition Metadata.h:761
MDString(const MDString &)=delete
static MDString * get(LLVMContext &Context, const char *Str)
Definition Metadata.h:744
MDString & operator=(MDString &&)=delete
static bool classof(const Metadata *MD)
Methods for support type inquiry through isa, cast, and dyn_cast.
Definition Metadata.h:765
const unsigned char * bytes_end() const
Definition Metadata.h:762
iterator begin() const
Pointer to the first byte of the string.
Definition Metadata.h:756
MDString & operator=(const MDString &)=delete
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:605
static LLVM_ABI MDString * getIfExists(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
StringRef::iterator iterator
Definition Metadata.h:753
iterator end() const
Pointer to one byte past the end of the string.
Definition Metadata.h:759
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:587
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t<!std::is_convertible< U *, T * >::value > *=nullptr)
Definition Metadata.h:1677
MDTupleTypedArrayWrapper(const MDTuple *N)
Definition Metadata.h:1668
T * operator[](unsigned I) const
Definition Metadata.h:1692
MDTuple * operator->() const
Definition Metadata.h:1686
MDTuple & operator*() const
Definition Metadata.h:1687
MDTupleTypedArrayWrapper(const MDTupleTypedArrayWrapper< U > &Other, std::enable_if_t< std::is_convertible< U *, T * >::value > *=nullptr)
Definition Metadata.h:1671
TypedMDOperandIterator< T > iterator
Definition Metadata.h:1695
Tuple of metadata.
Definition Metadata.h:1494
TempMDTuple clone() const
Return a (temporary) clone of this.
Definition Metadata.h:1549
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1534
static bool classof(const Metadata *MD)
Definition Metadata.h:1572
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition Metadata.h:1552
unsigned getHash() const
Get the hash, if any.
Definition Metadata.h:1521
friend class LLVMContextImpl
Definition Metadata.h:1495
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1523
static MDTuple * getIfExists(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1527
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1543
friend class MDNode
Definition Metadata.h:1496
void pop_back()
Shrink the operands by 1.
Definition Metadata.h:1559
MDTuple * filter(T &&Pred)
Filter out tuple elements that do not satisfy predicate.
Definition Metadata.h:1563
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:313
static LLVM_ABI bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition Metadata.cpp:250
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
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:1765
const_op_iterator op_begin() const
Definition Metadata.h:1858
NamedMDNode(const NamedMDNode &)=delete
op_iterator_impl< const MDNode * > const_op_iterator
Definition Metadata.h:1856
friend class Module
Definition Metadata.h:1767
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:1830
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:1859
iterator_range< const_op_iterator > operands() const
Definition Metadata.h:1864
op_iterator op_end()
Definition Metadata.h:1854
LLVM_ABI MDNode * getOperand(unsigned i) const
friend class LLVMContextImpl
Definition Metadata.h:1766
op_iterator op_begin()
Definition Metadata.h:1853
op_iterator_impl< MDNode * > op_iterator
Definition Metadata.h:1851
LLVM_ABI unsigned getNumOperands() const
const Module * getParent() const
Definition Metadata.h:1836
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
iterator_range< op_iterator > operands()
Definition Metadata.h:1861
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1835
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:451
ReplaceableUsesWithContext(LLVMContext &Context)
Definition Metadata.h:455
LLVMContext & getContext() const
Definition Metadata.h:458
Shared implementation of use-lists for replaceable metadata.
Definition Metadata.h:391
friend class MetadataTracking
Definition Metadata.h:392
ReplaceableUses & operator=(const ReplaceableUses &)=delete
MetadataTracking::OwnerTy OwnerTy
Definition Metadata.h:395
LLVM_ABI SmallVector< Metadata * > getAllArgListUsers()
Returns the list of all DIArgList users of this.
Definition Metadata.cpp:254
LLVM_ABI SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Returns the list of all DbgVariableRecord users of this.
Definition Metadata.cpp:276
LLVM_ABI void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition Metadata.cpp:424
LLVM_ABI void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition Metadata.cpp:371
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:334
unsigned getNumUses() const
Definition Metadata.h:427
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:1629
TypedMDOperandIterator operator++(int)
Definition Metadata.h:1649
std::ptrdiff_t difference_type
Definition Metadata.h:1635
bool operator==(const TypedMDOperandIterator &X) const
Definition Metadata.h:1655
TypedMDOperandIterator & operator++()
Definition Metadata.h:1644
std::forward_iterator_tag iterator_category
Definition Metadata.h:1633
TypedMDOperandIterator(MDNode::op_iterator I)
Definition Metadata.h:1640
bool operator!=(const TypedMDOperandIterator &X) const
Definition Metadata.h:1656
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:469
Type * getType() const
Definition Metadata.h:509
static LocalAsMetadata * getLocalIfExists(Value *Local)
Definition Metadata.h:504
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition Metadata.h:528
SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Definition Metadata.h:515
LLVMContext & getContext() const
Definition Metadata.h:510
static LLVM_ABI void handleDeletion(Value *V)
Definition Metadata.cpp:529
static LocalAsMetadata * getLocal(Value *Local)
Definition Metadata.h:494
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:505
static ConstantAsMetadata * getConstantIfExists(Value *C)
Definition Metadata.h:500
static ConstantAsMetadata * getConstant(Value *C)
Definition Metadata.h:490
static LLVM_ABI ValueAsMetadata * getIfExists(Value *V)
Definition Metadata.cpp:524
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition Metadata.cpp:548
static bool classof(const Metadata *MD)
Definition Metadata.h:533
friend class LLVMContextImpl
Definition Metadata.h:471
SmallVector< Metadata * > getAllArgListUsers()
Definition Metadata.h:512
ValueAsMetadata(unsigned ID, Value *V)
Definition Metadata.h:481
friend class ReplaceableUses
Definition Metadata.h:470
Value * getValue() const
Definition Metadata.h:508
~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:640
decltype(static_cast< V >(*std::declval< U & >())) check_has_dereference
Definition Metadata.h:637
Transitional API for extracting constants from Metadata.
Definition Metadata.h:633
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:718
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
Definition Metadata.h:660
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:692
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:705
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:677
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:1739
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:551
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:772
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:782
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:801
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:792
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:795
static LLVM_ABI MDNode * extendToTBAA(MDNode *TBAA, ssize_t len)
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:789
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:831
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:798
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:818
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:774
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:845
bool operator==(const AAMDNodes &A) const
Definition Metadata.h:777
AAMDNodes()=default
static LLVM_ABI MDNode * shiftTBAA(MDNode *M, size_t off)
static unsigned getHashValue(const AAMDNodes &Val)
Definition Metadata.h:880
static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS)
Definition Metadata.h:888
An information struct used to provide DenseMap with the various necessary components for a given valu...
void operator()(MDNode *Node) const
Definition Metadata.h:1594
static SimpleType getSimplifiedValue(MDOperand &MD)
Definition Metadata.h:964
static SimpleType getSimplifiedValue(const MDOperand &MD)
Definition Metadata.h:970
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34