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