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