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