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