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