LLVM API Documentation

Metadata.h
Go to the documentation of this file.
00001 //===-- llvm/Metadata.h - Metadata definitions ------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 /// @file
00011 /// This file contains the declarations for metadata subclasses.
00012 /// They represent the different flavors of metadata that live in LLVM.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #ifndef LLVM_IR_METADATA_H
00017 #define LLVM_IR_METADATA_H
00018 
00019 #include "llvm/ADT/ArrayRef.h"
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/ilist_node.h"
00022 #include "llvm/ADT/iterator_range.h"
00023 #include "llvm/IR/Constant.h"
00024 #include "llvm/IR/MetadataTracking.h"
00025 #include "llvm/IR/Value.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include <type_traits>
00028 
00029 namespace llvm {
00030 class LLVMContext;
00031 class Module;
00032 template<typename ValueSubClass, typename ItemParentClass>
00033   class SymbolTableListTraits;
00034 
00035 
00036 enum LLVMConstants : uint32_t {
00037   DEBUG_METADATA_VERSION = 2  // Current debug info version number.
00038 };
00039 
00040 /// \brief Root of the metadata hierarchy.
00041 ///
00042 /// This is a root class for typeless data in the IR.
00043 class Metadata {
00044   friend class ReplaceableMetadataImpl;
00045 
00046   /// \brief RTTI.
00047   const unsigned char SubclassID;
00048 
00049 protected:
00050   /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
00051   bool IsDistinctInContext : 1;
00052   bool InRAUW : 1;
00053   // TODO: expose remaining bits to subclasses.
00054 
00055   unsigned short SubclassData16;
00056   unsigned SubclassData32;
00057 
00058 public:
00059   enum MetadataKind {
00060     GenericMDNodeKind,
00061     MDNodeFwdDeclKind,
00062     ConstantAsMetadataKind,
00063     LocalAsMetadataKind,
00064     MDStringKind
00065   };
00066 
00067 protected:
00068   Metadata(unsigned ID)
00069       : SubclassID(ID), IsDistinctInContext(false), InRAUW(false),
00070         SubclassData16(0), SubclassData32(0) {}
00071   ~Metadata() {}
00072 
00073   /// \brief Store this in a big non-uniqued untyped bucket.
00074   bool isStoredDistinctInContext() const { return IsDistinctInContext; }
00075 
00076   /// \brief Default handling of a changed operand, which asserts.
00077   ///
00078   /// If subclasses pass themselves in as owners to a tracking node reference,
00079   /// they must provide an implementation of this method.
00080   void handleChangedOperand(void *, Metadata *) {
00081     llvm_unreachable("Unimplemented in Metadata subclass");
00082   }
00083 
00084 public:
00085   unsigned getMetadataID() const { return SubclassID; }
00086 
00087   /// \brief User-friendly dump.
00088   void dump() const;
00089   void print(raw_ostream &OS) const;
00090   void printAsOperand(raw_ostream &OS, bool PrintType = true,
00091                       const Module *M = nullptr) const;
00092 };
00093 
00094 #define HANDLE_METADATA(CLASS) class CLASS;
00095 #include "llvm/IR/Metadata.def"
00096 
00097 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
00098   MD.print(OS);
00099   return OS;
00100 }
00101 
00102 /// \brief Metadata wrapper in the Value hierarchy.
00103 ///
00104 /// A member of the \a Value hierarchy to represent a reference to metadata.
00105 /// This allows, e.g., instrinsics to have metadata as operands.
00106 ///
00107 /// Notably, this is the only thing in either hierarchy that is allowed to
00108 /// reference \a LocalAsMetadata.
00109 class MetadataAsValue : public Value {
00110   friend class ReplaceableMetadataImpl;
00111   friend class LLVMContextImpl;
00112 
00113   Metadata *MD;
00114 
00115   MetadataAsValue(Type *Ty, Metadata *MD);
00116   ~MetadataAsValue();
00117 
00118 public:
00119   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
00120   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
00121   Metadata *getMetadata() const { return MD; }
00122 
00123   static bool classof(const Value *V) {
00124     return V->getValueID() == MetadataAsValueVal;
00125   }
00126 
00127 private:
00128   void handleChangedMetadata(Metadata *MD);
00129   void track();
00130   void untrack();
00131 };
00132 
00133 /// \brief Shared implementation of use-lists for replaceable metadata.
00134 ///
00135 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
00136 /// use-lists and associated API for the two that support it (\a ValueAsMetadata
00137 /// and \a TempMDNode).
00138 class ReplaceableMetadataImpl {
00139   friend class MetadataTracking;
00140 
00141 public:
00142   typedef MetadataTracking::OwnerTy OwnerTy;
00143 
00144 private:
00145   uint64_t NextIndex;
00146   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
00147 
00148 public:
00149   ReplaceableMetadataImpl() : NextIndex(0) {}
00150   ~ReplaceableMetadataImpl() {
00151     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
00152   }
00153 
00154   /// \brief Replace all uses of this with MD.
00155   ///
00156   /// Replace all uses of this with \c MD, which is allowed to be null.
00157   void replaceAllUsesWith(Metadata *MD);
00158 
00159   /// \brief Resolve all uses of this.
00160   ///
00161   /// Resolve all uses of this, turning off RAUW permanently.  If \c
00162   /// ResolveUsers, call \a GenericMDNode::resolve() on any users whose last
00163   /// operand is resolved.
00164   void resolveAllUses(bool ResolveUsers = true);
00165 
00166 private:
00167   void addRef(void *Ref, OwnerTy Owner);
00168   void dropRef(void *Ref);
00169   void moveRef(void *Ref, void *New, const Metadata &MD);
00170 
00171   static ReplaceableMetadataImpl *get(Metadata &MD);
00172 };
00173 
00174 /// \brief Value wrapper in the Metadata hierarchy.
00175 ///
00176 /// This is a custom value handle that allows other metadata to refer to
00177 /// classes in the Value hierarchy.
00178 ///
00179 /// Because of full uniquing support, each value is only wrapped by a single \a
00180 /// ValueAsMetadata object, so the lookup maps are far more efficient than
00181 /// those using ValueHandleBase.
00182 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
00183   friend class ReplaceableMetadataImpl;
00184   friend class LLVMContextImpl;
00185 
00186   Value *V;
00187 
00188 protected:
00189   ValueAsMetadata(LLVMContext &Context, unsigned ID, Value *V)
00190       : Metadata(ID), V(V) {
00191     assert(V && "Expected valid value");
00192   }
00193   ~ValueAsMetadata() {}
00194 
00195 public:
00196   static ValueAsMetadata *get(Value *V);
00197   static ConstantAsMetadata *getConstant(Value *C) {
00198     return cast<ConstantAsMetadata>(get(C));
00199   }
00200   static LocalAsMetadata *getLocal(Value *Local) {
00201     return cast<LocalAsMetadata>(get(Local));
00202   }
00203 
00204   static ValueAsMetadata *getIfExists(Value *V);
00205   static ConstantAsMetadata *getConstantIfExists(Value *C) {
00206     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
00207   }
00208   static LocalAsMetadata *getLocalIfExists(Value *Local) {
00209     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
00210   }
00211 
00212   Value *getValue() const { return V; }
00213   Type *getType() const { return V->getType(); }
00214   LLVMContext &getContext() const { return V->getContext(); }
00215 
00216   static void handleDeletion(Value *V);
00217   static void handleRAUW(Value *From, Value *To);
00218 
00219 protected:
00220   /// \brief Handle collisions after \a Value::replaceAllUsesWith().
00221   ///
00222   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
00223   /// \a Value gets RAUW'ed and the target already exists, this is used to
00224   /// merge the two metadata nodes.
00225   void replaceAllUsesWith(Metadata *MD) {
00226     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
00227   }
00228 
00229 public:
00230   static bool classof(const Metadata *MD) {
00231     return MD->getMetadataID() == LocalAsMetadataKind ||
00232            MD->getMetadataID() == ConstantAsMetadataKind;
00233   }
00234 };
00235 
00236 class ConstantAsMetadata : public ValueAsMetadata {
00237   friend class ValueAsMetadata;
00238 
00239   ConstantAsMetadata(LLVMContext &Context, Constant *C)
00240       : ValueAsMetadata(Context, ConstantAsMetadataKind, C) {}
00241 
00242 public:
00243   static ConstantAsMetadata *get(Constant *C) {
00244     return ValueAsMetadata::getConstant(C);
00245   }
00246   static ConstantAsMetadata *getIfExists(Constant *C) {
00247     return ValueAsMetadata::getConstantIfExists(C);
00248   }
00249 
00250   Constant *getValue() const {
00251     return cast<Constant>(ValueAsMetadata::getValue());
00252   }
00253 
00254   static bool classof(const Metadata *MD) {
00255     return MD->getMetadataID() == ConstantAsMetadataKind;
00256   }
00257 };
00258 
00259 class LocalAsMetadata : public ValueAsMetadata {
00260   friend class ValueAsMetadata;
00261 
00262   LocalAsMetadata(LLVMContext &Context, Value *Local)
00263       : ValueAsMetadata(Context, LocalAsMetadataKind, Local) {
00264     assert(!isa<Constant>(Local) && "Expected local value");
00265   }
00266 
00267 public:
00268   static LocalAsMetadata *get(Value *Local) {
00269     return ValueAsMetadata::getLocal(Local);
00270   }
00271   static LocalAsMetadata *getIfExists(Value *Local) {
00272     return ValueAsMetadata::getLocalIfExists(Local);
00273   }
00274 
00275   static bool classof(const Metadata *MD) {
00276     return MD->getMetadataID() == LocalAsMetadataKind;
00277   }
00278 };
00279 
00280 /// \brief Transitional API for extracting constants from Metadata.
00281 ///
00282 /// This namespace contains transitional functions for metadata that points to
00283 /// \a Constants.
00284 ///
00285 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
00286 /// operands could refer to any \a Value.  There's was a lot of code like this:
00287 ///
00288 /// \code
00289 ///     MDNode *N = ...;
00290 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
00291 /// \endcode
00292 ///
00293 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
00294 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
00295 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
00296 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
00297 /// requires subtle control flow changes.
00298 ///
00299 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
00300 /// so that metadata can refer to numbers without traversing a bridge to the \a
00301 /// Value hierarchy.  In this final state, the code above would look like this:
00302 ///
00303 /// \code
00304 ///     MDNode *N = ...;
00305 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
00306 /// \endcode
00307 ///
00308 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
00309 /// yet, and even once it does, changing each metadata schema to use it is its
00310 /// own mini-project.  In the meantime this API prevents us from introducing
00311 /// complex and bug-prone control flow that will disappear in the end.  In
00312 /// particular, the above code looks like this:
00313 ///
00314 /// \code
00315 ///     MDNode *N = ...;
00316 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
00317 /// \endcode
00318 ///
00319 /// The full set of provided functions includes:
00320 ///
00321 ///   mdconst::hasa                <=> isa
00322 ///   mdconst::extract             <=> cast
00323 ///   mdconst::extract_or_null     <=> cast_or_null
00324 ///   mdconst::dyn_extract         <=> dyn_cast
00325 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
00326 ///
00327 /// The target of the cast must be a subclass of \a Constant.
00328 namespace mdconst {
00329 
00330 namespace detail {
00331 template <class T> T &make();
00332 template <class T, class Result> struct HasDereference {
00333   typedef char Yes[1];
00334   typedef char No[2];
00335   template <size_t N> struct SFINAE {};
00336 
00337   template <class U, class V>
00338   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
00339   template <class U, class V> static No &hasDereference(...);
00340 
00341   static const bool value =
00342       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
00343 };
00344 template <class V, class M> struct IsValidPointer {
00345   static const bool value = std::is_base_of<Constant, V>::value &&
00346                             HasDereference<M, const Metadata &>::value;
00347 };
00348 template <class V, class M> struct IsValidReference {
00349   static const bool value = std::is_base_of<Constant, V>::value &&
00350                             std::is_convertible<M, const Metadata &>::value;
00351 };
00352 } // end namespace detail
00353 
00354 /// \brief Check whether Metadata has a Value.
00355 ///
00356 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
00357 /// type \c X.
00358 template <class X, class Y>
00359 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
00360 hasa(Y &&MD) {
00361   assert(MD && "Null pointer sent into hasa");
00362   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
00363     return isa<X>(V->getValue());
00364   return false;
00365 }
00366 template <class X, class Y>
00367 inline
00368     typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
00369     hasa(Y &MD) {
00370   return hasa(&MD);
00371 }
00372 
00373 /// \brief Extract a Value from Metadata.
00374 ///
00375 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
00376 template <class X, class Y>
00377 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00378 extract(Y &&MD) {
00379   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
00380 }
00381 template <class X, class Y>
00382 inline
00383     typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
00384     extract(Y &MD) {
00385   return extract(&MD);
00386 }
00387 
00388 /// \brief Extract a Value from Metadata, allowing null.
00389 ///
00390 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
00391 /// from \c MD, allowing \c MD to be null.
00392 template <class X, class Y>
00393 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00394 extract_or_null(Y &&MD) {
00395   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
00396     return cast<X>(V->getValue());
00397   return nullptr;
00398 }
00399 
00400 /// \brief Extract a Value from Metadata, if any.
00401 ///
00402 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
00403 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
00404 /// Value it does contain is of the wrong subclass.
00405 template <class X, class Y>
00406 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00407 dyn_extract(Y &&MD) {
00408   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
00409     return dyn_cast<X>(V->getValue());
00410   return nullptr;
00411 }
00412 
00413 /// \brief Extract a Value from Metadata, if any, allowing null.
00414 ///
00415 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
00416 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
00417 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
00418 template <class X, class Y>
00419 inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
00420 dyn_extract_or_null(Y &&MD) {
00421   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
00422     return dyn_cast<X>(V->getValue());
00423   return nullptr;
00424 }
00425 
00426 } // end namespace mdconst
00427 
00428 //===----------------------------------------------------------------------===//
00429 /// \brief A single uniqued string.
00430 ///
00431 /// These are used to efficiently contain a byte sequence for metadata.
00432 /// MDString is always unnamed.
00433 class MDString : public Metadata {
00434   friend class StringMapEntry<MDString>;
00435 
00436   MDString(const MDString &) LLVM_DELETED_FUNCTION;
00437   MDString &operator=(MDString &&) LLVM_DELETED_FUNCTION;
00438   MDString &operator=(const MDString &) LLVM_DELETED_FUNCTION;
00439 
00440   StringMapEntry<MDString> *Entry;
00441   MDString() : Metadata(MDStringKind), Entry(nullptr) {}
00442   MDString(MDString &&) : Metadata(MDStringKind) {}
00443 
00444 public:
00445   static MDString *get(LLVMContext &Context, StringRef Str);
00446   static MDString *get(LLVMContext &Context, const char *Str) {
00447     return get(Context, Str ? StringRef(Str) : StringRef());
00448   }
00449 
00450   StringRef getString() const;
00451 
00452   unsigned getLength() const { return (unsigned)getString().size(); }
00453 
00454   typedef StringRef::iterator iterator;
00455 
00456   /// \brief Pointer to the first byte of the string.
00457   iterator begin() const { return getString().begin(); }
00458 
00459   /// \brief Pointer to one byte past the end of the string.
00460   iterator end() const { return getString().end(); }
00461 
00462   const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
00463   const unsigned char *bytes_end() const { return getString().bytes_end(); }
00464 
00465   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
00466   static bool classof(const Metadata *MD) {
00467     return MD->getMetadataID() == MDStringKind;
00468   }
00469 };
00470 
00471 /// \brief A collection of metadata nodes that might be associated with a
00472 /// memory access used by the alias-analysis infrastructure.
00473 struct AAMDNodes {
00474   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
00475                      MDNode *N = nullptr)
00476       : TBAA(T), Scope(S), NoAlias(N) {}
00477 
00478   bool operator==(const AAMDNodes &A) const {
00479     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
00480   }
00481 
00482   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
00483 
00484   LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
00485 
00486   /// \brief The tag for type-based alias analysis.
00487   MDNode *TBAA;
00488 
00489   /// \brief The tag for alias scope specification (used with noalias).
00490   MDNode *Scope;
00491 
00492   /// \brief The tag specifying the noalias scope.
00493   MDNode *NoAlias;
00494 };
00495 
00496 // Specialize DenseMapInfo for AAMDNodes.
00497 template<>
00498 struct DenseMapInfo<AAMDNodes> {
00499   static inline AAMDNodes getEmptyKey() {
00500     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
00501   }
00502   static inline AAMDNodes getTombstoneKey() {
00503     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
00504   }
00505   static unsigned getHashValue(const AAMDNodes &Val) {
00506     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
00507            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
00508            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
00509   }
00510   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
00511     return LHS == RHS;
00512   }
00513 };
00514 
00515 /// \brief Tracking metadata reference owned by Metadata.
00516 ///
00517 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
00518 /// of \a Metadata, which has the option of registering itself for callbacks to
00519 /// re-unique itself.
00520 ///
00521 /// In particular, this is used by \a MDNode.
00522 class MDOperand {
00523   MDOperand(MDOperand &&) LLVM_DELETED_FUNCTION;
00524   MDOperand(const MDOperand &) LLVM_DELETED_FUNCTION;
00525   MDOperand &operator=(MDOperand &&) LLVM_DELETED_FUNCTION;
00526   MDOperand &operator=(const MDOperand &) LLVM_DELETED_FUNCTION;
00527 
00528   Metadata *MD;
00529 
00530 public:
00531   MDOperand() : MD(nullptr) {}
00532   ~MDOperand() { untrack(); }
00533 
00534   Metadata *get() const { return MD; }
00535   operator Metadata *() const { return get(); }
00536   Metadata *operator->() const { return get(); }
00537   Metadata &operator*() const { return *get(); }
00538 
00539   void reset() {
00540     untrack();
00541     MD = nullptr;
00542   }
00543   void reset(Metadata *MD, Metadata *Owner) {
00544     untrack();
00545     this->MD = MD;
00546     track(Owner);
00547   }
00548 
00549 private:
00550   void track(Metadata *Owner) {
00551     if (MD) {
00552       if (Owner)
00553         MetadataTracking::track(this, *MD, *Owner);
00554       else
00555         MetadataTracking::track(MD);
00556     }
00557   }
00558   void untrack() {
00559     assert(static_cast<void *>(this) == &MD && "Expected same address");
00560     if (MD)
00561       MetadataTracking::untrack(MD);
00562   }
00563 };
00564 
00565 template <> struct simplify_type<MDOperand> {
00566   typedef Metadata *SimpleType;
00567   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
00568 };
00569 
00570 template <> struct simplify_type<const MDOperand> {
00571   typedef Metadata *SimpleType;
00572   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
00573 };
00574 
00575 //===----------------------------------------------------------------------===//
00576 /// \brief Tuple of metadata.
00577 class MDNode : public Metadata {
00578   MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
00579   void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
00580   void *operator new(size_t) LLVM_DELETED_FUNCTION;
00581 
00582   LLVMContext &Context;
00583   unsigned NumOperands;
00584 
00585 protected:
00586   unsigned MDNodeSubclassData;
00587 
00588   void *operator new(size_t Size, unsigned NumOps);
00589 
00590   /// \brief Required by std, but never called.
00591   void operator delete(void *Mem);
00592 
00593   /// \brief Required by std, but never called.
00594   void operator delete(void *, unsigned) {
00595     llvm_unreachable("Constructor throws?");
00596   }
00597 
00598   /// \brief Required by std, but never called.
00599   void operator delete(void *, unsigned, bool) {
00600     llvm_unreachable("Constructor throws?");
00601   }
00602 
00603   MDNode(LLVMContext &Context, unsigned ID, ArrayRef<Metadata *> MDs);
00604   ~MDNode() {}
00605 
00606   void dropAllReferences();
00607   void storeDistinctInContext();
00608 
00609   static MDNode *getMDNode(LLVMContext &C, ArrayRef<Metadata *> MDs,
00610                            bool Insert = true);
00611 
00612   MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
00613   MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
00614 
00615 public:
00616   static MDNode *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
00617     return getMDNode(Context, MDs, true);
00618   }
00619   static MDNode *getWhenValsUnresolved(LLVMContext &Context,
00620                                        ArrayRef<Metadata *> MDs) {
00621     // TODO: Remove this.
00622     return get(Context, MDs);
00623   }
00624 
00625   static MDNode *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
00626     return getMDNode(Context, MDs, false);
00627   }
00628 
00629   /// \brief Return a temporary MDNode
00630   ///
00631   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
00632   /// not uniqued, may be RAUW'd, and must be manually deleted with
00633   /// deleteTemporary.
00634   static MDNodeFwdDecl *getTemporary(LLVMContext &Context,
00635                                      ArrayRef<Metadata *> MDs);
00636 
00637   /// \brief Deallocate a node created by getTemporary.
00638   ///
00639   /// The node must not have any users.
00640   static void deleteTemporary(MDNode *N);
00641 
00642   LLVMContext &getContext() const { return Context; }
00643 
00644   /// \brief Replace a specific operand.
00645   void replaceOperandWith(unsigned I, Metadata *New);
00646 
00647   /// \brief Check if node is fully resolved.
00648   bool isResolved() const;
00649 
00650 protected:
00651   /// \brief Set an operand.
00652   ///
00653   /// Sets the operand directly, without worrying about uniquing.
00654   void setOperand(unsigned I, Metadata *New);
00655 
00656 public:
00657   typedef const MDOperand *op_iterator;
00658   typedef iterator_range<op_iterator> op_range;
00659 
00660   op_iterator op_begin() const {
00661     return const_cast<MDNode *>(this)->mutable_begin();
00662   }
00663   op_iterator op_end() const {
00664     return const_cast<MDNode *>(this)->mutable_end();
00665   }
00666   op_range operands() const { return op_range(op_begin(), op_end()); }
00667 
00668   const MDOperand &getOperand(unsigned I) const {
00669     assert(I < NumOperands && "Out of range");
00670     return op_begin()[I];
00671   }
00672 
00673   /// \brief Return number of MDNode operands.
00674   unsigned getNumOperands() const { return NumOperands; }
00675 
00676   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
00677   static bool classof(const Metadata *MD) {
00678     return MD->getMetadataID() == GenericMDNodeKind ||
00679            MD->getMetadataID() == MDNodeFwdDeclKind;
00680   }
00681 
00682   /// \brief Check whether MDNode is a vtable access.
00683   bool isTBAAVtableAccess() const;
00684 
00685   /// \brief Methods for metadata merging.
00686   static MDNode *concatenate(MDNode *A, MDNode *B);
00687   static MDNode *intersect(MDNode *A, MDNode *B);
00688   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
00689   static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
00690   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
00691   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
00692 };
00693 
00694 /// \brief Generic metadata node.
00695 ///
00696 /// Generic metadata nodes, with opt-out support for uniquing.
00697 ///
00698 /// Although nodes are uniqued by default, \a GenericMDNode has no support for
00699 /// RAUW.  If an operand change (due to RAUW or otherwise) causes a uniquing
00700 /// collision, the uniquing bit is dropped.
00701 ///
00702 /// TODO: Make uniquing opt-out (status: mandatory, sometimes dropped).
00703 /// TODO: Drop support for RAUW.
00704 class GenericMDNode : public MDNode {
00705   friend class Metadata;
00706   friend class MDNode;
00707   friend class LLVMContextImpl;
00708   friend class ReplaceableMetadataImpl;
00709 
00710   /// \brief Support RAUW as long as one of its arguments is replaceable.
00711   ///
00712   /// If an operand is an \a MDNodeFwdDecl (or a replaceable \a GenericMDNode),
00713   /// support RAUW to support uniquing as forward declarations are resolved.
00714   /// As soon as operands have been resolved, drop support.
00715   ///
00716   /// FIXME: Save memory by storing this in a pointer union with the
00717   /// LLVMContext, and adding an LLVMContext reference to RMI.
00718   std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses;
00719 
00720   GenericMDNode(LLVMContext &C, ArrayRef<Metadata *> Vals);
00721   ~GenericMDNode();
00722 
00723   void setHash(unsigned Hash) { MDNodeSubclassData = Hash; }
00724 
00725 public:
00726   /// \brief Get the hash, if any.
00727   unsigned getHash() const { return MDNodeSubclassData; }
00728 
00729   static bool classof(const Metadata *MD) {
00730     return MD->getMetadataID() == GenericMDNodeKind;
00731   }
00732 
00733   /// \brief Check whether any operands are forward declarations.
00734   ///
00735   /// Returns \c true as long as any operands (or their operands, etc.) are \a
00736   /// MDNodeFwdDecl.
00737   ///
00738   /// As forward declarations are resolved, their containers should get
00739   /// resolved automatically.  However, if this (or one of its operands) is
00740   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
00741   bool isResolved() const { return !ReplaceableUses; }
00742 
00743   /// \brief Resolve cycles.
00744   ///
00745   /// Once all forward declarations have been resolved, force cycles to be
00746   /// resolved.
00747   ///
00748   /// \pre No operands (or operands' operands, etc.) are \a MDNodeFwdDecl.
00749   void resolveCycles();
00750 
00751 private:
00752   void handleChangedOperand(void *Ref, Metadata *New);
00753 
00754   bool hasUnresolvedOperands() const { return SubclassData32; }
00755   void incrementUnresolvedOperands() { ++SubclassData32; }
00756   void decrementUnresolvedOperands() { --SubclassData32; }
00757   void resolve();
00758 };
00759 
00760 /// \brief Forward declaration of metadata.
00761 ///
00762 /// Forward declaration of metadata, in the form of a metadata node.  Unlike \a
00763 /// GenericMDNode, this class has support for RAUW and is suitable for forward
00764 /// references.
00765 class MDNodeFwdDecl : public MDNode, ReplaceableMetadataImpl {
00766   friend class Metadata;
00767   friend class MDNode;
00768   friend class ReplaceableMetadataImpl;
00769 
00770   MDNodeFwdDecl(LLVMContext &C, ArrayRef<Metadata *> Vals)
00771       : MDNode(C, MDNodeFwdDeclKind, Vals) {}
00772   ~MDNodeFwdDecl() { dropAllReferences(); }
00773 
00774 public:
00775   static bool classof(const Metadata *MD) {
00776     return MD->getMetadataID() == MDNodeFwdDeclKind;
00777   }
00778 
00779   using ReplaceableMetadataImpl::replaceAllUsesWith;
00780 };
00781 
00782 //===----------------------------------------------------------------------===//
00783 /// \brief A tuple of MDNodes.
00784 ///
00785 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
00786 /// to modules, have names, and contain lists of MDNodes.
00787 ///
00788 /// TODO: Inherit from Metadata.
00789 class NamedMDNode : public ilist_node<NamedMDNode> {
00790   friend class SymbolTableListTraits<NamedMDNode, Module>;
00791   friend struct ilist_traits<NamedMDNode>;
00792   friend class LLVMContextImpl;
00793   friend class Module;
00794   NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
00795 
00796   std::string Name;
00797   Module *Parent;
00798   void *Operands; // SmallVector<TrackingMDRef, 4>
00799 
00800   void setParent(Module *M) { Parent = M; }
00801 
00802   explicit NamedMDNode(const Twine &N);
00803 
00804   template<class T1, class T2>
00805   class op_iterator_impl :
00806       public std::iterator<std::bidirectional_iterator_tag, T2> {
00807     const NamedMDNode *Node;
00808     unsigned Idx;
00809     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
00810 
00811     friend class NamedMDNode;
00812 
00813   public:
00814     op_iterator_impl() : Node(nullptr), Idx(0) { }
00815 
00816     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
00817     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
00818     op_iterator_impl &operator++() {
00819       ++Idx;
00820       return *this;
00821     }
00822     op_iterator_impl operator++(int) {
00823       op_iterator_impl tmp(*this);
00824       operator++();
00825       return tmp;
00826     }
00827     op_iterator_impl &operator--() {
00828       --Idx;
00829       return *this;
00830     }
00831     op_iterator_impl operator--(int) {
00832       op_iterator_impl tmp(*this);
00833       operator--();
00834       return tmp;
00835     }
00836 
00837     T1 operator*() const { return Node->getOperand(Idx); }
00838   };
00839 
00840 public:
00841   /// \brief Drop all references and remove the node from parent module.
00842   void eraseFromParent();
00843 
00844   /// \brief Remove all uses and clear node vector.
00845   void dropAllReferences();
00846 
00847   ~NamedMDNode();
00848 
00849   /// \brief Get the module that holds this named metadata collection.
00850   inline Module *getParent() { return Parent; }
00851   inline const Module *getParent() const { return Parent; }
00852 
00853   MDNode *getOperand(unsigned i) const;
00854   unsigned getNumOperands() const;
00855   void addOperand(MDNode *M);
00856   StringRef getName() const;
00857   void print(raw_ostream &ROS) const;
00858   void dump() const;
00859 
00860   // ---------------------------------------------------------------------------
00861   // Operand Iterator interface...
00862   //
00863   typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
00864   op_iterator op_begin() { return op_iterator(this, 0); }
00865   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
00866 
00867   typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
00868   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
00869   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
00870 
00871   inline iterator_range<op_iterator>  operands() {
00872     return iterator_range<op_iterator>(op_begin(), op_end());
00873   }
00874   inline iterator_range<const_op_iterator> operands() const {
00875     return iterator_range<const_op_iterator>(op_begin(), op_end());
00876   }
00877 };
00878 
00879 } // end llvm namespace
00880 
00881 #endif