IR: Split Metadata from Value
[oota-llvm.git] / include / llvm / IR / Metadata.h
1 //===-- llvm/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
36 enum LLVMConstants : uint32_t {
37   DEBUG_METADATA_VERSION = 2  // Current debug info version number.
38 };
39
40 /// \brief Root of the metadata hierarchy.
41 ///
42 /// This is a root class for typeless data in the IR.
43 class Metadata {
44   friend class ReplaceableMetadataImpl;
45
46   /// \brief RTTI.
47   const unsigned char SubclassID;
48
49 protected:
50   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
51   bool IsDistinctInContext : 1;
52   // TODO: expose remaining bits to subclasses.
53
54   unsigned short SubclassData16;
55   unsigned SubclassData32;
56
57 public:
58   enum MetadataKind {
59     GenericMDNodeKind,
60     MDNodeFwdDeclKind,
61     ConstantAsMetadataKind,
62     LocalAsMetadataKind,
63     MDStringKind
64   };
65
66 protected:
67   Metadata(unsigned ID)
68       : SubclassID(ID), IsDistinctInContext(false), SubclassData16(0),
69         SubclassData32(0) {}
70   ~Metadata() {}
71
72   /// \brief Store this in a big non-uniqued untyped bucket.
73   bool isStoredDistinctInContext() const { return IsDistinctInContext; }
74
75   /// \brief Default handling of a changed operand, which asserts.
76   ///
77   /// If subclasses pass themselves in as owners to a tracking node reference,
78   /// they must provide an implementation of this method.
79   void handleChangedOperand(void *, Metadata *) {
80     llvm_unreachable("Unimplemented in Metadata subclass");
81   }
82
83 public:
84   unsigned getMetadataID() const { return SubclassID; }
85
86   /// \brief User-friendly dump.
87   void dump() const;
88   void print(raw_ostream &OS) const;
89   void printAsOperand(raw_ostream &OS, bool PrintType = true,
90                       const Module *M = nullptr) const;
91 };
92
93 #define HANDLE_METADATA(CLASS) class CLASS;
94 #include "llvm/IR/Metadata.def"
95
96 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
97   MD.print(OS);
98   return OS;
99 }
100
101 /// \brief Metadata wrapper in the Value hierarchy.
102 ///
103 /// A member of the \a Value hierarchy to represent a reference to metadata.
104 /// This allows, e.g., instrinsics to have metadata as operands.
105 ///
106 /// Notably, this is the only thing in either hierarchy that is allowed to
107 /// reference \a LocalAsMetadata.
108 class MetadataAsValue : public Value {
109   friend class ReplaceableMetadataImpl;
110   friend class LLVMContextImpl;
111
112   Metadata *MD;
113
114   MetadataAsValue(Type *Ty, Metadata *MD);
115   ~MetadataAsValue();
116
117 public:
118   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
119   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
120   Metadata *getMetadata() const { return MD; }
121
122   static bool classof(const Value *V) {
123     return V->getValueID() == MetadataAsValueVal;
124   }
125
126 private:
127   void handleChangedMetadata(Metadata *MD);
128   void track();
129   void untrack();
130 };
131
132 /// \brief Shared implementation of use-lists for replaceable metadata.
133 ///
134 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
135 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
136 /// and \a TempMDNode).
137 class ReplaceableMetadataImpl {
138   friend class MetadataTracking;
139
140 public:
141   typedef MetadataTracking::OwnerTy OwnerTy;
142
143 private:
144   SmallDenseMap<void *, OwnerTy, 4> UseMap;
145
146 public:
147   ~ReplaceableMetadataImpl() {
148     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
149   }
150
151   /// \brief Replace all uses of this with MD.
152   ///
153   /// Replace all uses of this with \c MD, which is allowed to be null.
154   void replaceAllUsesWith(Metadata *MD);
155
156   /// \brief Resolve all uses of this.
157   ///
158   /// Resolve all uses of this, turning off RAUW permanently.  If \c
159   /// ResolveUsers, call \a GenericMDNode::resolve() on any users whose last
160   /// operand is resolved.
161   void resolveAllUses(bool ResolveUsers = true);
162
163 private:
164   void addRef(void *Ref, OwnerTy Owner);
165   void dropRef(void *Ref);
166   void moveRef(void *Ref, void *New, const Metadata &MD);
167
168   static ReplaceableMetadataImpl *get(Metadata &MD);
169 };
170
171 /// \brief Value wrapper in the Metadata hierarchy.
172 ///
173 /// This is a custom value handle that allows other metadata to refer to
174 /// classes in the Value hierarchy.
175 ///
176 /// Because of full uniquing support, each value is only wrapped by a single \a
177 /// ValueAsMetadata object, so the lookup maps are far more efficient than
178 /// those using ValueHandleBase.
179 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
180   friend class ReplaceableMetadataImpl;
181   friend class LLVMContextImpl;
182
183   Value *V;
184
185 protected:
186   ValueAsMetadata(LLVMContext &Context, unsigned ID, Value *V)
187       : Metadata(ID), V(V) {
188     assert(V && "Expected valid value");
189   }
190   ~ValueAsMetadata() {}
191
192 public:
193   static ValueAsMetadata *get(Value *V);
194   static ConstantAsMetadata *getConstant(Value *C) {
195     return cast<ConstantAsMetadata>(get(C));
196   }
197   static LocalAsMetadata *getLocal(Value *Local) {
198     return cast<LocalAsMetadata>(get(Local));
199   }
200
201   static ValueAsMetadata *getIfExists(Value *V);
202   static ConstantAsMetadata *getConstantIfExists(Value *C) {
203     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
204   }
205   static LocalAsMetadata *getLocalIfExists(Value *Local) {
206     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
207   }
208
209   Value *getValue() const { return V; }
210   Type *getType() const { return V->getType(); }
211   LLVMContext &getContext() const { return V->getContext(); }
212
213   static void handleDeletion(Value *V);
214   static void handleRAUW(Value *From, Value *To);
215
216 protected:
217   /// \brief Handle collisions after \a Value::replaceAllUsesWith().
218   ///
219   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
220   /// \a Value gets RAUW'ed and the target already exists, this is used to
221   /// merge the two metadata nodes.
222   void replaceAllUsesWith(Metadata *MD) {
223     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
224   }
225
226 public:
227   static bool classof(const Metadata *MD) {
228     return MD->getMetadataID() == LocalAsMetadataKind ||
229            MD->getMetadataID() == ConstantAsMetadataKind;
230   }
231 };
232
233 class ConstantAsMetadata : public ValueAsMetadata {
234   friend class ValueAsMetadata;
235
236   ConstantAsMetadata(LLVMContext &Context, Constant *C)
237       : ValueAsMetadata(Context, ConstantAsMetadataKind, C) {}
238
239 public:
240   static ConstantAsMetadata *get(Constant *C) {
241     return ValueAsMetadata::getConstant(C);
242   }
243   static ConstantAsMetadata *getIfExists(Constant *C) {
244     return ValueAsMetadata::getConstantIfExists(C);
245   }
246
247   Constant *getValue() const {
248     return cast<Constant>(ValueAsMetadata::getValue());
249   }
250
251   static bool classof(const Metadata *MD) {
252     return MD->getMetadataID() == ConstantAsMetadataKind;
253   }
254 };
255
256 class LocalAsMetadata : public ValueAsMetadata {
257   friend class ValueAsMetadata;
258
259   LocalAsMetadata(LLVMContext &Context, Value *Local)
260       : ValueAsMetadata(Context, LocalAsMetadataKind, Local) {
261     assert(!isa<Constant>(Local) && "Expected local value");
262   }
263
264 public:
265   static LocalAsMetadata *get(Value *Local) {
266     return ValueAsMetadata::getLocal(Local);
267   }
268   static LocalAsMetadata *getIfExists(Value *Local) {
269     return ValueAsMetadata::getLocalIfExists(Local);
270   }
271
272   static bool classof(const Metadata *MD) {
273     return MD->getMetadataID() == LocalAsMetadataKind;
274   }
275 };
276
277 /// \brief Transitional API for extracting constants from Metadata.
278 ///
279 /// This namespace contains transitional functions for metadata that points to
280 /// \a Constants.
281 ///
282 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
283 /// operands could refer to any \a Value.  There's was a lot of code like this:
284 ///
285 /// \code
286 ///     MDNode *N = ...;
287 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
288 /// \endcode
289 ///
290 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
291 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
292 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
293 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
294 /// requires subtle control flow changes.
295 ///
296 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
297 /// so that metadata can refer to numbers without traversing a bridge to the \a
298 /// Value hierarchy.  In this final state, the code above would look like this:
299 ///
300 /// \code
301 ///     MDNode *N = ...;
302 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
303 /// \endcode
304 ///
305 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
306 /// yet, and even once it does, changing each metadata schema to use it is its
307 /// own mini-project.  In the meantime this API prevents us from introducing
308 /// complex and bug-prone control flow that will disappear in the end.  In
309 /// particular, the above code looks like this:
310 ///
311 /// \code
312 ///     MDNode *N = ...;
313 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
314 /// \endcode
315 ///
316 /// The full set of provided functions includes:
317 ///
318 ///   mdconst::hasa                <=> isa
319 ///   mdconst::extract             <=> cast
320 ///   mdconst::extract_or_null     <=> cast_or_null
321 ///   mdconst::dyn_extract         <=> dyn_cast
322 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
323 ///
324 /// The target of the cast must be a subclass of \a Constant.
325 namespace mdconst {
326
327 namespace detail {
328 template <class T> T &make();
329 template <class T, class Result> struct HasDereference {
330   typedef char Yes[1];
331   typedef char No[2];
332   template <size_t N> struct SFINAE {};
333
334   template <class U, class V>
335   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
336   template <class U, class V> static No &hasDereference(...);
337
338   static const bool value =
339       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
340 };
341 template <class V, class M> struct IsValidPointer {
342   static const bool value = std::is_base_of<Constant, V>::value &&
343                             HasDereference<M, const Metadata &>::value;
344 };
345 template <class V, class M> struct IsValidReference {
346   static const bool value = std::is_base_of<Constant, V>::value &&
347                             std::is_convertible<M, const Metadata &>::value;
348 };
349 } // end namespace detail
350
351 /// \brief Check whether Metadata has a Value.
352 ///
353 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
354 /// type \c X.
355 template <class X, class Y>
356 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
357 hasa(Y &&MD) {
358   assert(MD && "Null pointer sent into hasa");
359   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
360     return isa<X>(V->getValue());
361   return false;
362 }
363 template <class X, class Y>
364 inline
365     typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
366     hasa(Y &MD) {
367   return hasa(&MD);
368 }
369
370 /// \brief Extract a Value from Metadata.
371 ///
372 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
373 template <class X, class Y>
374 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
375 extract(Y &&MD) {
376   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
377 }
378 template <class X, class Y>
379 inline
380     typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
381     extract(Y &MD) {
382   return extract(&MD);
383 }
384
385 /// \brief Extract a Value from Metadata, allowing null.
386 ///
387 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
388 /// from \c MD, allowing \c MD to be null.
389 template <class X, class Y>
390 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
391 extract_or_null(Y &&MD) {
392   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
393     return cast<X>(V->getValue());
394   return nullptr;
395 }
396
397 /// \brief Extract a Value from Metadata, if any.
398 ///
399 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
400 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
401 /// Value it does contain is of the wrong subclass.
402 template <class X, class Y>
403 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
404 dyn_extract(Y &&MD) {
405   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
406     return dyn_cast<X>(V->getValue());
407   return nullptr;
408 }
409
410 /// \brief Extract a Value from Metadata, if any, allowing null.
411 ///
412 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
413 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
414 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
415 template <class X, class Y>
416 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
417 dyn_extract_or_null(Y &&MD) {
418   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
419     return dyn_cast<X>(V->getValue());
420   return nullptr;
421 }
422
423 } // end namespace mdconst
424
425 //===----------------------------------------------------------------------===//
426 /// \brief A single uniqued string.
427 ///
428 /// These are used to efficiently contain a byte sequence for metadata.
429 /// MDString is always unnamed.
430 class MDString : public Metadata {
431   friend class StringMapEntry<MDString>;
432
433   MDString(const MDString &) LLVM_DELETED_FUNCTION;
434   MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
435   MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
436
437   StringMapEntry<MDString> *Entry;
438   MDString() : Metadata(MDStringKind), Entry(nullptr) {}
439   MDString(MDString &&) : Metadata(MDStringKind) {}
440
441 public:
442   static MDString *get(LLVMContext &Context, StringRef Str);
443   static MDString *get(LLVMContext &Context, const char *Str) {
444     return get(Context, Str ? StringRef(Str) : StringRef());
445   }
446
447   StringRef getString() const;
448
449   unsigned getLength() const { return (unsigned)getString().size(); }
450
451   typedef StringRef::iterator iterator;
452
453   /// \brief Pointer to the first byte of the string.
454   iterator begin() const { return getString().begin(); }
455
456   /// \brief Pointer to one byte past the end of the string.
457   iterator end() const { return getString().end(); }
458
459   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
460   static bool classof(const Metadata *MD) {
461     return MD->getMetadataID() == MDStringKind;
462   }
463 };
464
465 /// \brief A collection of metadata nodes that might be associated with a
466 /// memory access used by the alias-analysis infrastructure.
467 struct AAMDNodes {
468   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
469                      MDNode *N = nullptr)
470       : TBAA(T), Scope(S), NoAlias(N) {}
471
472   bool operator==(const AAMDNodes &A) const {
473     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
474   }
475
476   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
477
478   LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
479
480   /// \brief The tag for type-based alias analysis.
481   MDNode *TBAA;
482
483   /// \brief The tag for alias scope specification (used with noalias).
484   MDNode *Scope;
485
486   /// \brief The tag specifying the noalias scope.
487   MDNode *NoAlias;
488 };
489
490 // Specialize DenseMapInfo for AAMDNodes.
491 template<>
492 struct DenseMapInfo<AAMDNodes> {
493   static inline AAMDNodes getEmptyKey() {
494     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
495   }
496   static inline AAMDNodes getTombstoneKey() {
497     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
498   }
499   static unsigned getHashValue(const AAMDNodes &Val) {
500     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
501            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
502            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
503   }
504   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
505     return LHS == RHS;
506   }
507 };
508
509 /// \brief Tracking metadata reference owned by Metadata.
510 ///
511 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
512 /// of \a Metadata, which has the option of registering itself for callbacks to
513 /// re-unique itself.
514 ///
515 /// In particular, this is used by \a MDNode.
516 class MDOperand {
517   MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
518   MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
519   MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
520   MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
521
522   Metadata *MD;
523
524 public:
525   MDOperand() : MD(nullptr) {}
526   ~MDOperand() { untrack(); }
527
528   LLVM_EXPLICIT operator bool() const { return get(); }
529   Metadata *get() const { return MD; }
530   operator Metadata *() const { return get(); }
531   Metadata *operator->() const { return get(); }
532   Metadata &operator*() const { return *get(); }
533
534   void reset() {
535     untrack();
536     MD = nullptr;
537   }
538   void reset(Metadata *MD, Metadata *Owner) {
539     untrack();
540     this->MD = MD;
541     track(Owner);
542   }
543
544 private:
545   void track(Metadata *Owner) {
546     if (MD) {
547       if (Owner)
548         MetadataTracking::track(this, *MD, *Owner);
549       else
550         MetadataTracking::track(MD);
551     }
552   }
553   void untrack() {
554     assert(static_cast<void *>(this) == &MD && "Expected same address");
555     if (MD)
556       MetadataTracking::untrack(MD);
557   }
558 };
559
560 template <> struct simplify_type<MDOperand> {
561   typedef Metadata *SimpleType;
562   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
563 };
564
565 template <> struct simplify_type<const MDOperand> {
566   typedef Metadata *SimpleType;
567   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
568 };
569
570 //===----------------------------------------------------------------------===//
571 /// \brief Tuple of metadata.
572 class MDNode : public Metadata {
573   MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
574   void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
575   void *operator new(size_t) LLVM_DELETED_FUNCTION;
576
577   LLVMContext &Context;
578   unsigned NumOperands;
579
580 protected:
581   unsigned MDNodeSubclassData;
582
583   void *operator new(size_t Size, unsigned NumOps);
584
585   /// \brief Required by std, but never called.
586   void operator delete(void *Mem);
587
588   /// \brief Required by std, but never called.
589   void operator delete(void *, unsigned) {
590     llvm_unreachable("Constructor throws?");
591   }
592
593   /// \brief Required by std, but never called.
594   void operator delete(void *, unsigned, bool) {
595     llvm_unreachable("Constructor throws?");
596   }
597
598   MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs);
599   ~MDNode() { dropAllReferences(); }
600
601   void dropAllReferences();
602   void storeDistinctInContext();
603
604   static MDNode *getMDNode(LLVMContext &C, ArrayRef<Metadata *> MDs,
605                            bool Insert = true);
606
607   MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
608   MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
609
610 public:
611   static MDNode *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
612     return getMDNode(Context, MDs, true);
613   }
614   static MDNode *getWhenValsUnresolved(LLVMContext &Context,
615                                        ArrayRef<Metadata *> MDs) {
616     // TODO: Remove this.
617     return get(Context, MDs);
618   }
619
620   static MDNode *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
621     return getMDNode(Context, MDs, false);
622   }
623
624   /// \brief Return a temporary MDNode
625   ///
626   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
627   /// not uniqued, may be RAUW'd, and must be manually deleted with
628   /// deleteTemporary.
629   static MDNodeFwdDecl *getTemporary(LLVMContext &Context,
630                                      ArrayRef<Metadata *> MDs);
631
632   /// \brief Deallocate a node created by getTemporary.
633   ///
634   /// The node must not have any users.
635   static void deleteTemporary(MDNode *N);
636
637   LLVMContext &getContext() const { return Context; }
638
639   /// \brief Replace a specific operand.
640   void replaceOperandWith(unsigned I, Metadata *New);
641
642   /// \brief Check if node is fully resolved.
643   bool isResolved() const;
644
645 protected:
646   /// \brief Set an operand.
647   ///
648   /// Sets the operand directly, without worrying about uniquing.
649   void setOperand(unsigned I, Metadata *New);
650
651 public:
652   typedef const MDOperand *op_iterator;
653   typedef iterator_range<op_iterator> op_range;
654
655   op_iterator op_begin() const {
656     return const_cast<MDNode *>(this)->mutable_begin();
657   }
658   op_iterator op_end() const {
659     return const_cast<MDNode *>(this)->mutable_end();
660   }
661   op_range operands() const { return op_range(op_begin(), op_end()); }
662
663   const MDOperand &getOperand(unsigned I) const {
664     assert(I < NumOperands && "Out of range");
665     return op_begin()[I];
666   }
667
668   /// \brief Return number of MDNode operands.
669   unsigned getNumOperands() const { return NumOperands; }
670
671   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
672   static bool classof(const Metadata *MD) {
673     return MD->getMetadataID() == GenericMDNodeKind ||
674            MD->getMetadataID() == MDNodeFwdDeclKind;
675   }
676
677   /// \brief Check whether MDNode is a vtable access.
678   bool isTBAAVtableAccess() const;
679
680   /// \brief Methods for metadata merging.
681   static MDNode *concatenate(MDNode *A, MDNode *B);
682   static MDNode *intersect(MDNode *A, MDNode *B);
683   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
684   static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
685   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
686   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
687 };
688
689 /// \brief Generic metadata node.
690 ///
691 /// Generic metadata nodes, with opt-out support for uniquing.
692 ///
693 /// Although nodes are uniqued by default, \a GenericMDNode has no support for
694 /// RAUW.  If an operand change (due to RAUW or otherwise) causes a uniquing
695 /// collision, the uniquing bit is dropped.
696 ///
697 /// TODO: Make uniquing opt-out (status: mandatory, sometimes dropped).
698 /// TODO: Drop support for RAUW.
699 class GenericMDNode : public MDNode {
700   friend class Metadata;
701   friend class MDNode;
702   friend class LLVMContextImpl;
703   friend class ReplaceableMetadataImpl;
704
705   /// \brief Support RAUW as long as one of its arguments is replaceable.
706   ///
707   /// If an operand is an \a MDNodeFwdDecl (or a replaceable \a GenericMDNode),
708   /// support RAUW to support uniquing as forward declarations are resolved.
709   /// As soon as operands have been resolved, drop support.
710   ///
711   /// FIXME: Save memory by storing this in a pointer union with the
712   /// LLVMContext, and adding an LLVMContext reference to RMI.
713   std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses;
714
715   GenericMDNode(LLVMContext &C, ArrayRef<Metadata *> Vals);
716   ~GenericMDNode();
717
718   void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
719
720 public:
721   /// \brief Get the hash, if any.
722   unsigned getHash() const { return MDNodeSubclassData; }
723
724   static bool classof(const Metadata *MD) {
725     return MD->getMetadataID() == GenericMDNodeKind;
726   }
727
728   /// \brief Check whether any operands are forward declarations.
729   ///
730   /// Returns \c true as long as any operands (or their operands, etc.) are \a
731   /// MDNodeFwdDecl.
732   ///
733   /// As forward declarations are resolved, their containers should get
734   /// resolved automatically.  However, if this (or one of its operands) is
735   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
736   bool isResolved() const { return !ReplaceableUses; }
737
738   /// \brief Resolve cycles.
739   ///
740   /// Once all forward declarations have been resolved, force cycles to be
741   /// resolved.
742   ///
743   /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl.
744   void resolveCycles();
745
746 private:
747   void handleChangedOperand(void *Ref, Metadata *New);
748
749   bool hasUnresolvedOperands() const { return SubclassData32; }
750   void incrementUnresolvedOperands() { ++SubclassData32; }
751   void decrementUnresolvedOperands() { --SubclassData32; }
752   void resolve();
753 };
754
755 /// \brief Forward declaration of metadata.
756 ///
757 /// Forward declaration of metadata, in the form of a metadata node.  Unlike \a
758 /// GenericMDNode, this class has support for RAUW and is suitable for forward
759 /// references.
760 class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
761   friend class Metadata;
762   friend class MDNode;
763   friend class ReplaceableMetadataImpl;
764
765   MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
766       : MDNode(C, MDNodeFwdDeclKind, Vals) {}
767   ~MDNodeFwdDecl() {}
768
769 public:
770   static bool classof(const Metadata *MD) {
771     return MD->getMetadataID() == MDNodeFwdDeclKind;
772   }
773
774   using ReplaceableMetadataImpl::replaceAllUsesWith;
775 };
776
777 //===----------------------------------------------------------------------===//
778 /// \brief A tuple of MDNodes.
779 ///
780 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
781 /// to modules, have names, and contain lists of MDNodes.
782 ///
783 /// TODO: Inherit from Metadata.
784 class NamedMDNode : public ilist_node<NamedMDNode> {
785   friend class SymbolTableListTraits<NamedMDNode, Module>;
786   friend struct ilist_traits<NamedMDNode>;
787   friend class LLVMContextImpl;
788   friend class Module;
789   NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
790
791   std::string Name;
792   Module *Parent;
793   void *Operands; // SmallVector<TrackingMDRef, 4>
794
795   void setParent(Module *M) { Parent = M; }
796
797   explicit NamedMDNode(const Twine &N);
798
799   template<class T1, class T2>
800   class op_iterator_impl :
801       public std::iterator<std::bidirectional_iterator_tag, T2> {
802     const NamedMDNode *Node;
803     unsigned Idx;
804     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
805
806     friend class NamedMDNode;
807
808   public:
809     op_iterator_impl() : Node(nullptr), Idx(0) { }
810
811     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
812     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
813     op_iterator_impl &operator++() {
814       ++Idx;
815       return *this;
816     }
817     op_iterator_impl operator++(int) {
818       op_iterator_impl tmp(*this);
819       operator++();
820       return tmp;
821     }
822     op_iterator_impl &operator--() {
823       --Idx;
824       return *this;
825     }
826     op_iterator_impl operator--(int) {
827       op_iterator_impl tmp(*this);
828       operator--();
829       return tmp;
830     }
831
832     T1 operator*() const { return Node->getOperand(Idx); }
833   };
834
835 public:
836   /// \brief Drop all references and remove the node from parent module.
837   void eraseFromParent();
838
839   /// \brief Remove all uses and clear node vector.
840   void dropAllReferences();
841
842   ~NamedMDNode();
843
844   /// \brief Get the module that holds this named metadata collection.
845   inline Module *getParent() { return Parent; }
846   inline const Module *getParent() const { return Parent; }
847
848   MDNode *getOperand(unsigned i) const;
849   unsigned getNumOperands() const;
850   void addOperand(MDNode *M);
851   StringRef getName() const;
852   void print(raw_ostream &ROS) const;
853   void dump() const;
854
855   // ---------------------------------------------------------------------------
856   // Operand Iterator interface...
857   //
858   typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
859   op_iterator op_begin() { return op_iterator(this, 0); }
860   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
861
862   typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
863   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
864   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
865
866   inline iterator_range<op_iterator>  operands() {
867     return iterator_range<op_iterator>(op_begin(), op_end());
868   }
869   inline iterator_range<const_op_iterator> operands() const {
870     return iterator_range<const_op_iterator>(op_begin(), op_end());
871   }
872 };
873
874 } // end llvm namespace
875
876 #endif