LLVM API Documentation

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 "SymbolTableListTraitsImpl.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallSet.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/ADT/StringMap.h"
00022 #include "llvm/IR/ConstantRange.h"
00023 #include "llvm/IR/Instruction.h"
00024 #include "llvm/IR/LLVMContext.h"
00025 #include "llvm/IR/LeakDetector.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/IR/ValueHandle.h"
00028 
00029 using namespace llvm;
00030 
00031 Metadata::Metadata(LLVMContext &Context, unsigned ID)
00032     : Value(Type::getMetadataTy(Context), ID) {}
00033 
00034 //===----------------------------------------------------------------------===//
00035 // MDString implementation.
00036 //
00037 
00038 void MDString::anchor() { }
00039 
00040 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
00041   auto &Store = Context.pImpl->MDStringCache;
00042   auto I = Store.find(Str);
00043   if (I != Store.end())
00044     return &I->second;
00045 
00046   auto *Entry =
00047       StringMapEntry<MDString>::Create(Str, Store.getAllocator(), Context);
00048   bool WasInserted = Store.insert(Entry);
00049   (void)WasInserted;
00050   assert(WasInserted && "Expected entry to be inserted");
00051   return &Entry->second;
00052 }
00053 
00054 StringRef MDString::getString() const {
00055   return StringMapEntry<MDString>::GetStringMapEntryFromValue(*this).first();
00056 }
00057 
00058 //===----------------------------------------------------------------------===//
00059 // MDNodeOperand implementation.
00060 //
00061 
00062 // Use CallbackVH to hold MDNode operands.
00063 namespace llvm {
00064 class MDNodeOperand : public CallbackVH {
00065   MDNode *getParent() {
00066     MDNodeOperand *Cur = this;
00067 
00068     while (Cur->getValPtrInt() != 1)
00069       ++Cur;
00070 
00071     assert(Cur->getValPtrInt() == 1 &&
00072            "Couldn't find the end of the operand list!");
00073     return reinterpret_cast<MDNode *>(Cur + 1);
00074   }
00075 
00076 public:
00077   MDNodeOperand() {}
00078   virtual ~MDNodeOperand();
00079 
00080   void set(Value *V) {
00081     unsigned IsLast = this->getValPtrInt();
00082     this->setValPtr(V);
00083     this->setAsLastOperand(IsLast);
00084   }
00085 
00086   /// \brief Accessor method to mark the operand as the first in the list.
00087   void setAsLastOperand(unsigned I) { this->setValPtrInt(I); }
00088 
00089   void deleted() override;
00090   void allUsesReplacedWith(Value *NV) override;
00091 };
00092 } // end namespace llvm.
00093 
00094 // Provide out-of-line definition to prevent weak vtable.
00095 MDNodeOperand::~MDNodeOperand() {}
00096 
00097 void MDNodeOperand::deleted() {
00098   getParent()->replaceOperand(this, nullptr);
00099 }
00100 
00101 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
00102   getParent()->replaceOperand(this, NV);
00103 }
00104 
00105 //===----------------------------------------------------------------------===//
00106 // MDNode implementation.
00107 //
00108 
00109 /// \brief Get the MDNodeOperand's coallocated on the end of the MDNode.
00110 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
00111   // Use <= instead of < to permit a one-past-the-end address.
00112   assert(Op <= N->getNumOperands() && "Invalid operand number");
00113   return reinterpret_cast<MDNodeOperand *>(N) - N->getNumOperands() + Op;
00114 }
00115 
00116 void MDNode::replaceOperandWith(unsigned i, Value *Val) {
00117   MDNodeOperand *Op = getOperandPtr(this, i);
00118   replaceOperand(Op, Val);
00119 }
00120 
00121 void *MDNode::operator new(size_t Size, unsigned NumOps) {
00122   void *Ptr = ::operator new(Size + NumOps * sizeof(MDNodeOperand));
00123   MDNodeOperand *Op = static_cast<MDNodeOperand *>(Ptr);
00124   if (NumOps) {
00125     MDNodeOperand *Last = Op + NumOps;
00126     for (; Op != Last; ++Op)
00127       new (Op) MDNodeOperand();
00128     (Op - 1)->setAsLastOperand(1);
00129   }
00130   return Op;
00131 }
00132 
00133 void MDNode::operator delete(void *Mem) {
00134   MDNode *N = static_cast<MDNode *>(Mem);
00135   MDNodeOperand *Op = static_cast<MDNodeOperand *>(Mem);
00136   for (unsigned I = 0, E = N->NumOperands; I != E; ++I)
00137     (--Op)->~MDNodeOperand();
00138   ::operator delete(Op);
00139 }
00140 
00141 MDNode::MDNode(LLVMContext &C, unsigned ID, ArrayRef<Value *> Vals,
00142                bool isFunctionLocal)
00143     : Metadata(C, ID) {
00144   NumOperands = Vals.size();
00145 
00146   if (isFunctionLocal)
00147     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
00148 
00149   // Initialize the operand list.
00150   unsigned i = 0;
00151   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op + NumOperands;
00152        Op != E; ++Op, ++i)
00153     Op->set(Vals[i]);
00154 }
00155 
00156 GenericMDNode::~GenericMDNode() {
00157   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
00158   if (isNotUniqued()) {
00159     pImpl->NonUniquedMDNodes.erase(this);
00160   } else {
00161     pImpl->MDNodeSet.erase(this);
00162   }
00163 }
00164 
00165 void GenericMDNode::dropAllReferences() {
00166   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op + NumOperands;
00167        Op != E; ++Op)
00168     Op->set(nullptr);
00169 }
00170 
00171 static const Function *getFunctionForValue(Value *V) {
00172   if (!V) return nullptr;
00173   if (Instruction *I = dyn_cast<Instruction>(V)) {
00174     BasicBlock *BB = I->getParent();
00175     return BB ? BB->getParent() : nullptr;
00176   }
00177   if (Argument *A = dyn_cast<Argument>(V))
00178     return A->getParent();
00179   if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
00180     return BB->getParent();
00181   if (MDNode *MD = dyn_cast<MDNode>(V))
00182     return MD->getFunction();
00183   return nullptr;
00184 }
00185 
00186 #ifndef NDEBUG
00187 static const Function *assertLocalFunction(const MDNode *N) {
00188   if (!N->isFunctionLocal()) return nullptr;
00189 
00190   // FIXME: This does not handle cyclic function local metadata.
00191   const Function *F = nullptr, *NewF = nullptr;
00192   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00193     if (Value *V = N->getOperand(i)) {
00194       if (MDNode *MD = dyn_cast<MDNode>(V))
00195         NewF = assertLocalFunction(MD);
00196       else
00197         NewF = getFunctionForValue(V);
00198     }
00199     if (!F)
00200       F = NewF;
00201     else
00202       assert((NewF == nullptr || F == NewF) &&
00203              "inconsistent function-local metadata");
00204   }
00205   return F;
00206 }
00207 #endif
00208 
00209 // getFunction - If this metadata is function-local and recursively has a
00210 // function-local operand, return the first such operand's parent function.
00211 // Otherwise, return null. getFunction() should not be used for performance-
00212 // critical code because it recursively visits all the MDNode's operands.  
00213 const Function *MDNode::getFunction() const {
00214 #ifndef NDEBUG
00215   return assertLocalFunction(this);
00216 #else
00217   if (!isFunctionLocal()) return nullptr;
00218   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00219     if (const Function *F = getFunctionForValue(getOperand(i)))
00220       return F;
00221   return nullptr;
00222 #endif
00223 }
00224 
00225 /// \brief Check if the Value  would require a function-local MDNode.
00226 static bool isFunctionLocalValue(Value *V) {
00227   return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
00228          (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
00229 }
00230 
00231 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
00232                           FunctionLocalness FL, bool Insert) {
00233   auto &Store = Context.pImpl->MDNodeSet;
00234 
00235   GenericMDNodeInfo::KeyTy Key(Vals);
00236   auto I = Store.find_as(Key);
00237   if (I != Store.end())
00238     return *I;
00239   if (!Insert)
00240     return nullptr;
00241 
00242   bool isFunctionLocal = false;
00243   switch (FL) {
00244   case FL_Unknown:
00245     for (Value *V : Vals) {
00246       if (!V) continue;
00247       if (isFunctionLocalValue(V)) {
00248         isFunctionLocal = true;
00249         break;
00250       }
00251     }
00252     break;
00253   case FL_No:
00254     isFunctionLocal = false;
00255     break;
00256   case FL_Yes:
00257     isFunctionLocal = true;
00258     break;
00259   }
00260 
00261   // Coallocate space for the node and Operands together, then placement new.
00262   GenericMDNode *N =
00263       new (Vals.size()) GenericMDNode(Context, Vals, isFunctionLocal);
00264 
00265   N->Hash = Key.Hash;
00266   Store.insert(N);
00267   return N;
00268 }
00269 
00270 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
00271   return getMDNode(Context, Vals, FL_Unknown);
00272 }
00273 
00274 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
00275                                       ArrayRef<Value*> Vals,
00276                                       bool isFunctionLocal) {
00277   return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
00278 }
00279 
00280 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
00281   return getMDNode(Context, Vals, FL_Unknown, false);
00282 }
00283 
00284 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
00285   MDNode *N = new (Vals.size()) MDNodeFwdDecl(Context, Vals, FL_No);
00286   N->setValueSubclassData(N->getSubclassDataFromValue() | NotUniquedBit);
00287   LeakDetector::addGarbageObject(N);
00288   return N;
00289 }
00290 
00291 void MDNode::deleteTemporary(MDNode *N) {
00292   assert(N->use_empty() && "Temporary MDNode has uses!");
00293   assert(isa<MDNodeFwdDecl>(N) && "Expected forward declaration");
00294   assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
00295          "Temporary MDNode does not have NotUniquedBit set!");
00296   LeakDetector::removeGarbageObject(N);
00297   delete cast<MDNodeFwdDecl>(N);
00298 }
00299 
00300 /// \brief Return specified operand.
00301 Value *MDNode::getOperand(unsigned i) const {
00302   assert(i < getNumOperands() && "Invalid operand number");
00303   return *getOperandPtr(const_cast<MDNode*>(this), i);
00304 }
00305 
00306 void MDNode::setIsNotUniqued() {
00307   setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
00308   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
00309   auto *G = cast<GenericMDNode>(this);
00310   G->Hash = 0;
00311   pImpl->NonUniquedMDNodes.insert(G);
00312 }
00313 
00314 // Replace value from this node's operand list.
00315 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
00316   Value *From = *Op;
00317 
00318   // If is possible that someone did GV->RAUW(inst), replacing a global variable
00319   // with an instruction or some other function-local object.  If this is a
00320   // non-function-local MDNode, it can't point to a function-local object.
00321   // Handle this case by implicitly dropping the MDNode reference to null.
00322   // Likewise if the MDNode is function-local but for a different function.
00323   if (To && isFunctionLocalValue(To)) {
00324     if (!isFunctionLocal())
00325       To = nullptr;
00326     else {
00327       const Function *F = getFunction();
00328       const Function *FV = getFunctionForValue(To);
00329       // Metadata can be function-local without having an associated function.
00330       // So only consider functions to have changed if non-null.
00331       if (F && FV && F != FV)
00332         To = nullptr;
00333     }
00334   }
00335   
00336   if (From == To)
00337     return;
00338 
00339   // If this node is already not being uniqued (because one of the operands
00340   // already went to null), then there is nothing else to do here.
00341   if (isNotUniqued()) {
00342     Op->set(To);
00343     return;
00344   }
00345 
00346   auto &Store = getContext().pImpl->MDNodeSet;
00347   auto *N = cast<GenericMDNode>(this);
00348 
00349   // Remove "this" from the context map.
00350   Store.erase(N);
00351 
00352   // Update the operand.
00353   Op->set(To);
00354 
00355   // If we are dropping an argument to null, we choose to not unique the MDNode
00356   // anymore.  This commonly occurs during destruction, and uniquing these
00357   // brings little reuse.  Also, this means we don't need to include
00358   // isFunctionLocal bits in the hash for MDNodes.
00359   if (!To) {
00360     setIsNotUniqued();
00361     return;
00362   }
00363 
00364   // Now that the node is out of the table, get ready to reinsert it.  First,
00365   // check to see if another node with the same operands already exists in the
00366   // set.  If so, then this node is redundant.
00367   SmallVector<Value *, 8> Vals;
00368   GenericMDNodeInfo::KeyTy Key(N, Vals);
00369   auto I = Store.find_as(Key);
00370   if (I != Store.end()) {
00371     N->replaceAllUsesWith(*I);
00372     delete N;
00373     return;
00374   }
00375 
00376   N->Hash = Key.Hash;
00377   Store.insert(N);
00378 
00379   // If this MDValue was previously function-local but no longer is, clear
00380   // its function-local flag.
00381   if (isFunctionLocal() && !isFunctionLocalValue(To)) {
00382     bool isStillFunctionLocal = false;
00383     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00384       Value *V = getOperand(i);
00385       if (!V) continue;
00386       if (isFunctionLocalValue(V)) {
00387         isStillFunctionLocal = true;
00388         break;
00389       }
00390     }
00391     if (!isStillFunctionLocal)
00392       setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
00393   }
00394 }
00395 
00396 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
00397   if (!A)
00398     return B;
00399   if (!B)
00400     return A;
00401 
00402   SmallVector<Value *, 4> Vals(A->getNumOperands() +
00403                                B->getNumOperands());
00404 
00405   unsigned j = 0;
00406   for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
00407     Vals[j++] = A->getOperand(i);
00408   for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
00409     Vals[j++] = B->getOperand(i);
00410 
00411   return MDNode::get(A->getContext(), Vals);
00412 }
00413 
00414 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
00415   if (!A || !B)
00416     return nullptr;
00417 
00418   SmallVector<Value *, 4> Vals;
00419   for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
00420     Value *V = A->getOperand(i);
00421     for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
00422       if (V == B->getOperand(j)) {
00423         Vals.push_back(V);
00424         break;
00425       }
00426   }
00427 
00428   return MDNode::get(A->getContext(), Vals);
00429 }
00430 
00431 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
00432   if (!A || !B)
00433     return nullptr;
00434 
00435   APFloat AVal = cast<ConstantFP>(A->getOperand(0))->getValueAPF();
00436   APFloat BVal = cast<ConstantFP>(B->getOperand(0))->getValueAPF();
00437   if (AVal.compare(BVal) == APFloat::cmpLessThan)
00438     return A;
00439   return B;
00440 }
00441 
00442 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
00443   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
00444 }
00445 
00446 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
00447   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
00448 }
00449 
00450 static bool tryMergeRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
00451                           ConstantInt *High) {
00452   ConstantRange NewRange(Low->getValue(), High->getValue());
00453   unsigned Size = EndPoints.size();
00454   APInt LB = cast<ConstantInt>(EndPoints[Size - 2])->getValue();
00455   APInt LE = cast<ConstantInt>(EndPoints[Size - 1])->getValue();
00456   ConstantRange LastRange(LB, LE);
00457   if (canBeMerged(NewRange, LastRange)) {
00458     ConstantRange Union = LastRange.unionWith(NewRange);
00459     Type *Ty = High->getType();
00460     EndPoints[Size - 2] = ConstantInt::get(Ty, Union.getLower());
00461     EndPoints[Size - 1] = ConstantInt::get(Ty, Union.getUpper());
00462     return true;
00463   }
00464   return false;
00465 }
00466 
00467 static void addRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
00468                      ConstantInt *High) {
00469   if (!EndPoints.empty())
00470     if (tryMergeRange(EndPoints, Low, High))
00471       return;
00472 
00473   EndPoints.push_back(Low);
00474   EndPoints.push_back(High);
00475 }
00476 
00477 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
00478   // Given two ranges, we want to compute the union of the ranges. This
00479   // is slightly complitade by having to combine the intervals and merge
00480   // the ones that overlap.
00481 
00482   if (!A || !B)
00483     return nullptr;
00484 
00485   if (A == B)
00486     return A;
00487 
00488   // First, walk both lists in older of the lower boundary of each interval.
00489   // At each step, try to merge the new interval to the last one we adedd.
00490   SmallVector<Value*, 4> EndPoints;
00491   int AI = 0;
00492   int BI = 0;
00493   int AN = A->getNumOperands() / 2;
00494   int BN = B->getNumOperands() / 2;
00495   while (AI < AN && BI < BN) {
00496     ConstantInt *ALow = cast<ConstantInt>(A->getOperand(2 * AI));
00497     ConstantInt *BLow = cast<ConstantInt>(B->getOperand(2 * BI));
00498 
00499     if (ALow->getValue().slt(BLow->getValue())) {
00500       addRange(EndPoints, ALow, cast<ConstantInt>(A->getOperand(2 * AI + 1)));
00501       ++AI;
00502     } else {
00503       addRange(EndPoints, BLow, cast<ConstantInt>(B->getOperand(2 * BI + 1)));
00504       ++BI;
00505     }
00506   }
00507   while (AI < AN) {
00508     addRange(EndPoints, cast<ConstantInt>(A->getOperand(2 * AI)),
00509              cast<ConstantInt>(A->getOperand(2 * AI + 1)));
00510     ++AI;
00511   }
00512   while (BI < BN) {
00513     addRange(EndPoints, cast<ConstantInt>(B->getOperand(2 * BI)),
00514              cast<ConstantInt>(B->getOperand(2 * BI + 1)));
00515     ++BI;
00516   }
00517 
00518   // If we have more than 2 ranges (4 endpoints) we have to try to merge
00519   // the last and first ones.
00520   unsigned Size = EndPoints.size();
00521   if (Size > 4) {
00522     ConstantInt *FB = cast<ConstantInt>(EndPoints[0]);
00523     ConstantInt *FE = cast<ConstantInt>(EndPoints[1]);
00524     if (tryMergeRange(EndPoints, FB, FE)) {
00525       for (unsigned i = 0; i < Size - 2; ++i) {
00526         EndPoints[i] = EndPoints[i + 2];
00527       }
00528       EndPoints.resize(Size - 2);
00529     }
00530   }
00531 
00532   // If in the end we have a single range, it is possible that it is now the
00533   // full range. Just drop the metadata in that case.
00534   if (EndPoints.size() == 2) {
00535     ConstantRange Range(cast<ConstantInt>(EndPoints[0])->getValue(),
00536                         cast<ConstantInt>(EndPoints[1])->getValue());
00537     if (Range.isFullSet())
00538       return nullptr;
00539   }
00540 
00541   return MDNode::get(A->getContext(), EndPoints);
00542 }
00543 
00544 //===----------------------------------------------------------------------===//
00545 // NamedMDNode implementation.
00546 //
00547 
00548 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
00549   return *(SmallVector<TrackingVH<MDNode>, 4> *)Operands;
00550 }
00551 
00552 NamedMDNode::NamedMDNode(const Twine &N)
00553     : Name(N.str()), Parent(nullptr),
00554       Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {}
00555 
00556 NamedMDNode::~NamedMDNode() {
00557   dropAllReferences();
00558   delete &getNMDOps(Operands);
00559 }
00560 
00561 unsigned NamedMDNode::getNumOperands() const {
00562   return (unsigned)getNMDOps(Operands).size();
00563 }
00564 
00565 MDNode *NamedMDNode::getOperand(unsigned i) const {
00566   assert(i < getNumOperands() && "Invalid Operand number!");
00567   return &*getNMDOps(Operands)[i];
00568 }
00569 
00570 void NamedMDNode::addOperand(MDNode *M) {
00571   assert(!M->isFunctionLocal() &&
00572          "NamedMDNode operands must not be function-local!");
00573   getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
00574 }
00575 
00576 void NamedMDNode::eraseFromParent() {
00577   getParent()->eraseNamedMetadata(this);
00578 }
00579 
00580 void NamedMDNode::dropAllReferences() {
00581   getNMDOps(Operands).clear();
00582 }
00583 
00584 StringRef NamedMDNode::getName() const {
00585   return StringRef(Name);
00586 }
00587 
00588 //===----------------------------------------------------------------------===//
00589 // Instruction Metadata method implementations.
00590 //
00591 
00592 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
00593   if (!Node && !hasMetadata())
00594     return;
00595   setMetadata(getContext().getMDKindID(Kind), Node);
00596 }
00597 
00598 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
00599   return getMetadataImpl(getContext().getMDKindID(Kind));
00600 }
00601 
00602 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
00603   SmallSet<unsigned, 5> KnownSet;
00604   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
00605 
00606   // Drop debug if needed
00607   if (KnownSet.erase(LLVMContext::MD_dbg))
00608     DbgLoc = DebugLoc();
00609 
00610   if (!hasMetadataHashEntry())
00611     return; // Nothing to remove!
00612 
00613   DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
00614       getContext().pImpl->MetadataStore;
00615 
00616   if (KnownSet.empty()) {
00617     // Just drop our entry at the store.
00618     MetadataStore.erase(this);
00619     setHasMetadataHashEntry(false);
00620     return;
00621   }
00622 
00623   LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
00624   unsigned I;
00625   unsigned E;
00626   // Walk the array and drop any metadata we don't know.
00627   for (I = 0, E = Info.size(); I != E;) {
00628     if (KnownSet.count(Info[I].first)) {
00629       ++I;
00630       continue;
00631     }
00632 
00633     Info[I] = Info.back();
00634     Info.pop_back();
00635     --E;
00636   }
00637   assert(E == Info.size());
00638 
00639   if (E == 0) {
00640     // Drop our entry at the store.
00641     MetadataStore.erase(this);
00642     setHasMetadataHashEntry(false);
00643   }
00644 }
00645 
00646 /// setMetadata - Set the metadata of of the specified kind to the specified
00647 /// node.  This updates/replaces metadata if already present, or removes it if
00648 /// Node is null.
00649 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
00650   if (!Node && !hasMetadata())
00651     return;
00652 
00653   // Handle 'dbg' as a special case since it is not stored in the hash table.
00654   if (KindID == LLVMContext::MD_dbg) {
00655     DbgLoc = DebugLoc::getFromDILocation(Node);
00656     return;
00657   }
00658   
00659   // Handle the case when we're adding/updating metadata on an instruction.
00660   if (Node) {
00661     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
00662     assert(!Info.empty() == hasMetadataHashEntry() &&
00663            "HasMetadata bit is wonked");
00664     if (Info.empty()) {
00665       setHasMetadataHashEntry(true);
00666     } else {
00667       // Handle replacement of an existing value.
00668       for (auto &P : Info)
00669         if (P.first == KindID) {
00670           P.second = Node;
00671           return;
00672         }
00673     }
00674 
00675     // No replacement, just add it to the list.
00676     Info.push_back(std::make_pair(KindID, Node));
00677     return;
00678   }
00679 
00680   // Otherwise, we're removing metadata from an instruction.
00681   assert((hasMetadataHashEntry() ==
00682           (getContext().pImpl->MetadataStore.count(this) > 0)) &&
00683          "HasMetadata bit out of date!");
00684   if (!hasMetadataHashEntry())
00685     return;  // Nothing to remove!
00686   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
00687 
00688   // Common case is removing the only entry.
00689   if (Info.size() == 1 && Info[0].first == KindID) {
00690     getContext().pImpl->MetadataStore.erase(this);
00691     setHasMetadataHashEntry(false);
00692     return;
00693   }
00694 
00695   // Handle removal of an existing value.
00696   for (unsigned i = 0, e = Info.size(); i != e; ++i)
00697     if (Info[i].first == KindID) {
00698       Info[i] = Info.back();
00699       Info.pop_back();
00700       assert(!Info.empty() && "Removing last entry should be handled above");
00701       return;
00702     }
00703   // Otherwise, removing an entry that doesn't exist on the instruction.
00704 }
00705 
00706 void Instruction::setAAMetadata(const AAMDNodes &N) {
00707   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
00708   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
00709   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
00710 }
00711 
00712 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
00713   // Handle 'dbg' as a special case since it is not stored in the hash table.
00714   if (KindID == LLVMContext::MD_dbg)
00715     return DbgLoc.getAsMDNode(getContext());
00716   
00717   if (!hasMetadataHashEntry()) return nullptr;
00718   
00719   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
00720   assert(!Info.empty() && "bit out of sync with hash table");
00721 
00722   for (const auto &I : Info)
00723     if (I.first == KindID)
00724       return I.second;
00725   return nullptr;
00726 }
00727 
00728 void Instruction::getAllMetadataImpl(
00729     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
00730   Result.clear();
00731   
00732   // Handle 'dbg' as a special case since it is not stored in the hash table.
00733   if (!DbgLoc.isUnknown()) {
00734     Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
00735                                     DbgLoc.getAsMDNode(getContext())));
00736     if (!hasMetadataHashEntry()) return;
00737   }
00738   
00739   assert(hasMetadataHashEntry() &&
00740          getContext().pImpl->MetadataStore.count(this) &&
00741          "Shouldn't have called this");
00742   const LLVMContextImpl::MDMapTy &Info =
00743     getContext().pImpl->MetadataStore.find(this)->second;
00744   assert(!Info.empty() && "Shouldn't have called this");
00745 
00746   Result.append(Info.begin(), Info.end());
00747 
00748   // Sort the resulting array so it is stable.
00749   if (Result.size() > 1)
00750     array_pod_sort(Result.begin(), Result.end());
00751 }
00752 
00753 void Instruction::getAllMetadataOtherThanDebugLocImpl(
00754     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
00755   Result.clear();
00756   assert(hasMetadataHashEntry() &&
00757          getContext().pImpl->MetadataStore.count(this) &&
00758          "Shouldn't have called this");
00759   const LLVMContextImpl::MDMapTy &Info =
00760     getContext().pImpl->MetadataStore.find(this)->second;
00761   assert(!Info.empty() && "Shouldn't have called this");
00762   Result.append(Info.begin(), Info.end());
00763 
00764   // Sort the resulting array so it is stable.
00765   if (Result.size() > 1)
00766     array_pod_sort(Result.begin(), Result.end());
00767 }
00768 
00769 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
00770 /// this instruction.
00771 void Instruction::clearMetadataHashEntries() {
00772   assert(hasMetadataHashEntry() && "Caller should check");
00773   getContext().pImpl->MetadataStore.erase(this);
00774   setHasMetadataHashEntry(false);
00775 }
00776