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