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