• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// @file
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
18 
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseMapInfo.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/PointerUnion.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include <cassert>
35 #include <cstddef>
36 #include <cstdint>
37 #include <iterator>
38 #include <memory>
39 #include <string>
40 #include <type_traits>
41 #include <utility>
42 
43 namespace llvm {
44 
45 class Module;
46 class ModuleSlotTracker;
47 
48 enum LLVMConstants : uint32_t {
49   DEBUG_METADATA_VERSION = 3 // Current debug info version number.
50 };
51 
52 /// \brief Root of the metadata hierarchy.
53 ///
54 /// This is a root class for typeless data in the IR.
55 class Metadata {
56   friend class ReplaceableMetadataImpl;
57 
58   /// \brief RTTI.
59   const unsigned char SubclassID;
60 
61 protected:
62   /// \brief Active type of storage.
63   enum StorageType { Uniqued, Distinct, Temporary };
64 
65   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
66   unsigned char Storage;
67   // TODO: expose remaining bits to subclasses.
68 
69   unsigned short SubclassData16;
70   unsigned SubclassData32;
71 
72 public:
73   enum MetadataKind {
74 #define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
75 #include "llvm/IR/Metadata.def"
76   };
77 
78 protected:
Metadata(unsigned ID,StorageType Storage)79   Metadata(unsigned ID, StorageType Storage)
80       : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
81     static_assert(sizeof(*this) == 8, "Metdata fields poorly packed");
82   }
83 
84   ~Metadata() = default;
85 
86   /// \brief Default handling of a changed operand, which asserts.
87   ///
88   /// If subclasses pass themselves in as owners to a tracking node reference,
89   /// they must provide an implementation of this method.
handleChangedOperand(void *,Metadata *)90   void handleChangedOperand(void *, Metadata *) {
91     llvm_unreachable("Unimplemented in Metadata subclass");
92   }
93 
94 public:
getMetadataID()95   unsigned getMetadataID() const { return SubclassID; }
96 
97   /// \brief User-friendly dump.
98   ///
99   /// If \c M is provided, metadata nodes will be numbered canonically;
100   /// otherwise, pointer addresses are substituted.
101   ///
102   /// Note: this uses an explicit overload instead of default arguments so that
103   /// the nullptr version is easy to call from a debugger.
104   ///
105   /// @{
106   void dump() const;
107   void dump(const Module *M) const;
108   /// @}
109 
110   /// \brief Print.
111   ///
112   /// Prints definition of \c this.
113   ///
114   /// If \c M is provided, metadata nodes will be numbered canonically;
115   /// otherwise, pointer addresses are substituted.
116   /// @{
117   void print(raw_ostream &OS, const Module *M = nullptr,
118              bool IsForDebug = false) const;
119   void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
120              bool IsForDebug = false) const;
121   /// @}
122 
123   /// \brief Print as operand.
124   ///
125   /// Prints reference of \c this.
126   ///
127   /// If \c M is provided, metadata nodes will be numbered canonically;
128   /// otherwise, pointer addresses are substituted.
129   /// @{
130   void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
131   void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
132                       const Module *M = nullptr) const;
133   /// @}
134 };
135 
136 #define HANDLE_METADATA(CLASS) class CLASS;
137 #include "llvm/IR/Metadata.def"
138 
139 // Provide specializations of isa so that we don't need definitions of
140 // subclasses to see if the metadata is a subclass.
141 #define HANDLE_METADATA_LEAF(CLASS)                                            \
142   template <> struct isa_impl<CLASS, Metadata> {                               \
143     static inline bool doit(const Metadata &MD) {                              \
144       return MD.getMetadataID() == Metadata::CLASS##Kind;                      \
145     }                                                                          \
146   };
147 #include "llvm/IR/Metadata.def"
148 
149 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
150   MD.print(OS);
151   return OS;
152 }
153 
154 /// \brief Metadata wrapper in the Value hierarchy.
155 ///
156 /// A member of the \a Value hierarchy to represent a reference to metadata.
157 /// This allows, e.g., instrinsics to have metadata as operands.
158 ///
159 /// Notably, this is the only thing in either hierarchy that is allowed to
160 /// reference \a LocalAsMetadata.
161 class MetadataAsValue : public Value {
162   friend class ReplaceableMetadataImpl;
163   friend class LLVMContextImpl;
164 
165   Metadata *MD;
166 
167   MetadataAsValue(Type *Ty, Metadata *MD);
168   ~MetadataAsValue() override;
169 
170   /// \brief Drop use of metadata (during teardown).
dropUse()171   void dropUse() { MD = nullptr; }
172 
173 public:
174   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
175   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
getMetadata()176   Metadata *getMetadata() const { return MD; }
177 
classof(const Value * V)178   static bool classof(const Value *V) {
179     return V->getValueID() == MetadataAsValueVal;
180   }
181 
182 private:
183   void handleChangedMetadata(Metadata *MD);
184   void track();
185   void untrack();
186 };
187 
188 /// \brief API for tracking metadata references through RAUW and deletion.
189 ///
190 /// Shared API for updating \a Metadata pointers in subclasses that support
191 /// RAUW.
192 ///
193 /// This API is not meant to be used directly.  See \a TrackingMDRef for a
194 /// user-friendly tracking reference.
195 class MetadataTracking {
196 public:
197   /// \brief Track the reference to metadata.
198   ///
199   /// Register \c MD with \c *MD, if the subclass supports tracking.  If \c *MD
200   /// gets RAUW'ed, \c MD will be updated to the new address.  If \c *MD gets
201   /// deleted, \c MD will be set to \c nullptr.
202   ///
203   /// If tracking isn't supported, \c *MD will not change.
204   ///
205   /// \return true iff tracking is supported by \c MD.
track(Metadata * & MD)206   static bool track(Metadata *&MD) {
207     return track(&MD, *MD, static_cast<Metadata *>(nullptr));
208   }
209 
210   /// \brief Track the reference to metadata for \a Metadata.
211   ///
212   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
213   /// tell it that its operand changed.  This could trigger \c Owner being
214   /// re-uniqued.
track(void * Ref,Metadata & MD,Metadata & Owner)215   static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
216     return track(Ref, MD, &Owner);
217   }
218 
219   /// \brief Track the reference to metadata for \a MetadataAsValue.
220   ///
221   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
222   /// tell it that its operand changed.  This could trigger \c Owner being
223   /// re-uniqued.
track(void * Ref,Metadata & MD,MetadataAsValue & Owner)224   static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
225     return track(Ref, MD, &Owner);
226   }
227 
228   /// \brief Stop tracking a reference to metadata.
229   ///
230   /// Stops \c *MD from tracking \c MD.
untrack(Metadata * & MD)231   static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
232   static void untrack(void *Ref, Metadata &MD);
233 
234   /// \brief Move tracking from one reference to another.
235   ///
236   /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
237   /// except that ownership callbacks are maintained.
238   ///
239   /// Note: it is an error if \c *MD does not equal \c New.
240   ///
241   /// \return true iff tracking is supported by \c MD.
retrack(Metadata * & MD,Metadata * & New)242   static bool retrack(Metadata *&MD, Metadata *&New) {
243     return retrack(&MD, *MD, &New);
244   }
245   static bool retrack(void *Ref, Metadata &MD, void *New);
246 
247   /// \brief Check whether metadata is replaceable.
248   static bool isReplaceable(const Metadata &MD);
249 
250   typedef PointerUnion<MetadataAsValue *, Metadata *> OwnerTy;
251 
252 private:
253   /// \brief Track a reference to metadata for an owner.
254   ///
255   /// Generalized version of tracking.
256   static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
257 };
258 
259 /// \brief Shared implementation of use-lists for replaceable metadata.
260 ///
261 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
262 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
263 /// and \a TempMDNode).
264 class ReplaceableMetadataImpl {
265   friend class MetadataTracking;
266 
267 public:
268   typedef MetadataTracking::OwnerTy OwnerTy;
269 
270 private:
271   LLVMContext &Context;
272   uint64_t NextIndex;
273   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
274 
275 public:
ReplaceableMetadataImpl(LLVMContext & Context)276   ReplaceableMetadataImpl(LLVMContext &Context)
277       : Context(Context), NextIndex(0) {}
278 
~ReplaceableMetadataImpl()279   ~ReplaceableMetadataImpl() {
280     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
281   }
282 
getContext()283   LLVMContext &getContext() const { return Context; }
284 
285   /// \brief Replace all uses of this with MD.
286   ///
287   /// Replace all uses of this with \c MD, which is allowed to be null.
288   void replaceAllUsesWith(Metadata *MD);
289 
290   /// \brief Resolve all uses of this.
291   ///
292   /// Resolve all uses of this, turning off RAUW permanently.  If \c
293   /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
294   /// is resolved.
295   void resolveAllUses(bool ResolveUsers = true);
296 
297 private:
298   void addRef(void *Ref, OwnerTy Owner);
299   void dropRef(void *Ref);
300   void moveRef(void *Ref, void *New, const Metadata &MD);
301 
302   /// Lazily construct RAUW support on MD.
303   ///
304   /// If this is an unresolved MDNode, RAUW support will be created on-demand.
305   /// ValueAsMetadata always has RAUW support.
306   static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
307 
308   /// Get RAUW support on MD, if it exists.
309   static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
310 
311   /// Check whether this node will support RAUW.
312   ///
313   /// Returns \c true unless getOrCreate() would return null.
314   static bool isReplaceable(const Metadata &MD);
315 };
316 
317 /// \brief Value wrapper in the Metadata hierarchy.
318 ///
319 /// This is a custom value handle that allows other metadata to refer to
320 /// classes in the Value hierarchy.
321 ///
322 /// Because of full uniquing support, each value is only wrapped by a single \a
323 /// ValueAsMetadata object, so the lookup maps are far more efficient than
324 /// those using ValueHandleBase.
325 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
326   friend class ReplaceableMetadataImpl;
327   friend class LLVMContextImpl;
328 
329   Value *V;
330 
331   /// \brief Drop users without RAUW (during teardown).
dropUsers()332   void dropUsers() {
333     ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
334   }
335 
336 protected:
ValueAsMetadata(unsigned ID,Value * V)337   ValueAsMetadata(unsigned ID, Value *V)
338       : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
339     assert(V && "Expected valid value");
340   }
341 
342   ~ValueAsMetadata() = default;
343 
344 public:
345   static ValueAsMetadata *get(Value *V);
getConstant(Value * C)346   static ConstantAsMetadata *getConstant(Value *C) {
347     return cast<ConstantAsMetadata>(get(C));
348   }
getLocal(Value * Local)349   static LocalAsMetadata *getLocal(Value *Local) {
350     return cast<LocalAsMetadata>(get(Local));
351   }
352 
353   static ValueAsMetadata *getIfExists(Value *V);
getConstantIfExists(Value * C)354   static ConstantAsMetadata *getConstantIfExists(Value *C) {
355     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
356   }
getLocalIfExists(Value * Local)357   static LocalAsMetadata *getLocalIfExists(Value *Local) {
358     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
359   }
360 
getValue()361   Value *getValue() const { return V; }
getType()362   Type *getType() const { return V->getType(); }
getContext()363   LLVMContext &getContext() const { return V->getContext(); }
364 
365   static void handleDeletion(Value *V);
366   static void handleRAUW(Value *From, Value *To);
367 
368 protected:
369   /// \brief Handle collisions after \a Value::replaceAllUsesWith().
370   ///
371   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
372   /// \a Value gets RAUW'ed and the target already exists, this is used to
373   /// merge the two metadata nodes.
replaceAllUsesWith(Metadata * MD)374   void replaceAllUsesWith(Metadata *MD) {
375     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
376   }
377 
378 public:
classof(const Metadata * MD)379   static bool classof(const Metadata *MD) {
380     return MD->getMetadataID() == LocalAsMetadataKind ||
381            MD->getMetadataID() == ConstantAsMetadataKind;
382   }
383 };
384 
385 class ConstantAsMetadata : public ValueAsMetadata {
386   friend class ValueAsMetadata;
387 
ConstantAsMetadata(Constant * C)388   ConstantAsMetadata(Constant *C)
389       : ValueAsMetadata(ConstantAsMetadataKind, C) {}
390 
391 public:
get(Constant * C)392   static ConstantAsMetadata *get(Constant *C) {
393     return ValueAsMetadata::getConstant(C);
394   }
395 
getIfExists(Constant * C)396   static ConstantAsMetadata *getIfExists(Constant *C) {
397     return ValueAsMetadata::getConstantIfExists(C);
398   }
399 
getValue()400   Constant *getValue() const {
401     return cast<Constant>(ValueAsMetadata::getValue());
402   }
403 
classof(const Metadata * MD)404   static bool classof(const Metadata *MD) {
405     return MD->getMetadataID() == ConstantAsMetadataKind;
406   }
407 };
408 
409 class LocalAsMetadata : public ValueAsMetadata {
410   friend class ValueAsMetadata;
411 
LocalAsMetadata(Value * Local)412   LocalAsMetadata(Value *Local)
413       : ValueAsMetadata(LocalAsMetadataKind, Local) {
414     assert(!isa<Constant>(Local) && "Expected local value");
415   }
416 
417 public:
get(Value * Local)418   static LocalAsMetadata *get(Value *Local) {
419     return ValueAsMetadata::getLocal(Local);
420   }
421 
getIfExists(Value * Local)422   static LocalAsMetadata *getIfExists(Value *Local) {
423     return ValueAsMetadata::getLocalIfExists(Local);
424   }
425 
classof(const Metadata * MD)426   static bool classof(const Metadata *MD) {
427     return MD->getMetadataID() == LocalAsMetadataKind;
428   }
429 };
430 
431 /// \brief Transitional API for extracting constants from Metadata.
432 ///
433 /// This namespace contains transitional functions for metadata that points to
434 /// \a Constants.
435 ///
436 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
437 /// operands could refer to any \a Value.  There's was a lot of code like this:
438 ///
439 /// \code
440 ///     MDNode *N = ...;
441 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
442 /// \endcode
443 ///
444 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
445 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
446 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
447 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
448 /// requires subtle control flow changes.
449 ///
450 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
451 /// so that metadata can refer to numbers without traversing a bridge to the \a
452 /// Value hierarchy.  In this final state, the code above would look like this:
453 ///
454 /// \code
455 ///     MDNode *N = ...;
456 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
457 /// \endcode
458 ///
459 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
460 /// yet, and even once it does, changing each metadata schema to use it is its
461 /// own mini-project.  In the meantime this API prevents us from introducing
462 /// complex and bug-prone control flow that will disappear in the end.  In
463 /// particular, the above code looks like this:
464 ///
465 /// \code
466 ///     MDNode *N = ...;
467 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
468 /// \endcode
469 ///
470 /// The full set of provided functions includes:
471 ///
472 ///   mdconst::hasa                <=> isa
473 ///   mdconst::extract             <=> cast
474 ///   mdconst::extract_or_null     <=> cast_or_null
475 ///   mdconst::dyn_extract         <=> dyn_cast
476 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
477 ///
478 /// The target of the cast must be a subclass of \a Constant.
479 namespace mdconst {
480 
481 namespace detail {
482 
483 template <class T> T &make();
484 template <class T, class Result> struct HasDereference {
485   typedef char Yes[1];
486   typedef char No[2];
487   template <size_t N> struct SFINAE {};
488 
489   template <class U, class V>
490   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
491   template <class U, class V> static No &hasDereference(...);
492 
493   static const bool value =
494       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
495 };
496 template <class V, class M> struct IsValidPointer {
497   static const bool value = std::is_base_of<Constant, V>::value &&
498                             HasDereference<M, const Metadata &>::value;
499 };
500 template <class V, class M> struct IsValidReference {
501   static const bool value = std::is_base_of<Constant, V>::value &&
502                             std::is_convertible<M, const Metadata &>::value;
503 };
504 
505 } // end namespace detail
506 
507 /// \brief Check whether Metadata has a Value.
508 ///
509 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
510 /// type \c X.
511 template <class X, class Y>
512 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
hasa(Y && MD)513 hasa(Y &&MD) {
514   assert(MD && "Null pointer sent into hasa");
515   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
516     return isa<X>(V->getValue());
517   return false;
518 }
519 template <class X, class Y>
520 inline
521     typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
hasa(Y & MD)522     hasa(Y &MD) {
523   return hasa(&MD);
524 }
525 
526 /// \brief Extract a Value from Metadata.
527 ///
528 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
529 template <class X, class Y>
530 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
extract(Y && MD)531 extract(Y &&MD) {
532   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
533 }
534 template <class X, class Y>
535 inline
536     typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
extract(Y & MD)537     extract(Y &MD) {
538   return extract(&MD);
539 }
540 
541 /// \brief Extract a Value from Metadata, allowing null.
542 ///
543 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
544 /// from \c MD, allowing \c MD to be null.
545 template <class X, class Y>
546 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
extract_or_null(Y && MD)547 extract_or_null(Y &&MD) {
548   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
549     return cast<X>(V->getValue());
550   return nullptr;
551 }
552 
553 /// \brief Extract a Value from Metadata, if any.
554 ///
555 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
556 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
557 /// Value it does contain is of the wrong subclass.
558 template <class X, class Y>
559 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
dyn_extract(Y && MD)560 dyn_extract(Y &&MD) {
561   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
562     return dyn_cast<X>(V->getValue());
563   return nullptr;
564 }
565 
566 /// \brief Extract a Value from Metadata, if any, allowing null.
567 ///
568 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
569 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
570 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
571 template <class X, class Y>
572 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
dyn_extract_or_null(Y && MD)573 dyn_extract_or_null(Y &&MD) {
574   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
575     return dyn_cast<X>(V->getValue());
576   return nullptr;
577 }
578 
579 } // end namespace mdconst
580 
581 //===----------------------------------------------------------------------===//
582 /// \brief A single uniqued string.
583 ///
584 /// These are used to efficiently contain a byte sequence for metadata.
585 /// MDString is always unnamed.
586 class MDString : public Metadata {
587   friend class StringMapEntry<MDString>;
588 
589   StringMapEntry<MDString> *Entry;
MDString()590   MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
591 
592 public:
593   MDString(const MDString &) = delete;
594   MDString &operator=(MDString &&) = delete;
595   MDString &operator=(const MDString &) = delete;
596 
597   static MDString *get(LLVMContext &Context, StringRef Str);
get(LLVMContext & Context,const char * Str)598   static MDString *get(LLVMContext &Context, const char *Str) {
599     return get(Context, Str ? StringRef(Str) : StringRef());
600   }
601 
602   StringRef getString() const;
603 
getLength()604   unsigned getLength() const { return (unsigned)getString().size(); }
605 
606   typedef StringRef::iterator iterator;
607 
608   /// \brief Pointer to the first byte of the string.
begin()609   iterator begin() const { return getString().begin(); }
610 
611   /// \brief Pointer to one byte past the end of the string.
end()612   iterator end() const { return getString().end(); }
613 
bytes_begin()614   const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
bytes_end()615   const unsigned char *bytes_end() const { return getString().bytes_end(); }
616 
617   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
classof(const Metadata * MD)618   static bool classof(const Metadata *MD) {
619     return MD->getMetadataID() == MDStringKind;
620   }
621 };
622 
623 /// \brief A collection of metadata nodes that might be associated with a
624 /// memory access used by the alias-analysis infrastructure.
625 struct AAMDNodes {
626   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
627                      MDNode *N = nullptr)
TBAAAAMDNodes628       : TBAA(T), Scope(S), NoAlias(N) {}
629 
630   bool operator==(const AAMDNodes &A) const {
631     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
632   }
633 
634   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
635 
636   explicit operator bool() const { return TBAA || Scope || NoAlias; }
637 
638   /// \brief The tag for type-based alias analysis.
639   MDNode *TBAA;
640 
641   /// \brief The tag for alias scope specification (used with noalias).
642   MDNode *Scope;
643 
644   /// \brief The tag specifying the noalias scope.
645   MDNode *NoAlias;
646 };
647 
648 // Specialize DenseMapInfo for AAMDNodes.
649 template<>
650 struct DenseMapInfo<AAMDNodes> {
651   static inline AAMDNodes getEmptyKey() {
652     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
653                      nullptr, nullptr);
654   }
655 
656   static inline AAMDNodes getTombstoneKey() {
657     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
658                      nullptr, nullptr);
659   }
660 
661   static unsigned getHashValue(const AAMDNodes &Val) {
662     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
663            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
664            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
665   }
666 
667   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
668     return LHS == RHS;
669   }
670 };
671 
672 /// \brief Tracking metadata reference owned by Metadata.
673 ///
674 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
675 /// of \a Metadata, which has the option of registering itself for callbacks to
676 /// re-unique itself.
677 ///
678 /// In particular, this is used by \a MDNode.
679 class MDOperand {
680   Metadata *MD = nullptr;
681 
682 public:
683   MDOperand() = default;
684   MDOperand(MDOperand &&) = delete;
685   MDOperand(const MDOperand &) = delete;
686   MDOperand &operator=(MDOperand &&) = delete;
687   MDOperand &operator=(const MDOperand &) = delete;
688   ~MDOperand() { untrack(); }
689 
690   Metadata *get() const { return MD; }
691   operator Metadata *() const { return get(); }
692   Metadata *operator->() const { return get(); }
693   Metadata &operator*() const { return *get(); }
694 
695   void reset() {
696     untrack();
697     MD = nullptr;
698   }
699   void reset(Metadata *MD, Metadata *Owner) {
700     untrack();
701     this->MD = MD;
702     track(Owner);
703   }
704 
705 private:
706   void track(Metadata *Owner) {
707     if (MD) {
708       if (Owner)
709         MetadataTracking::track(this, *MD, *Owner);
710       else
711         MetadataTracking::track(MD);
712     }
713   }
714 
715   void untrack() {
716     assert(static_cast<void *>(this) == &MD && "Expected same address");
717     if (MD)
718       MetadataTracking::untrack(MD);
719   }
720 };
721 
722 template <> struct simplify_type<MDOperand> {
723   typedef Metadata *SimpleType;
724   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
725 };
726 
727 template <> struct simplify_type<const MDOperand> {
728   typedef Metadata *SimpleType;
729   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
730 };
731 
732 /// \brief Pointer to the context, with optional RAUW support.
733 ///
734 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
735 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
736 class ContextAndReplaceableUses {
737   PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
738 
739 public:
740   ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
741   ContextAndReplaceableUses(
742       std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
743       : Ptr(ReplaceableUses.release()) {
744     assert(getReplaceableUses() && "Expected non-null replaceable uses");
745   }
746   ContextAndReplaceableUses() = delete;
747   ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
748   ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
749   ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
750   ContextAndReplaceableUses &
751   operator=(const ContextAndReplaceableUses &) = delete;
752   ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
753 
754   operator LLVMContext &() { return getContext(); }
755 
756   /// \brief Whether this contains RAUW support.
757   bool hasReplaceableUses() const {
758     return Ptr.is<ReplaceableMetadataImpl *>();
759   }
760 
761   LLVMContext &getContext() const {
762     if (hasReplaceableUses())
763       return getReplaceableUses()->getContext();
764     return *Ptr.get<LLVMContext *>();
765   }
766 
767   ReplaceableMetadataImpl *getReplaceableUses() const {
768     if (hasReplaceableUses())
769       return Ptr.get<ReplaceableMetadataImpl *>();
770     return nullptr;
771   }
772 
773   /// Ensure that this has RAUW support, and then return it.
774   ReplaceableMetadataImpl *getOrCreateReplaceableUses() {
775     if (!hasReplaceableUses())
776       makeReplaceable(llvm::make_unique<ReplaceableMetadataImpl>(getContext()));
777     return getReplaceableUses();
778   }
779 
780   /// \brief Assign RAUW support to this.
781   ///
782   /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
783   /// not be null).
784   void
785   makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
786     assert(ReplaceableUses && "Expected non-null replaceable uses");
787     assert(&ReplaceableUses->getContext() == &getContext() &&
788            "Expected same context");
789     delete getReplaceableUses();
790     Ptr = ReplaceableUses.release();
791   }
792 
793   /// \brief Drop RAUW support.
794   ///
795   /// Cede ownership of RAUW support, returning it.
796   std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
797     assert(hasReplaceableUses() && "Expected to own replaceable uses");
798     std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
799         getReplaceableUses());
800     Ptr = &ReplaceableUses->getContext();
801     return ReplaceableUses;
802   }
803 };
804 
805 struct TempMDNodeDeleter {
806   inline void operator()(MDNode *Node) const;
807 };
808 
809 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
810   typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
811 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
812 #include "llvm/IR/Metadata.def"
813 
814 /// \brief Metadata node.
815 ///
816 /// Metadata nodes can be uniqued, like constants, or distinct.  Temporary
817 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
818 /// until forward references are known.  The basic metadata node is an \a
819 /// MDTuple.
820 ///
821 /// There is limited support for RAUW at construction time.  At construction
822 /// time, if any operand is a temporary node (or an unresolved uniqued node,
823 /// which indicates a transitive temporary operand), the node itself will be
824 /// unresolved.  As soon as all operands become resolved, it will drop RAUW
825 /// support permanently.
826 ///
827 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
828 /// to be called on some member of the cycle once all temporary nodes have been
829 /// replaced.
830 class MDNode : public Metadata {
831   friend class ReplaceableMetadataImpl;
832   friend class LLVMContextImpl;
833 
834   unsigned NumOperands;
835   unsigned NumUnresolved;
836 
837   ContextAndReplaceableUses Context;
838 
839 protected:
840   void *operator new(size_t Size, unsigned NumOps);
841   void operator delete(void *Mem);
842 
843   /// \brief Required by std, but never called.
844   void operator delete(void *, unsigned) {
845     llvm_unreachable("Constructor throws?");
846   }
847 
848   /// \brief Required by std, but never called.
849   void operator delete(void *, unsigned, bool) {
850     llvm_unreachable("Constructor throws?");
851   }
852 
853   MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
854          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
855   ~MDNode() = default;
856 
857   void dropAllReferences();
858 
859   MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
860   MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
861 
862   typedef iterator_range<MDOperand *> mutable_op_range;
863   mutable_op_range mutable_operands() {
864     return mutable_op_range(mutable_begin(), mutable_end());
865   }
866 
867 public:
868   MDNode(const MDNode &) = delete;
869   void operator=(const MDNode &) = delete;
870   void *operator new(size_t) = delete;
871 
872   static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
873   static inline MDTuple *getIfExists(LLVMContext &Context,
874                                      ArrayRef<Metadata *> MDs);
875   static inline MDTuple *getDistinct(LLVMContext &Context,
876                                      ArrayRef<Metadata *> MDs);
877   static inline TempMDTuple getTemporary(LLVMContext &Context,
878                                          ArrayRef<Metadata *> MDs);
879 
880   /// \brief Create a (temporary) clone of this.
881   TempMDNode clone() const;
882 
883   /// \brief Deallocate a node created by getTemporary.
884   ///
885   /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
886   /// references will be reset.
887   static void deleteTemporary(MDNode *N);
888 
889   LLVMContext &getContext() const { return Context.getContext(); }
890 
891   /// \brief Replace a specific operand.
892   void replaceOperandWith(unsigned I, Metadata *New);
893 
894   /// \brief Check if node is fully resolved.
895   ///
896   /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
897   /// this always returns \c true.
898   ///
899   /// If \a isUniqued(), returns \c true if this has already dropped RAUW
900   /// support (because all operands are resolved).
901   ///
902   /// As forward declarations are resolved, their containers should get
903   /// resolved automatically.  However, if this (or one of its operands) is
904   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
905   bool isResolved() const { return !isTemporary() && !NumUnresolved; }
906 
907   bool isUniqued() const { return Storage == Uniqued; }
908   bool isDistinct() const { return Storage == Distinct; }
909   bool isTemporary() const { return Storage == Temporary; }
910 
911   /// \brief RAUW a temporary.
912   ///
913   /// \pre \a isTemporary() must be \c true.
914   void replaceAllUsesWith(Metadata *MD) {
915     assert(isTemporary() && "Expected temporary node");
916     if (Context.hasReplaceableUses())
917       Context.getReplaceableUses()->replaceAllUsesWith(MD);
918   }
919 
920   /// \brief Resolve cycles.
921   ///
922   /// Once all forward declarations have been resolved, force cycles to be
923   /// resolved.
924   ///
925   /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
926   void resolveCycles();
927 
928   /// \brief Replace a temporary node with a permanent one.
929   ///
930   /// Try to create a uniqued version of \c N -- in place, if possible -- and
931   /// return it.  If \c N cannot be uniqued, return a distinct node instead.
932   template <class T>
933   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
934   replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
935     return cast<T>(N.release()->replaceWithPermanentImpl());
936   }
937 
938   /// \brief Replace a temporary node with a uniqued one.
939   ///
940   /// Create a uniqued version of \c N -- in place, if possible -- and return
941   /// it.  Takes ownership of the temporary node.
942   ///
943   /// \pre N does not self-reference.
944   template <class T>
945   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
946   replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
947     return cast<T>(N.release()->replaceWithUniquedImpl());
948   }
949 
950   /// \brief Replace a temporary node with a distinct one.
951   ///
952   /// Create a distinct version of \c N -- in place, if possible -- and return
953   /// it.  Takes ownership of the temporary node.
954   template <class T>
955   static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
956   replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
957     return cast<T>(N.release()->replaceWithDistinctImpl());
958   }
959 
960 private:
961   MDNode *replaceWithPermanentImpl();
962   MDNode *replaceWithUniquedImpl();
963   MDNode *replaceWithDistinctImpl();
964 
965 protected:
966   /// \brief Set an operand.
967   ///
968   /// Sets the operand directly, without worrying about uniquing.
969   void setOperand(unsigned I, Metadata *New);
970 
971   void storeDistinctInContext();
972   template <class T, class StoreT>
973   static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
974   template <class T> static T *storeImpl(T *N, StorageType Storage);
975 
976 private:
977   void handleChangedOperand(void *Ref, Metadata *New);
978 
979   /// Resolve a unique, unresolved node.
980   void resolve();
981 
982   /// Drop RAUW support, if any.
983   void dropReplaceableUses();
984 
985   void resolveAfterOperandChange(Metadata *Old, Metadata *New);
986   void decrementUnresolvedOperandCount();
987   void countUnresolvedOperands();
988 
989   /// \brief Mutate this to be "uniqued".
990   ///
991   /// Mutate this so that \a isUniqued().
992   /// \pre \a isTemporary().
993   /// \pre already added to uniquing set.
994   void makeUniqued();
995 
996   /// \brief Mutate this to be "distinct".
997   ///
998   /// Mutate this so that \a isDistinct().
999   /// \pre \a isTemporary().
1000   void makeDistinct();
1001 
1002   void deleteAsSubclass();
1003   MDNode *uniquify();
1004   void eraseFromStore();
1005 
1006   template <class NodeTy> struct HasCachedHash;
1007   template <class NodeTy>
1008   static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1009     N->recalculateHash();
1010   }
1011   template <class NodeTy>
1012   static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1013   template <class NodeTy>
1014   static void dispatchResetHash(NodeTy *N, std::true_type) {
1015     N->setHash(0);
1016   }
1017   template <class NodeTy>
1018   static void dispatchResetHash(NodeTy *, std::false_type) {}
1019 
1020 public:
1021   typedef const MDOperand *op_iterator;
1022   typedef iterator_range<op_iterator> op_range;
1023 
1024   op_iterator op_begin() const {
1025     return const_cast<MDNode *>(this)->mutable_begin();
1026   }
1027 
1028   op_iterator op_end() const {
1029     return const_cast<MDNode *>(this)->mutable_end();
1030   }
1031 
1032   op_range operands() const { return op_range(op_begin(), op_end()); }
1033 
1034   const MDOperand &getOperand(unsigned I) const {
1035     assert(I < NumOperands && "Out of range");
1036     return op_begin()[I];
1037   }
1038 
1039   /// \brief Return number of MDNode operands.
1040   unsigned getNumOperands() const { return NumOperands; }
1041 
1042   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
1043   static bool classof(const Metadata *MD) {
1044     switch (MD->getMetadataID()) {
1045     default:
1046       return false;
1047 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1048   case CLASS##Kind:                                                            \
1049     return true;
1050 #include "llvm/IR/Metadata.def"
1051     }
1052   }
1053 
1054   /// \brief Check whether MDNode is a vtable access.
1055   bool isTBAAVtableAccess() const;
1056 
1057   /// \brief Methods for metadata merging.
1058   static MDNode *concatenate(MDNode *A, MDNode *B);
1059   static MDNode *intersect(MDNode *A, MDNode *B);
1060   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1061   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1062   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1063   static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1064   static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1065 
1066 };
1067 
1068 /// \brief Tuple of metadata.
1069 ///
1070 /// This is the simple \a MDNode arbitrary tuple.  Nodes are uniqued by
1071 /// default based on their operands.
1072 class MDTuple : public MDNode {
1073   friend class LLVMContextImpl;
1074   friend class MDNode;
1075 
1076   MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1077           ArrayRef<Metadata *> Vals)
1078       : MDNode(C, MDTupleKind, Storage, Vals) {
1079     setHash(Hash);
1080   }
1081 
1082   ~MDTuple() { dropAllReferences(); }
1083 
1084   void setHash(unsigned Hash) { SubclassData32 = Hash; }
1085   void recalculateHash();
1086 
1087   static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1088                           StorageType Storage, bool ShouldCreate = true);
1089 
1090   TempMDTuple cloneImpl() const {
1091     return getTemporary(getContext(),
1092                         SmallVector<Metadata *, 4>(op_begin(), op_end()));
1093   }
1094 
1095 public:
1096   /// \brief Get the hash, if any.
1097   unsigned getHash() const { return SubclassData32; }
1098 
1099   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1100     return getImpl(Context, MDs, Uniqued);
1101   }
1102 
1103   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1104     return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1105   }
1106 
1107   /// \brief Return a distinct node.
1108   ///
1109   /// Return a distinct node -- i.e., a node that is not uniqued.
1110   static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1111     return getImpl(Context, MDs, Distinct);
1112   }
1113 
1114   /// \brief Return a temporary node.
1115   ///
1116   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1117   /// not uniqued, may be RAUW'd, and must be manually deleted with
1118   /// deleteTemporary.
1119   static TempMDTuple getTemporary(LLVMContext &Context,
1120                                   ArrayRef<Metadata *> MDs) {
1121     return TempMDTuple(getImpl(Context, MDs, Temporary));
1122   }
1123 
1124   /// \brief Return a (temporary) clone of this.
1125   TempMDTuple clone() const { return cloneImpl(); }
1126 
1127   static bool classof(const Metadata *MD) {
1128     return MD->getMetadataID() == MDTupleKind;
1129   }
1130 };
1131 
1132 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1133   return MDTuple::get(Context, MDs);
1134 }
1135 
1136 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1137   return MDTuple::getIfExists(Context, MDs);
1138 }
1139 
1140 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1141   return MDTuple::getDistinct(Context, MDs);
1142 }
1143 
1144 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1145                                  ArrayRef<Metadata *> MDs) {
1146   return MDTuple::getTemporary(Context, MDs);
1147 }
1148 
1149 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1150   MDNode::deleteTemporary(Node);
1151 }
1152 
1153 /// \brief Typed iterator through MDNode operands.
1154 ///
1155 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1156 /// particular Metadata subclass.
1157 template <class T>
1158 class TypedMDOperandIterator
1159     : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
1160   MDNode::op_iterator I = nullptr;
1161 
1162 public:
1163   TypedMDOperandIterator() = default;
1164   explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1165 
1166   T *operator*() const { return cast_or_null<T>(*I); }
1167 
1168   TypedMDOperandIterator &operator++() {
1169     ++I;
1170     return *this;
1171   }
1172 
1173   TypedMDOperandIterator operator++(int) {
1174     TypedMDOperandIterator Temp(*this);
1175     ++I;
1176     return Temp;
1177   }
1178 
1179   bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1180   bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1181 };
1182 
1183 /// \brief Typed, array-like tuple of metadata.
1184 ///
1185 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1186 /// particular type of metadata.
1187 template <class T> class MDTupleTypedArrayWrapper {
1188   const MDTuple *N = nullptr;
1189 
1190 public:
1191   MDTupleTypedArrayWrapper() = default;
1192   MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1193 
1194   template <class U>
1195   MDTupleTypedArrayWrapper(
1196       const MDTupleTypedArrayWrapper<U> &Other,
1197       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
1198           nullptr)
1199       : N(Other.get()) {}
1200 
1201   template <class U>
1202   explicit MDTupleTypedArrayWrapper(
1203       const MDTupleTypedArrayWrapper<U> &Other,
1204       typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
1205           nullptr)
1206       : N(Other.get()) {}
1207 
1208   explicit operator bool() const { return get(); }
1209   explicit operator MDTuple *() const { return get(); }
1210 
1211   MDTuple *get() const { return const_cast<MDTuple *>(N); }
1212   MDTuple *operator->() const { return get(); }
1213   MDTuple &operator*() const { return *get(); }
1214 
1215   // FIXME: Fix callers and remove condition on N.
1216   unsigned size() const { return N ? N->getNumOperands() : 0u; }
1217   T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1218 
1219   // FIXME: Fix callers and remove condition on N.
1220   typedef TypedMDOperandIterator<T> iterator;
1221   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1222   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1223 };
1224 
1225 #define HANDLE_METADATA(CLASS)                                                 \
1226   typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
1227 #include "llvm/IR/Metadata.def"
1228 
1229 /// Placeholder metadata for operands of distinct MDNodes.
1230 ///
1231 /// This is a lightweight placeholder for an operand of a distinct node.  It's
1232 /// purpose is to help track forward references when creating a distinct node.
1233 /// This allows distinct nodes involved in a cycle to be constructed before
1234 /// their operands without requiring a heavyweight temporary node with
1235 /// full-blown RAUW support.
1236 ///
1237 /// Each placeholder supports only a single MDNode user.  Clients should pass
1238 /// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1239 /// should be replaced with.
1240 ///
1241 /// While it would be possible to implement move operators, they would be
1242 /// fairly expensive.  Leave them unimplemented to discourage their use
1243 /// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1244 class DistinctMDOperandPlaceholder : public Metadata {
1245   friend class MetadataTracking;
1246 
1247   Metadata **Use = nullptr;
1248 
1249 public:
1250   explicit DistinctMDOperandPlaceholder(unsigned ID)
1251       : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1252     SubclassData32 = ID;
1253   }
1254 
1255   DistinctMDOperandPlaceholder() = delete;
1256   DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&) = delete;
1257   DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &) = delete;
1258 
1259   ~DistinctMDOperandPlaceholder() {
1260     if (Use)
1261       *Use = nullptr;
1262   }
1263 
1264   unsigned getID() const { return SubclassData32; }
1265 
1266   /// Replace the use of this with MD.
1267   void replaceUseWith(Metadata *MD) {
1268     if (!Use)
1269       return;
1270     *Use = MD;
1271     Use = nullptr;
1272   }
1273 };
1274 
1275 //===----------------------------------------------------------------------===//
1276 /// \brief A tuple of MDNodes.
1277 ///
1278 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
1279 /// to modules, have names, and contain lists of MDNodes.
1280 ///
1281 /// TODO: Inherit from Metadata.
1282 class NamedMDNode : public ilist_node<NamedMDNode> {
1283   friend class LLVMContextImpl;
1284   friend class Module;
1285 
1286   std::string Name;
1287   Module *Parent;
1288   void *Operands; // SmallVector<TrackingMDRef, 4>
1289 
1290   void setParent(Module *M) { Parent = M; }
1291 
1292   explicit NamedMDNode(const Twine &N);
1293 
1294   template<class T1, class T2>
1295   class op_iterator_impl :
1296       public std::iterator<std::bidirectional_iterator_tag, T2> {
1297     const NamedMDNode *Node = nullptr;
1298     unsigned Idx = 0;
1299 
1300     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
1301 
1302     friend class NamedMDNode;
1303 
1304   public:
1305     op_iterator_impl() = default;
1306 
1307     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1308     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1309 
1310     op_iterator_impl &operator++() {
1311       ++Idx;
1312       return *this;
1313     }
1314 
1315     op_iterator_impl operator++(int) {
1316       op_iterator_impl tmp(*this);
1317       operator++();
1318       return tmp;
1319     }
1320 
1321     op_iterator_impl &operator--() {
1322       --Idx;
1323       return *this;
1324     }
1325 
1326     op_iterator_impl operator--(int) {
1327       op_iterator_impl tmp(*this);
1328       operator--();
1329       return tmp;
1330     }
1331 
1332     T1 operator*() const { return Node->getOperand(Idx); }
1333   };
1334 
1335 public:
1336   NamedMDNode(const NamedMDNode &) = delete;
1337   ~NamedMDNode();
1338 
1339   /// \brief Drop all references and remove the node from parent module.
1340   void eraseFromParent();
1341 
1342   /// Remove all uses and clear node vector.
1343   void dropAllReferences() { clearOperands(); }
1344   /// Drop all references to this node's operands.
1345   void clearOperands();
1346 
1347   /// \brief Get the module that holds this named metadata collection.
1348   inline Module *getParent() { return Parent; }
1349   inline const Module *getParent() const { return Parent; }
1350 
1351   MDNode *getOperand(unsigned i) const;
1352   unsigned getNumOperands() const;
1353   void addOperand(MDNode *M);
1354   void setOperand(unsigned I, MDNode *New);
1355   StringRef getName() const;
1356   void print(raw_ostream &ROS, bool IsForDebug = false) const;
1357   void print(raw_ostream &ROS, ModuleSlotTracker &MST,
1358              bool IsForDebug = false) const;
1359   void dump() const;
1360 
1361   // ---------------------------------------------------------------------------
1362   // Operand Iterator interface...
1363   //
1364   typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
1365   op_iterator op_begin() { return op_iterator(this, 0); }
1366   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
1367 
1368   typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
1369   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1370   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
1371 
1372   inline iterator_range<op_iterator>  operands() {
1373     return make_range(op_begin(), op_end());
1374   }
1375   inline iterator_range<const_op_iterator> operands() const {
1376     return make_range(op_begin(), op_end());
1377   }
1378 };
1379 
1380 } // end namespace llvm
1381 
1382 #endif // LLVM_IR_METADATA_H
1383