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