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