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