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