LLVM  mainline
Metadata.cpp
Go to the documentation of this file.
00001 //===- Metadata.cpp - Implement Metadata classes --------------------------===//
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 // This file implements the Metadata classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Metadata.h"
00015 #include "LLVMContextImpl.h"
00016 #include "MetadataImpl.h"
00017 #include "SymbolTableListTraitsImpl.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/ADT/SmallString.h"
00022 #include "llvm/ADT/StringMap.h"
00023 #include "llvm/IR/ConstantRange.h"
00024 #include "llvm/IR/DebugInfoMetadata.h"
00025 #include "llvm/IR/Instruction.h"
00026 #include "llvm/IR/LLVMContext.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/ValueHandle.h"
00029 
00030 using namespace llvm;
00031 
00032 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
00033     : Value(Ty, MetadataAsValueVal), MD(MD) {
00034   track();
00035 }
00036 
00037 MetadataAsValue::~MetadataAsValue() {
00038   getType()->getContext().pImpl->MetadataAsValues.erase(MD);
00039   untrack();
00040 }
00041 
00042 /// \brief Canonicalize metadata arguments to intrinsics.
00043 ///
00044 /// To support bitcode upgrades (and assembly semantic sugar) for \a
00045 /// MetadataAsValue, we need to canonicalize certain metadata.
00046 ///
00047 ///   - nullptr is replaced by an empty MDNode.
00048 ///   - An MDNode with a single null operand is replaced by an empty MDNode.
00049 ///   - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
00050 ///
00051 /// This maintains readability of bitcode from when metadata was a type of
00052 /// value, and these bridges were unnecessary.
00053 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
00054                                               Metadata *MD) {
00055   if (!MD)
00056     // !{}
00057     return MDNode::get(Context, None);
00058 
00059   // Return early if this isn't a single-operand MDNode.
00060   auto *N = dyn_cast<MDNode>(MD);
00061   if (!N || N->getNumOperands() != 1)
00062     return MD;
00063 
00064   if (!N->getOperand(0))
00065     // !{}
00066     return MDNode::get(Context, None);
00067 
00068   if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
00069     // Look through the MDNode.
00070     return C;
00071 
00072   return MD;
00073 }
00074 
00075 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
00076   MD = canonicalizeMetadataForValue(Context, MD);
00077   auto *&Entry = Context.pImpl->MetadataAsValues[MD];
00078   if (!Entry)
00079     Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
00080   return Entry;
00081 }
00082 
00083 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
00084                                               Metadata *MD) {
00085   MD = canonicalizeMetadataForValue(Context, MD);
00086   auto &Store = Context.pImpl->MetadataAsValues;
00087   return Store.lookup(MD);
00088 }
00089 
00090 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
00091   LLVMContext &Context = getContext();
00092   MD = canonicalizeMetadataForValue(Context, MD);
00093   auto &Store = Context.pImpl->MetadataAsValues;
00094 
00095   // Stop tracking the old metadata.
00096   Store.erase(this->MD);
00097   untrack();
00098   this->MD = nullptr;
00099 
00100   // Start tracking MD, or RAUW if necessary.
00101   auto *&Entry = Store[MD];
00102   if (Entry) {
00103     replaceAllUsesWith(Entry);
00104     delete this;
00105     return;
00106   }
00107 
00108   this->MD = MD;
00109   track();
00110   Entry = this;
00111 }
00112 
00113 void MetadataAsValue::track() {
00114   if (MD)
00115     MetadataTracking::track(&MD, *MD, *this);
00116 }
00117 
00118 void MetadataAsValue::untrack() {
00119   if (MD)
00120     MetadataTracking::untrack(MD);
00121 }
00122 
00123 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
00124   bool WasInserted =
00125       UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
00126           .second;
00127   (void)WasInserted;
00128   assert(WasInserted && "Expected to add a reference");
00129 
00130   ++NextIndex;
00131   assert(NextIndex != 0 && "Unexpected overflow");
00132 }
00133 
00134 void ReplaceableMetadataImpl::dropRef(void *Ref) {
00135   bool WasErased = UseMap.erase(Ref);
00136   (void)WasErased;
00137   assert(WasErased && "Expected to drop a reference");
00138 }
00139 
00140 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
00141                                       const Metadata &MD) {
00142   auto I = UseMap.find(Ref);
00143   assert(I != UseMap.end() && "Expected to move a reference");
00144   auto OwnerAndIndex = I->second;
00145   UseMap.erase(I);
00146   bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
00147   (void)WasInserted;
00148   assert(WasInserted && "Expected to add a reference");
00149 
00150   // Check that the references are direct if there's no owner.
00151   (void)MD;
00152   assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
00153          "Reference without owner must be direct");
00154   assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
00155          "Reference without owner must be direct");
00156 }
00157 
00158 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
00159   assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
00160          "Expected non-temp node");
00161 
00162   if (UseMap.empty())
00163     return;
00164 
00165   // Copy out uses since UseMap will get touched below.
00166   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
00167   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
00168   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
00169     return L.second.second < R.second.second;
00170   });
00171   for (const auto &Pair : Uses) {
00172     // Check that this Ref hasn't disappeared after RAUW (when updating a
00173     // previous Ref).
00174     if (!UseMap.count(Pair.first))
00175       continue;
00176 
00177     OwnerTy Owner = Pair.second.first;
00178     if (!Owner) {
00179       // Update unowned tracking references directly.
00180       Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
00181       Ref = MD;
00182       if (MD)
00183         MetadataTracking::track(Ref);
00184       UseMap.erase(Pair.first);
00185       continue;
00186     }
00187 
00188     // Check for MetadataAsValue.
00189     if (Owner.is<MetadataAsValue *>()) {
00190       Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
00191       continue;
00192     }
00193 
00194     // There's a Metadata owner -- dispatch.
00195     Metadata *OwnerMD = Owner.get<Metadata *>();
00196     switch (OwnerMD->getMetadataID()) {
00197 #define HANDLE_METADATA_LEAF(CLASS)                                            \
00198   case Metadata::CLASS##Kind:                                                  \
00199     cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD);                \
00200     continue;
00201 #include "llvm/IR/Metadata.def"
00202     default:
00203       llvm_unreachable("Invalid metadata subclass");
00204     }
00205   }
00206   assert(UseMap.empty() && "Expected all uses to be replaced");
00207 }
00208 
00209 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
00210   if (UseMap.empty())
00211     return;
00212 
00213   if (!ResolveUsers) {
00214     UseMap.clear();
00215     return;
00216   }
00217 
00218   // Copy out uses since UseMap could get touched below.
00219   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
00220   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
00221   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
00222     return L.second.second < R.second.second;
00223   });
00224   UseMap.clear();
00225   for (const auto &Pair : Uses) {
00226     auto Owner = Pair.second.first;
00227     if (!Owner)
00228       continue;
00229     if (Owner.is<MetadataAsValue *>())
00230       continue;
00231 
00232     // Resolve MDNodes that point at this.
00233     auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
00234     if (!OwnerMD)
00235       continue;
00236     if (OwnerMD->isResolved())
00237       continue;
00238     OwnerMD->decrementUnresolvedOperandCount();
00239   }
00240 }
00241 
00242 static Function *getLocalFunction(Value *V) {
00243   assert(V && "Expected value");
00244   if (auto *A = dyn_cast<Argument>(V))
00245     return A->getParent();
00246   if (BasicBlock *BB = cast<Instruction>(V)->getParent())
00247     return BB->getParent();
00248   return nullptr;
00249 }
00250 
00251 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
00252   assert(V && "Unexpected null Value");
00253 
00254   auto &Context = V->getContext();
00255   auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
00256   if (!Entry) {
00257     assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
00258            "Expected constant or function-local value");
00259     assert(!V->IsUsedByMD &&
00260            "Expected this to be the only metadata use");
00261     V->IsUsedByMD = true;
00262     if (auto *C = dyn_cast<Constant>(V))
00263       Entry = new ConstantAsMetadata(C);
00264     else
00265       Entry = new LocalAsMetadata(V);
00266   }
00267 
00268   return Entry;
00269 }
00270 
00271 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
00272   assert(V && "Unexpected null Value");
00273   return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
00274 }
00275 
00276 void ValueAsMetadata::handleDeletion(Value *V) {
00277   assert(V && "Expected valid value");
00278 
00279   auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
00280   auto I = Store.find(V);
00281   if (I == Store.end())
00282     return;
00283 
00284   // Remove old entry from the map.
00285   ValueAsMetadata *MD = I->second;
00286   assert(MD && "Expected valid metadata");
00287   assert(MD->getValue() == V && "Expected valid mapping");
00288   Store.erase(I);
00289 
00290   // Delete the metadata.
00291   MD->replaceAllUsesWith(nullptr);
00292   delete MD;
00293 }
00294 
00295 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
00296   assert(From && "Expected valid value");
00297   assert(To && "Expected valid value");
00298   assert(From != To && "Expected changed value");
00299   assert(From->getType() == To->getType() && "Unexpected type change");
00300 
00301   LLVMContext &Context = From->getType()->getContext();
00302   auto &Store = Context.pImpl->ValuesAsMetadata;
00303   auto I = Store.find(From);
00304   if (I == Store.end()) {
00305     assert(!From->IsUsedByMD &&
00306            "Expected From not to be used by metadata");
00307     return;
00308   }
00309 
00310   // Remove old entry from the map.
00311   assert(From->IsUsedByMD &&
00312          "Expected From to be used by metadata");
00313   From->IsUsedByMD = false;
00314   ValueAsMetadata *MD = I->second;
00315   assert(MD && "Expected valid metadata");
00316   assert(MD->getValue() == From && "Expected valid mapping");
00317   Store.erase(I);
00318 
00319   if (isa<LocalAsMetadata>(MD)) {
00320     if (auto *C = dyn_cast<Constant>(To)) {
00321       // Local became a constant.
00322       MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
00323       delete MD;
00324       return;
00325     }
00326     if (getLocalFunction(From) && getLocalFunction(To) &&
00327         getLocalFunction(From) != getLocalFunction(To)) {
00328       // Function changed.
00329       MD->replaceAllUsesWith(nullptr);
00330       delete MD;
00331       return;
00332     }
00333   } else if (!isa<Constant>(To)) {
00334     // Changed to function-local value.
00335     MD->replaceAllUsesWith(nullptr);
00336     delete MD;
00337     return;
00338   }
00339 
00340   auto *&Entry = Store[To];
00341   if (Entry) {
00342     // The target already exists.
00343     MD->replaceAllUsesWith(Entry);
00344     delete MD;
00345     return;
00346   }
00347 
00348   // Update MD in place (and update the map entry).
00349   assert(!To->IsUsedByMD &&
00350          "Expected this to be the only metadata use");
00351   To->IsUsedByMD = true;
00352   MD->V = To;
00353   Entry = MD;
00354 }
00355 
00356 //===----------------------------------------------------------------------===//
00357 // MDString implementation.
00358 //
00359 
00360 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
00361   auto &Store = Context.pImpl->MDStringCache;
00362   auto I = Store.find(Str);
00363   if (I != Store.end())
00364     return &I->second;
00365 
00366   auto *Entry =
00367       StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
00368   bool WasInserted = Store.insert(Entry);
00369   (void)WasInserted;
00370   assert(WasInserted && "Expected entry to be inserted");
00371   Entry->second.Entry = Entry;
00372   return &Entry->second;
00373 }
00374 
00375 StringRef MDString::getString() const {
00376   assert(Entry && "Expected to find string map entry");
00377   return Entry->first();
00378 }
00379 
00380 //===----------------------------------------------------------------------===//
00381 // MDNode implementation.
00382 //
00383 
00384 // Assert that the MDNode types will not be unaligned by the objects
00385 // prepended to them.
00386 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00387   static_assert(                                                               \
00388       llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment,   \
00389       "Alignment is insufficient after objects prepended to " #CLASS);
00390 #include "llvm/IR/Metadata.def"
00391 
00392 void *MDNode::operator new(size_t Size, unsigned NumOps) {
00393   size_t OpSize = NumOps * sizeof(MDOperand);
00394   // uint64_t is the most aligned type we need support (ensured by static_assert
00395   // above)
00396   OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
00397   void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
00398   MDOperand *O = static_cast<MDOperand *>(Ptr);
00399   for (MDOperand *E = O - NumOps; O != E; --O)
00400     (void)new (O - 1) MDOperand;
00401   return Ptr;
00402 }
00403 
00404 void MDNode::operator delete(void *Mem) {
00405   MDNode *N = static_cast<MDNode *>(Mem);
00406   size_t OpSize = N->NumOperands * sizeof(MDOperand);
00407   OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
00408 
00409   MDOperand *O = static_cast<MDOperand *>(Mem);
00410   for (MDOperand *E = O - N->NumOperands; O != E; --O)
00411     (O - 1)->~MDOperand();
00412   ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
00413 }
00414 
00415 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
00416                ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
00417     : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
00418       NumUnresolved(0), Context(Context) {
00419   unsigned Op = 0;
00420   for (Metadata *MD : Ops1)
00421     setOperand(Op++, MD);
00422   for (Metadata *MD : Ops2)
00423     setOperand(Op++, MD);
00424 
00425   if (isDistinct())
00426     return;
00427 
00428   if (isUniqued())
00429     // Check whether any operands are unresolved, requiring re-uniquing.  If
00430     // not, don't support RAUW.
00431     if (!countUnresolvedOperands())
00432       return;
00433 
00434   this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
00435 }
00436 
00437 TempMDNode MDNode::clone() const {
00438   switch (getMetadataID()) {
00439   default:
00440     llvm_unreachable("Invalid MDNode subclass");
00441 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00442   case CLASS##Kind:                                                            \
00443     return cast<CLASS>(this)->cloneImpl();
00444 #include "llvm/IR/Metadata.def"
00445   }
00446 }
00447 
00448 static bool isOperandUnresolved(Metadata *Op) {
00449   if (auto *N = dyn_cast_or_null<MDNode>(Op))
00450     return !N->isResolved();
00451   return false;
00452 }
00453 
00454 unsigned MDNode::countUnresolvedOperands() {
00455   assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
00456   NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
00457   return NumUnresolved;
00458 }
00459 
00460 void MDNode::makeUniqued() {
00461   assert(isTemporary() && "Expected this to be temporary");
00462   assert(!isResolved() && "Expected this to be unresolved");
00463 
00464   // Enable uniquing callbacks.
00465   for (auto &Op : mutable_operands())
00466     Op.reset(Op.get(), this);
00467 
00468   // Make this 'uniqued'.
00469   Storage = Uniqued;
00470   if (!countUnresolvedOperands())
00471     resolve();
00472 
00473   assert(isUniqued() && "Expected this to be uniqued");
00474 }
00475 
00476 void MDNode::makeDistinct() {
00477   assert(isTemporary() && "Expected this to be temporary");
00478   assert(!isResolved() && "Expected this to be unresolved");
00479 
00480   // Pretend to be uniqued, resolve the node, and then store in distinct table.
00481   Storage = Uniqued;
00482   resolve();
00483   storeDistinctInContext();
00484 
00485   assert(isDistinct() && "Expected this to be distinct");
00486   assert(isResolved() && "Expected this to be resolved");
00487 }
00488 
00489 void MDNode::resolve() {
00490   assert(isUniqued() && "Expected this to be uniqued");
00491   assert(!isResolved() && "Expected this to be unresolved");
00492 
00493   // Move the map, so that this immediately looks resolved.
00494   auto Uses = Context.takeReplaceableUses();
00495   NumUnresolved = 0;
00496   assert(isResolved() && "Expected this to be resolved");
00497 
00498   // Drop RAUW support.
00499   Uses->resolveAllUses();
00500 }
00501 
00502 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
00503   assert(NumUnresolved != 0 && "Expected unresolved operands");
00504 
00505   // Check if an operand was resolved.
00506   if (!isOperandUnresolved(Old)) {
00507     if (isOperandUnresolved(New))
00508       // An operand was un-resolved!
00509       ++NumUnresolved;
00510   } else if (!isOperandUnresolved(New))
00511     decrementUnresolvedOperandCount();
00512 }
00513 
00514 void MDNode::decrementUnresolvedOperandCount() {
00515   if (!--NumUnresolved)
00516     // Last unresolved operand has just been resolved.
00517     resolve();
00518 }
00519 
00520 void MDNode::resolveCycles() {
00521   if (isResolved())
00522     return;
00523 
00524   // Resolve this node immediately.
00525   resolve();
00526 
00527   // Resolve all operands.
00528   for (const auto &Op : operands()) {
00529     auto *N = dyn_cast_or_null<MDNode>(Op);
00530     if (!N)
00531       continue;
00532 
00533     assert(!N->isTemporary() &&
00534            "Expected all forward declarations to be resolved");
00535     if (!N->isResolved())
00536       N->resolveCycles();
00537   }
00538 }
00539 
00540 static bool hasSelfReference(MDNode *N) {
00541   for (Metadata *MD : N->operands())
00542     if (MD == N)
00543       return true;
00544   return false;
00545 }
00546 
00547 MDNode *MDNode::replaceWithPermanentImpl() {
00548   if (hasSelfReference(this))
00549     return replaceWithDistinctImpl();
00550   return replaceWithUniquedImpl();
00551 }
00552 
00553 MDNode *MDNode::replaceWithUniquedImpl() {
00554   // Try to uniquify in place.
00555   MDNode *UniquedNode = uniquify();
00556 
00557   if (UniquedNode == this) {
00558     makeUniqued();
00559     return this;
00560   }
00561 
00562   // Collision, so RAUW instead.
00563   replaceAllUsesWith(UniquedNode);
00564   deleteAsSubclass();
00565   return UniquedNode;
00566 }
00567 
00568 MDNode *MDNode::replaceWithDistinctImpl() {
00569   makeDistinct();
00570   return this;
00571 }
00572 
00573 void MDTuple::recalculateHash() {
00574   setHash(MDTupleInfo::KeyTy::calculateHash(this));
00575 }
00576 
00577 void MDNode::dropAllReferences() {
00578   for (unsigned I = 0, E = NumOperands; I != E; ++I)
00579     setOperand(I, nullptr);
00580   if (!isResolved()) {
00581     Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
00582     (void)Context.takeReplaceableUses();
00583   }
00584 }
00585 
00586 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
00587   unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
00588   assert(Op < getNumOperands() && "Expected valid operand");
00589 
00590   if (!isUniqued()) {
00591     // This node is not uniqued.  Just set the operand and be done with it.
00592     setOperand(Op, New);
00593     return;
00594   }
00595 
00596   // This node is uniqued.
00597   eraseFromStore();
00598 
00599   Metadata *Old = getOperand(Op);
00600   setOperand(Op, New);
00601 
00602   // Drop uniquing for self-reference cycles.
00603   if (New == this) {
00604     if (!isResolved())
00605       resolve();
00606     storeDistinctInContext();
00607     return;
00608   }
00609 
00610   // Re-unique the node.
00611   auto *Uniqued = uniquify();
00612   if (Uniqued == this) {
00613     if (!isResolved())
00614       resolveAfterOperandChange(Old, New);
00615     return;
00616   }
00617 
00618   // Collision.
00619   if (!isResolved()) {
00620     // Still unresolved, so RAUW.
00621     //
00622     // First, clear out all operands to prevent any recursion (similar to
00623     // dropAllReferences(), but we still need the use-list).
00624     for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
00625       setOperand(O, nullptr);
00626     Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
00627     deleteAsSubclass();
00628     return;
00629   }
00630 
00631   // Store in non-uniqued form if RAUW isn't possible.
00632   storeDistinctInContext();
00633 }
00634 
00635 void MDNode::deleteAsSubclass() {
00636   switch (getMetadataID()) {
00637   default:
00638     llvm_unreachable("Invalid subclass of MDNode");
00639 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00640   case CLASS##Kind:                                                            \
00641     delete cast<CLASS>(this);                                                  \
00642     break;
00643 #include "llvm/IR/Metadata.def"
00644   }
00645 }
00646 
00647 template <class T, class InfoT>
00648 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
00649   if (T *U = getUniqued(Store, N))
00650     return U;
00651 
00652   Store.insert(N);
00653   return N;
00654 }
00655 
00656 template <class NodeTy> struct MDNode::HasCachedHash {
00657   typedef char Yes[1];
00658   typedef char No[2];
00659   template <class U, U Val> struct SFINAE {};
00660 
00661   template <class U>
00662   static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
00663   template <class U> static No &check(...);
00664 
00665   static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
00666 };
00667 
00668 MDNode *MDNode::uniquify() {
00669   assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
00670 
00671   // Try to insert into uniquing store.
00672   switch (getMetadataID()) {
00673   default:
00674     llvm_unreachable("Invalid subclass of MDNode");
00675 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00676   case CLASS##Kind: {                                                          \
00677     CLASS *SubclassThis = cast<CLASS>(this);                                   \
00678     std::integral_constant<bool, HasCachedHash<CLASS>::value>                  \
00679         ShouldRecalculateHash;                                                 \
00680     dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash);              \
00681     return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s);           \
00682   }
00683 #include "llvm/IR/Metadata.def"
00684   }
00685 }
00686 
00687 void MDNode::eraseFromStore() {
00688   switch (getMetadataID()) {
00689   default:
00690     llvm_unreachable("Invalid subclass of MDNode");
00691 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00692   case CLASS##Kind:                                                            \
00693     getContext().pImpl->CLASS##s.erase(cast<CLASS>(this));                     \
00694     break;
00695 #include "llvm/IR/Metadata.def"
00696   }
00697 }
00698 
00699 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
00700                           StorageType Storage, bool ShouldCreate) {
00701   unsigned Hash = 0;
00702   if (Storage == Uniqued) {
00703     MDTupleInfo::KeyTy Key(MDs);
00704     if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
00705       return N;
00706     if (!ShouldCreate)
00707       return nullptr;
00708     Hash = Key.getHash();
00709   } else {
00710     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
00711   }
00712 
00713   return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
00714                    Storage, Context.pImpl->MDTuples);
00715 }
00716 
00717 void MDNode::deleteTemporary(MDNode *N) {
00718   assert(N->isTemporary() && "Expected temporary node");
00719   N->replaceAllUsesWith(nullptr);
00720   N->deleteAsSubclass();
00721 }
00722 
00723 void MDNode::storeDistinctInContext() {
00724   assert(isResolved() && "Expected resolved nodes");
00725   Storage = Distinct;
00726 
00727   // Reset the hash.
00728   switch (getMetadataID()) {
00729   default:
00730     llvm_unreachable("Invalid subclass of MDNode");
00731 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00732   case CLASS##Kind: {                                                          \
00733     std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
00734     dispatchResetHash(cast<CLASS>(this), ShouldResetHash);                     \
00735     break;                                                                     \
00736   }
00737 #include "llvm/IR/Metadata.def"
00738   }
00739 
00740   getContext().pImpl->DistinctMDNodes.insert(this);
00741 }
00742 
00743 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
00744   if (getOperand(I) == New)
00745     return;
00746 
00747   if (!isUniqued()) {
00748     setOperand(I, New);
00749     return;
00750   }
00751 
00752   handleChangedOperand(mutable_begin() + I, New);
00753 }
00754 
00755 void MDNode::setOperand(unsigned I, Metadata *New) {
00756   assert(I < NumOperands);
00757   mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
00758 }
00759 
00760 /// \brief Get a node, or a self-reference that looks like it.
00761 ///
00762 /// Special handling for finding self-references, for use by \a
00763 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
00764 /// when self-referencing nodes were still uniqued.  If the first operand has
00765 /// the same operands as \c Ops, return the first operand instead.
00766 static MDNode *getOrSelfReference(LLVMContext &Context,
00767                                   ArrayRef<Metadata *> Ops) {
00768   if (!Ops.empty())
00769     if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
00770       if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
00771         for (unsigned I = 1, E = Ops.size(); I != E; ++I)
00772           if (Ops[I] != N->getOperand(I))
00773             return MDNode::get(Context, Ops);
00774         return N;
00775       }
00776 
00777   return MDNode::get(Context, Ops);
00778 }
00779 
00780 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
00781   if (!A)
00782     return B;
00783   if (!B)
00784     return A;
00785 
00786   SmallVector<Metadata *, 4> MDs;
00787   MDs.reserve(A->getNumOperands() + B->getNumOperands());
00788   MDs.append(A->op_begin(), A->op_end());
00789   MDs.append(B->op_begin(), B->op_end());
00790 
00791   // FIXME: This preserves long-standing behaviour, but is it really the right
00792   // behaviour?  Or was that an unintended side-effect of node uniquing?
00793   return getOrSelfReference(A->getContext(), MDs);
00794 }
00795 
00796 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
00797   if (!A || !B)
00798     return nullptr;
00799 
00800   SmallVector<Metadata *, 4> MDs;
00801   for (Metadata *MD : A->operands())
00802     if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
00803       MDs.push_back(MD);
00804 
00805   // FIXME: This preserves long-standing behaviour, but is it really the right
00806   // behaviour?  Or was that an unintended side-effect of node uniquing?
00807   return getOrSelfReference(A->getContext(), MDs);
00808 }
00809 
00810 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
00811   if (!A || !B)
00812     return nullptr;
00813 
00814   SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
00815   for (Metadata *MD : A->operands())
00816     if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
00817       MDs.push_back(MD);
00818 
00819   // FIXME: This preserves long-standing behaviour, but is it really the right
00820   // behaviour?  Or was that an unintended side-effect of node uniquing?
00821   return getOrSelfReference(A->getContext(), MDs);
00822 }
00823 
00824 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
00825   if (!A || !B)
00826     return nullptr;
00827 
00828   APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
00829   APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
00830   if (AVal.compare(BVal) == APFloat::cmpLessThan)
00831     return A;
00832   return B;
00833 }
00834 
00835 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
00836   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
00837 }
00838 
00839 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
00840   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
00841 }
00842 
00843 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
00844                           ConstantInt *Low, ConstantInt *High) {
00845   ConstantRange NewRange(Low->getValue(), High->getValue());
00846   unsigned Size = EndPoints.size();
00847   APInt LB = EndPoints[Size - 2]->getValue();
00848   APInt LE = EndPoints[Size - 1]->getValue();
00849   ConstantRange LastRange(LB, LE);
00850   if (canBeMerged(NewRange, LastRange)) {
00851     ConstantRange Union = LastRange.unionWith(NewRange);
00852     Type *Ty = High->getType();
00853     EndPoints[Size - 2] =
00854         cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
00855     EndPoints[Size - 1] =
00856         cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
00857     return true;
00858   }
00859   return false;
00860 }
00861 
00862 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
00863                      ConstantInt *Low, ConstantInt *High) {
00864   if (!EndPoints.empty())
00865     if (tryMergeRange(EndPoints, Low, High))
00866       return;
00867 
00868   EndPoints.push_back(Low);
00869   EndPoints.push_back(High);
00870 }
00871 
00872 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
00873   // Given two ranges, we want to compute the union of the ranges. This
00874   // is slightly complitade by having to combine the intervals and merge
00875   // the ones that overlap.
00876 
00877   if (!A || !B)
00878     return nullptr;
00879 
00880   if (A == B)
00881     return A;
00882 
00883   // First, walk both lists in older of the lower boundary of each interval.
00884   // At each step, try to merge the new interval to the last one we adedd.
00885   SmallVector<ConstantInt *, 4> EndPoints;
00886   int AI = 0;
00887   int BI = 0;
00888   int AN = A->getNumOperands() / 2;
00889   int BN = B->getNumOperands() / 2;
00890   while (AI < AN && BI < BN) {
00891     ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
00892     ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
00893 
00894     if (ALow->getValue().slt(BLow->getValue())) {
00895       addRange(EndPoints, ALow,
00896                mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
00897       ++AI;
00898     } else {
00899       addRange(EndPoints, BLow,
00900                mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
00901       ++BI;
00902     }
00903   }
00904   while (AI < AN) {
00905     addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
00906              mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
00907     ++AI;
00908   }
00909   while (BI < BN) {
00910     addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
00911              mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
00912     ++BI;
00913   }
00914 
00915   // If we have more than 2 ranges (4 endpoints) we have to try to merge
00916   // the last and first ones.
00917   unsigned Size = EndPoints.size();
00918   if (Size > 4) {
00919     ConstantInt *FB = EndPoints[0];
00920     ConstantInt *FE = EndPoints[1];
00921     if (tryMergeRange(EndPoints, FB, FE)) {
00922       for (unsigned i = 0; i < Size - 2; ++i) {
00923         EndPoints[i] = EndPoints[i + 2];
00924       }
00925       EndPoints.resize(Size - 2);
00926     }
00927   }
00928 
00929   // If in the end we have a single range, it is possible that it is now the
00930   // full range. Just drop the metadata in that case.
00931   if (EndPoints.size() == 2) {
00932     ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
00933     if (Range.isFullSet())
00934       return nullptr;
00935   }
00936 
00937   SmallVector<Metadata *, 4> MDs;
00938   MDs.reserve(EndPoints.size());
00939   for (auto *I : EndPoints)
00940     MDs.push_back(ConstantAsMetadata::get(I));
00941   return MDNode::get(A->getContext(), MDs);
00942 }
00943 
00944 //===----------------------------------------------------------------------===//
00945 // NamedMDNode implementation.
00946 //
00947 
00948 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
00949   return *(SmallVector<TrackingMDRef, 4> *)Operands;
00950 }
00951 
00952 NamedMDNode::NamedMDNode(const Twine &N)
00953     : Name(N.str()), Parent(nullptr),
00954       Operands(new SmallVector<TrackingMDRef, 4>()) {}
00955 
00956 NamedMDNode::~NamedMDNode() {
00957   dropAllReferences();
00958   delete &getNMDOps(Operands);
00959 }
00960 
00961 unsigned NamedMDNode::getNumOperands() const {
00962   return (unsigned)getNMDOps(Operands).size();
00963 }
00964 
00965 MDNode *NamedMDNode::getOperand(unsigned i) const {
00966   assert(i < getNumOperands() && "Invalid Operand number!");
00967   auto *N = getNMDOps(Operands)[i].get();
00968   return cast_or_null<MDNode>(N);
00969 }
00970 
00971 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
00972 
00973 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
00974   assert(I < getNumOperands() && "Invalid operand number");
00975   getNMDOps(Operands)[I].reset(New);
00976 }
00977 
00978 void NamedMDNode::eraseFromParent() {
00979   getParent()->eraseNamedMetadata(this);
00980 }
00981 
00982 void NamedMDNode::dropAllReferences() {
00983   getNMDOps(Operands).clear();
00984 }
00985 
00986 StringRef NamedMDNode::getName() const {
00987   return StringRef(Name);
00988 }
00989 
00990 //===----------------------------------------------------------------------===//
00991 // Instruction Metadata method implementations.
00992 //
00993 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
00994   for (auto &I : Attachments)
00995     if (I.first == ID) {
00996       I.second.reset(&MD);
00997       return;
00998     }
00999   Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
01000                            std::make_tuple(&MD));
01001 }
01002 
01003 void MDAttachmentMap::erase(unsigned ID) {
01004   if (empty())
01005     return;
01006 
01007   // Common case is one/last value.
01008   if (Attachments.back().first == ID) {
01009     Attachments.pop_back();
01010     return;
01011   }
01012 
01013   for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
01014        ++I)
01015     if (I->first == ID) {
01016       *I = std::move(Attachments.back());
01017       Attachments.pop_back();
01018       return;
01019     }
01020 }
01021 
01022 MDNode *MDAttachmentMap::lookup(unsigned ID) const {
01023   for (const auto &I : Attachments)
01024     if (I.first == ID)
01025       return I.second;
01026   return nullptr;
01027 }
01028 
01029 void MDAttachmentMap::getAll(
01030     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
01031   Result.append(Attachments.begin(), Attachments.end());
01032 
01033   // Sort the resulting array so it is stable.
01034   if (Result.size() > 1)
01035     array_pod_sort(Result.begin(), Result.end());
01036 }
01037 
01038 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
01039   if (!Node && !hasMetadata())
01040     return;
01041   setMetadata(getContext().getMDKindID(Kind), Node);
01042 }
01043 
01044 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
01045   return getMetadataImpl(getContext().getMDKindID(Kind));
01046 }
01047 
01048 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
01049   SmallSet<unsigned, 5> KnownSet;
01050   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
01051 
01052   // Drop debug if needed
01053   if (KnownSet.erase(LLVMContext::MD_dbg))
01054     DbgLoc = DebugLoc();
01055 
01056   if (!hasMetadataHashEntry())
01057     return; // Nothing to remove!
01058 
01059   auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
01060 
01061   if (KnownSet.empty()) {
01062     // Just drop our entry at the store.
01063     InstructionMetadata.erase(this);
01064     setHasMetadataHashEntry(false);
01065     return;
01066   }
01067 
01068   auto &Info = InstructionMetadata[this];
01069   Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
01070     return !KnownSet.count(I.first);
01071   });
01072 
01073   if (Info.empty()) {
01074     // Drop our entry at the store.
01075     InstructionMetadata.erase(this);
01076     setHasMetadataHashEntry(false);
01077   }
01078 }
01079 
01080 /// setMetadata - Set the metadata of of the specified kind to the specified
01081 /// node.  This updates/replaces metadata if already present, or removes it if
01082 /// Node is null.
01083 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
01084   if (!Node && !hasMetadata())
01085     return;
01086 
01087   // Handle 'dbg' as a special case since it is not stored in the hash table.
01088   if (KindID == LLVMContext::MD_dbg) {
01089     DbgLoc = DebugLoc(Node);
01090     return;
01091   }
01092   
01093   // Handle the case when we're adding/updating metadata on an instruction.
01094   if (Node) {
01095     auto &Info = getContext().pImpl->InstructionMetadata[this];
01096     assert(!Info.empty() == hasMetadataHashEntry() &&
01097            "HasMetadata bit is wonked");
01098     if (Info.empty())
01099       setHasMetadataHashEntry(true);
01100     Info.set(KindID, *Node);
01101     return;
01102   }
01103 
01104   // Otherwise, we're removing metadata from an instruction.
01105   assert((hasMetadataHashEntry() ==
01106           (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
01107          "HasMetadata bit out of date!");
01108   if (!hasMetadataHashEntry())
01109     return;  // Nothing to remove!
01110   auto &Info = getContext().pImpl->InstructionMetadata[this];
01111 
01112   // Handle removal of an existing value.
01113   Info.erase(KindID);
01114 
01115   if (!Info.empty())
01116     return;
01117 
01118   getContext().pImpl->InstructionMetadata.erase(this);
01119   setHasMetadataHashEntry(false);
01120 }
01121 
01122 void Instruction::setAAMetadata(const AAMDNodes &N) {
01123   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
01124   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
01125   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
01126 }
01127 
01128 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
01129   // Handle 'dbg' as a special case since it is not stored in the hash table.
01130   if (KindID == LLVMContext::MD_dbg)
01131     return DbgLoc.getAsMDNode();
01132 
01133   if (!hasMetadataHashEntry())
01134     return nullptr;
01135   auto &Info = getContext().pImpl->InstructionMetadata[this];
01136   assert(!Info.empty() && "bit out of sync with hash table");
01137 
01138   return Info.lookup(KindID);
01139 }
01140 
01141 void Instruction::getAllMetadataImpl(
01142     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
01143   Result.clear();
01144   
01145   // Handle 'dbg' as a special case since it is not stored in the hash table.
01146   if (DbgLoc) {
01147     Result.push_back(
01148         std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
01149     if (!hasMetadataHashEntry()) return;
01150   }
01151 
01152   assert(hasMetadataHashEntry() &&
01153          getContext().pImpl->InstructionMetadata.count(this) &&
01154          "Shouldn't have called this");
01155   const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
01156   assert(!Info.empty() && "Shouldn't have called this");
01157   Info.getAll(Result);
01158 }
01159 
01160 void Instruction::getAllMetadataOtherThanDebugLocImpl(
01161     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
01162   Result.clear();
01163   assert(hasMetadataHashEntry() &&
01164          getContext().pImpl->InstructionMetadata.count(this) &&
01165          "Shouldn't have called this");
01166   const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
01167   assert(!Info.empty() && "Shouldn't have called this");
01168   Info.getAll(Result);
01169 }
01170 
01171 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
01172 /// this instruction.
01173 void Instruction::clearMetadataHashEntries() {
01174   assert(hasMetadataHashEntry() && "Caller should check");
01175   getContext().pImpl->InstructionMetadata.erase(this);
01176   setHasMetadataHashEntry(false);
01177 }
01178 
01179 MDNode *Function::getMetadata(unsigned KindID) const {
01180   if (!hasMetadata())
01181     return nullptr;
01182   return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
01183 }
01184 
01185 MDNode *Function::getMetadata(StringRef Kind) const {
01186   if (!hasMetadata())
01187     return nullptr;
01188   return getMetadata(getContext().getMDKindID(Kind));
01189 }
01190 
01191 void Function::setMetadata(unsigned KindID, MDNode *MD) {
01192   if (MD) {
01193     if (!hasMetadata())
01194       setHasMetadataHashEntry(true);
01195 
01196     getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
01197     return;
01198   }
01199 
01200   // Nothing to unset.
01201   if (!hasMetadata())
01202     return;
01203 
01204   auto &Store = getContext().pImpl->FunctionMetadata[this];
01205   Store.erase(KindID);
01206   if (Store.empty())
01207     clearMetadata();
01208 }
01209 
01210 void Function::setMetadata(StringRef Kind, MDNode *MD) {
01211   if (!MD && !hasMetadata())
01212     return;
01213   setMetadata(getContext().getMDKindID(Kind), MD);
01214 }
01215 
01216 void Function::getAllMetadata(
01217     SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
01218   MDs.clear();
01219 
01220   if (!hasMetadata())
01221     return;
01222 
01223   getContext().pImpl->FunctionMetadata[this].getAll(MDs);
01224 }
01225 
01226 void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
01227   if (!hasMetadata())
01228     return;
01229   if (KnownIDs.empty()) {
01230     clearMetadata();
01231     return;
01232   }
01233 
01234   SmallSet<unsigned, 5> KnownSet;
01235   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
01236 
01237   auto &Store = getContext().pImpl->FunctionMetadata[this];
01238   assert(!Store.empty());
01239 
01240   Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
01241     return !KnownSet.count(I.first);
01242   });
01243 
01244   if (Store.empty())
01245     clearMetadata();
01246 }
01247 
01248 void Function::clearMetadata() {
01249   if (!hasMetadata())
01250     return;
01251   getContext().pImpl->FunctionMetadata.erase(this);
01252   setHasMetadataHashEntry(false);
01253 }