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