IR: Cleanup comments for Value, User, and MDNode
[oota-llvm.git] / lib / IR / Metadata.cpp
1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Metadata classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Metadata.h"
15 #include "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/LeakDetector.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueHandle.h"
28 using namespace llvm;
29
30 //===----------------------------------------------------------------------===//
31 // MDString implementation.
32 //
33
34 void MDString::anchor() { }
35
36 MDString::MDString(LLVMContext &C)
37   : Value(Type::getMetadataTy(C), Value::MDStringVal) {}
38
39 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
40   LLVMContextImpl *pImpl = Context.pImpl;
41   StringMapEntry<Value*> &Entry =
42     pImpl->MDStringCache.GetOrCreateValue(Str);
43   Value *&S = Entry.getValue();
44   if (!S) S = new MDString(Context);
45   S->setValueName(&Entry);
46   return cast<MDString>(S);
47 }
48
49 //===----------------------------------------------------------------------===//
50 // MDNodeOperand implementation.
51 //
52
53 // Use CallbackVH to hold MDNode operands.
54 namespace llvm {
55 class MDNodeOperand : public CallbackVH {
56   MDNode *getParent() {
57     MDNodeOperand *Cur = this;
58
59     while (Cur->getValPtrInt() != 1)
60       --Cur;
61
62     assert(Cur->getValPtrInt() == 1 &&
63            "Couldn't find the beginning of the operand list!");
64     return reinterpret_cast<MDNode*>(Cur) - 1;
65   }
66
67 public:
68   MDNodeOperand(Value *V) : CallbackVH(V) {}
69   virtual ~MDNodeOperand();
70
71   void set(Value *V) {
72     unsigned IsFirst = this->getValPtrInt();
73     this->setValPtr(V);
74     this->setAsFirstOperand(IsFirst);
75   }
76
77   /// \brief Accessor method to mark the operand as the first in the list.
78   void setAsFirstOperand(unsigned V) { this->setValPtrInt(V); }
79
80   void deleted() override;
81   void allUsesReplacedWith(Value *NV) override;
82 };
83 } // end namespace llvm.
84
85 // Provide out-of-line definition to prevent weak vtable.
86 MDNodeOperand::~MDNodeOperand() {}
87
88 void MDNodeOperand::deleted() {
89   getParent()->replaceOperand(this, nullptr);
90 }
91
92 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
93   getParent()->replaceOperand(this, NV);
94 }
95
96 //===----------------------------------------------------------------------===//
97 // MDNode implementation.
98 //
99
100 /// \brief Get the MDNodeOperand's coallocated on the end of the MDNode.
101 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
102   // Use <= instead of < to permit a one-past-the-end address.
103   assert(Op <= N->getNumOperands() && "Invalid operand number");
104   return reinterpret_cast<MDNodeOperand*>(N + 1) + Op;
105 }
106
107 void MDNode::replaceOperandWith(unsigned i, Value *Val) {
108   MDNodeOperand *Op = getOperandPtr(this, i);
109   replaceOperand(Op, Val);
110 }
111
112 MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
113 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
114   NumOperands = Vals.size();
115
116   if (isFunctionLocal)
117     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
118
119   // Initialize the operand list, which is co-allocated on the end of the node.
120   unsigned i = 0;
121   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
122        Op != E; ++Op, ++i) {
123     new (Op) MDNodeOperand(Vals[i]);
124
125     // Mark the first MDNodeOperand as being the first in the list of operands.
126     if (i == 0)
127       Op->setAsFirstOperand(1);
128   }
129 }
130
131 /// ~MDNode - Destroy MDNode.
132 MDNode::~MDNode() {
133   assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
134          "Not being destroyed through destroy()?");
135   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
136   if (isNotUniqued()) {
137     pImpl->NonUniquedMDNodes.erase(this);
138   } else {
139     pImpl->MDNodeSet.RemoveNode(this);
140   }
141
142   // Destroy the operands.
143   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
144        Op != E; ++Op)
145     Op->~MDNodeOperand();
146 }
147
148 static const Function *getFunctionForValue(Value *V) {
149   if (!V) return nullptr;
150   if (Instruction *I = dyn_cast<Instruction>(V)) {
151     BasicBlock *BB = I->getParent();
152     return BB ? BB->getParent() : nullptr;
153   }
154   if (Argument *A = dyn_cast<Argument>(V))
155     return A->getParent();
156   if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
157     return BB->getParent();
158   if (MDNode *MD = dyn_cast<MDNode>(V))
159     return MD->getFunction();
160   return nullptr;
161 }
162
163 #ifndef NDEBUG
164 static const Function *assertLocalFunction(const MDNode *N) {
165   if (!N->isFunctionLocal()) return nullptr;
166
167   // FIXME: This does not handle cyclic function local metadata.
168   const Function *F = nullptr, *NewF = nullptr;
169   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
170     if (Value *V = N->getOperand(i)) {
171       if (MDNode *MD = dyn_cast<MDNode>(V))
172         NewF = assertLocalFunction(MD);
173       else
174         NewF = getFunctionForValue(V);
175     }
176     if (!F)
177       F = NewF;
178     else
179       assert((NewF == nullptr || F == NewF) &&
180              "inconsistent function-local metadata");
181   }
182   return F;
183 }
184 #endif
185
186 // getFunction - If this metadata is function-local and recursively has a
187 // function-local operand, return the first such operand's parent function.
188 // Otherwise, return null. getFunction() should not be used for performance-
189 // critical code because it recursively visits all the MDNode's operands.  
190 const Function *MDNode::getFunction() const {
191 #ifndef NDEBUG
192   return assertLocalFunction(this);
193 #else
194   if (!isFunctionLocal()) return nullptr;
195   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
196     if (const Function *F = getFunctionForValue(getOperand(i)))
197       return F;
198   return nullptr;
199 #endif
200 }
201
202 // destroy - Delete this node.  Only when there are no uses.
203 void MDNode::destroy() {
204   setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
205   // Placement delete, then free the memory.
206   this->~MDNode();
207   free(this);
208 }
209
210 /// \brief Check if the Value  would require a function-local MDNode.
211 static bool isFunctionLocalValue(Value *V) {
212   return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
213          (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
214 }
215
216 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
217                           FunctionLocalness FL, bool Insert) {
218   LLVMContextImpl *pImpl = Context.pImpl;
219
220   // Add all the operand pointers. Note that we don't have to add the
221   // isFunctionLocal bit because that's implied by the operands.
222   // Note that if the operands are later nulled out, the node will be
223   // removed from the uniquing map.
224   FoldingSetNodeID ID;
225   for (Value *V : Vals)
226     ID.AddPointer(V);
227
228   void *InsertPoint;
229   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
230
231   if (N || !Insert)
232     return N;
233
234   bool isFunctionLocal = false;
235   switch (FL) {
236   case FL_Unknown:
237     for (Value *V : Vals) {
238       if (!V) continue;
239       if (isFunctionLocalValue(V)) {
240         isFunctionLocal = true;
241         break;
242       }
243     }
244     break;
245   case FL_No:
246     isFunctionLocal = false;
247     break;
248   case FL_Yes:
249     isFunctionLocal = true;
250     break;
251   }
252
253   // Coallocate space for the node and Operands together, then placement new.
254   void *Ptr = malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
255   N = new (Ptr) MDNode(Context, Vals, isFunctionLocal);
256
257   // Cache the operand hash.
258   N->Hash = ID.ComputeHash();
259
260   // InsertPoint will have been set by the FindNodeOrInsertPos call.
261   pImpl->MDNodeSet.InsertNode(N, InsertPoint);
262
263   return N;
264 }
265
266 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
267   return getMDNode(Context, Vals, FL_Unknown);
268 }
269
270 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
271                                       ArrayRef<Value*> Vals,
272                                       bool isFunctionLocal) {
273   return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
274 }
275
276 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
277   return getMDNode(Context, Vals, FL_Unknown, false);
278 }
279
280 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
281   MDNode *N =
282     (MDNode *)malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
283   N = new (N) MDNode(Context, Vals, FL_No);
284   N->setValueSubclassData(N->getSubclassDataFromValue() |
285                           NotUniquedBit);
286   LeakDetector::addGarbageObject(N);
287   return N;
288 }
289
290 void MDNode::deleteTemporary(MDNode *N) {
291   assert(N->use_empty() && "Temporary MDNode has uses!");
292   assert(!N->getContext().pImpl->MDNodeSet.RemoveNode(N) &&
293          "Deleting a non-temporary uniqued node!");
294   assert(!N->getContext().pImpl->NonUniquedMDNodes.erase(N) &&
295          "Deleting a non-temporary non-uniqued node!");
296   assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
297          "Temporary MDNode does not have NotUniquedBit set!");
298   assert((N->getSubclassDataFromValue() & DestroyFlag) == 0 &&
299          "Temporary MDNode has DestroyFlag set!");
300   LeakDetector::removeGarbageObject(N);
301   N->destroy();
302 }
303
304 /// \brief Return specified operand.
305 Value *MDNode::getOperand(unsigned i) const {
306   assert(i < getNumOperands() && "Invalid operand number");
307   return *getOperandPtr(const_cast<MDNode*>(this), i);
308 }
309
310 void MDNode::Profile(FoldingSetNodeID &ID) const {
311   // Add all the operand pointers. Note that we don't have to add the
312   // isFunctionLocal bit because that's implied by the operands.
313   // Note that if the operands are later nulled out, the node will be
314   // removed from the uniquing map.
315   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
316     ID.AddPointer(getOperand(i));
317 }
318
319 void MDNode::setIsNotUniqued() {
320   setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
321   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
322   pImpl->NonUniquedMDNodes.insert(this);
323 }
324
325 // Replace value from this node's operand list.
326 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
327   Value *From = *Op;
328
329   // If is possible that someone did GV->RAUW(inst), replacing a global variable
330   // with an instruction or some other function-local object.  If this is a
331   // non-function-local MDNode, it can't point to a function-local object.
332   // Handle this case by implicitly dropping the MDNode reference to null.
333   // Likewise if the MDNode is function-local but for a different function.
334   if (To && isFunctionLocalValue(To)) {
335     if (!isFunctionLocal())
336       To = nullptr;
337     else {
338       const Function *F = getFunction();
339       const Function *FV = getFunctionForValue(To);
340       // Metadata can be function-local without having an associated function.
341       // So only consider functions to have changed if non-null.
342       if (F && FV && F != FV)
343         To = nullptr;
344     }
345   }
346   
347   if (From == To)
348     return;
349
350   // Update the operand.
351   Op->set(To);
352
353   // If this node is already not being uniqued (because one of the operands
354   // already went to null), then there is nothing else to do here.
355   if (isNotUniqued()) return;
356
357   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
358
359   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
360   // this node to remove it, so we don't care what state the operands are in.
361   pImpl->MDNodeSet.RemoveNode(this);
362
363   // If we are dropping an argument to null, we choose to not unique the MDNode
364   // anymore.  This commonly occurs during destruction, and uniquing these
365   // brings little reuse.  Also, this means we don't need to include
366   // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
367   if (!To) {
368     setIsNotUniqued();
369     return;
370   }
371
372   // Now that the node is out of the folding set, get ready to reinsert it.
373   // First, check to see if another node with the same operands already exists
374   // in the set.  If so, then this node is redundant.
375   FoldingSetNodeID ID;
376   Profile(ID);
377   void *InsertPoint;
378   if (MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)) {
379     replaceAllUsesWith(N);
380     destroy();
381     return;
382   }
383
384   // Cache the operand hash.
385   Hash = ID.ComputeHash();
386   // InsertPoint will have been set by the FindNodeOrInsertPos call.
387   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
388
389   // If this MDValue was previously function-local but no longer is, clear
390   // its function-local flag.
391   if (isFunctionLocal() && !isFunctionLocalValue(To)) {
392     bool isStillFunctionLocal = false;
393     for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
394       Value *V = getOperand(i);
395       if (!V) continue;
396       if (isFunctionLocalValue(V)) {
397         isStillFunctionLocal = true;
398         break;
399       }
400     }
401     if (!isStillFunctionLocal)
402       setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
403   }
404 }
405
406 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
407   if (!A)
408     return B;
409   if (!B)
410     return A;
411
412   SmallVector<Value *, 4> Vals(A->getNumOperands() +
413                                B->getNumOperands());
414
415   unsigned j = 0;
416   for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
417     Vals[j++] = A->getOperand(i);
418   for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
419     Vals[j++] = B->getOperand(i);
420
421   return MDNode::get(A->getContext(), Vals);
422 }
423
424 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
425   if (!A || !B)
426     return nullptr;
427
428   SmallVector<Value *, 4> Vals;
429   for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
430     Value *V = A->getOperand(i);
431     for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
432       if (V == B->getOperand(j)) {
433         Vals.push_back(V);
434         break;
435       }
436   }
437
438   return MDNode::get(A->getContext(), Vals);
439 }
440
441 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
442   if (!A || !B)
443     return nullptr;
444
445   APFloat AVal = cast<ConstantFP>(A->getOperand(0))->getValueAPF();
446   APFloat BVal = cast<ConstantFP>(B->getOperand(0))->getValueAPF();
447   if (AVal.compare(BVal) == APFloat::cmpLessThan)
448     return A;
449   return B;
450 }
451
452 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
453   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
454 }
455
456 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
457   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
458 }
459
460 static bool tryMergeRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
461                           ConstantInt *High) {
462   ConstantRange NewRange(Low->getValue(), High->getValue());
463   unsigned Size = EndPoints.size();
464   APInt LB = cast<ConstantInt>(EndPoints[Size - 2])->getValue();
465   APInt LE = cast<ConstantInt>(EndPoints[Size - 1])->getValue();
466   ConstantRange LastRange(LB, LE);
467   if (canBeMerged(NewRange, LastRange)) {
468     ConstantRange Union = LastRange.unionWith(NewRange);
469     Type *Ty = High->getType();
470     EndPoints[Size - 2] = ConstantInt::get(Ty, Union.getLower());
471     EndPoints[Size - 1] = ConstantInt::get(Ty, Union.getUpper());
472     return true;
473   }
474   return false;
475 }
476
477 static void addRange(SmallVectorImpl<Value *> &EndPoints, ConstantInt *Low,
478                      ConstantInt *High) {
479   if (!EndPoints.empty())
480     if (tryMergeRange(EndPoints, Low, High))
481       return;
482
483   EndPoints.push_back(Low);
484   EndPoints.push_back(High);
485 }
486
487 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
488   // Given two ranges, we want to compute the union of the ranges. This
489   // is slightly complitade by having to combine the intervals and merge
490   // the ones that overlap.
491
492   if (!A || !B)
493     return nullptr;
494
495   if (A == B)
496     return A;
497
498   // First, walk both lists in older of the lower boundary of each interval.
499   // At each step, try to merge the new interval to the last one we adedd.
500   SmallVector<Value*, 4> EndPoints;
501   int AI = 0;
502   int BI = 0;
503   int AN = A->getNumOperands() / 2;
504   int BN = B->getNumOperands() / 2;
505   while (AI < AN && BI < BN) {
506     ConstantInt *ALow = cast<ConstantInt>(A->getOperand(2 * AI));
507     ConstantInt *BLow = cast<ConstantInt>(B->getOperand(2 * BI));
508
509     if (ALow->getValue().slt(BLow->getValue())) {
510       addRange(EndPoints, ALow, cast<ConstantInt>(A->getOperand(2 * AI + 1)));
511       ++AI;
512     } else {
513       addRange(EndPoints, BLow, cast<ConstantInt>(B->getOperand(2 * BI + 1)));
514       ++BI;
515     }
516   }
517   while (AI < AN) {
518     addRange(EndPoints, cast<ConstantInt>(A->getOperand(2 * AI)),
519              cast<ConstantInt>(A->getOperand(2 * AI + 1)));
520     ++AI;
521   }
522   while (BI < BN) {
523     addRange(EndPoints, cast<ConstantInt>(B->getOperand(2 * BI)),
524              cast<ConstantInt>(B->getOperand(2 * BI + 1)));
525     ++BI;
526   }
527
528   // If we have more than 2 ranges (4 endpoints) we have to try to merge
529   // the last and first ones.
530   unsigned Size = EndPoints.size();
531   if (Size > 4) {
532     ConstantInt *FB = cast<ConstantInt>(EndPoints[0]);
533     ConstantInt *FE = cast<ConstantInt>(EndPoints[1]);
534     if (tryMergeRange(EndPoints, FB, FE)) {
535       for (unsigned i = 0; i < Size - 2; ++i) {
536         EndPoints[i] = EndPoints[i + 2];
537       }
538       EndPoints.resize(Size - 2);
539     }
540   }
541
542   // If in the end we have a single range, it is possible that it is now the
543   // full range. Just drop the metadata in that case.
544   if (EndPoints.size() == 2) {
545     ConstantRange Range(cast<ConstantInt>(EndPoints[0])->getValue(),
546                         cast<ConstantInt>(EndPoints[1])->getValue());
547     if (Range.isFullSet())
548       return nullptr;
549   }
550
551   return MDNode::get(A->getContext(), EndPoints);
552 }
553
554 //===----------------------------------------------------------------------===//
555 // NamedMDNode implementation.
556 //
557
558 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
559   return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
560 }
561
562 NamedMDNode::NamedMDNode(const Twine &N)
563   : Name(N.str()), Parent(nullptr),
564     Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
565 }
566
567 NamedMDNode::~NamedMDNode() {
568   dropAllReferences();
569   delete &getNMDOps(Operands);
570 }
571
572 unsigned NamedMDNode::getNumOperands() const {
573   return (unsigned)getNMDOps(Operands).size();
574 }
575
576 MDNode *NamedMDNode::getOperand(unsigned i) const {
577   assert(i < getNumOperands() && "Invalid Operand number!");
578   return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
579 }
580
581 void NamedMDNode::addOperand(MDNode *M) {
582   assert(!M->isFunctionLocal() &&
583          "NamedMDNode operands must not be function-local!");
584   getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
585 }
586
587 void NamedMDNode::eraseFromParent() {
588   getParent()->eraseNamedMetadata(this);
589 }
590
591 void NamedMDNode::dropAllReferences() {
592   getNMDOps(Operands).clear();
593 }
594
595 StringRef NamedMDNode::getName() const {
596   return StringRef(Name);
597 }
598
599 //===----------------------------------------------------------------------===//
600 // Instruction Metadata method implementations.
601 //
602
603 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
604   if (!Node && !hasMetadata()) return;
605   setMetadata(getContext().getMDKindID(Kind), Node);
606 }
607
608 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
609   return getMetadataImpl(getContext().getMDKindID(Kind));
610 }
611
612 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
613   SmallSet<unsigned, 5> KnownSet;
614   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
615
616   // Drop debug if needed
617   if (KnownSet.erase(LLVMContext::MD_dbg))
618     DbgLoc = DebugLoc();
619
620   if (!hasMetadataHashEntry())
621     return; // Nothing to remove!
622
623   DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
624       getContext().pImpl->MetadataStore;
625
626   if (KnownSet.empty()) {
627     // Just drop our entry at the store.
628     MetadataStore.erase(this);
629     setHasMetadataHashEntry(false);
630     return;
631   }
632
633   LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
634   unsigned I;
635   unsigned E;
636   // Walk the array and drop any metadata we don't know.
637   for (I = 0, E = Info.size(); I != E;) {
638     if (KnownSet.count(Info[I].first)) {
639       ++I;
640       continue;
641     }
642
643     Info[I] = Info.back();
644     Info.pop_back();
645     --E;
646   }
647   assert(E == Info.size());
648
649   if (E == 0) {
650     // Drop our entry at the store.
651     MetadataStore.erase(this);
652     setHasMetadataHashEntry(false);
653   }
654 }
655
656 /// setMetadata - Set the metadata of of the specified kind to the specified
657 /// node.  This updates/replaces metadata if already present, or removes it if
658 /// Node is null.
659 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
660   if (!Node && !hasMetadata()) return;
661
662   // Handle 'dbg' as a special case since it is not stored in the hash table.
663   if (KindID == LLVMContext::MD_dbg) {
664     DbgLoc = DebugLoc::getFromDILocation(Node);
665     return;
666   }
667   
668   // Handle the case when we're adding/updating metadata on an instruction.
669   if (Node) {
670     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
671     assert(!Info.empty() == hasMetadataHashEntry() &&
672            "HasMetadata bit is wonked");
673     if (Info.empty()) {
674       setHasMetadataHashEntry(true);
675     } else {
676       // Handle replacement of an existing value.
677       for (auto &P : Info)
678         if (P.first == KindID) {
679           P.second = Node;
680           return;
681         }
682     }
683
684     // No replacement, just add it to the list.
685     Info.push_back(std::make_pair(KindID, Node));
686     return;
687   }
688
689   // Otherwise, we're removing metadata from an instruction.
690   assert((hasMetadataHashEntry() ==
691           (getContext().pImpl->MetadataStore.count(this) > 0)) &&
692          "HasMetadata bit out of date!");
693   if (!hasMetadataHashEntry())
694     return;  // Nothing to remove!
695   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
696
697   // Common case is removing the only entry.
698   if (Info.size() == 1 && Info[0].first == KindID) {
699     getContext().pImpl->MetadataStore.erase(this);
700     setHasMetadataHashEntry(false);
701     return;
702   }
703
704   // Handle removal of an existing value.
705   for (unsigned i = 0, e = Info.size(); i != e; ++i)
706     if (Info[i].first == KindID) {
707       Info[i] = Info.back();
708       Info.pop_back();
709       assert(!Info.empty() && "Removing last entry should be handled above");
710       return;
711     }
712   // Otherwise, removing an entry that doesn't exist on the instruction.
713 }
714
715 void Instruction::setAAMetadata(const AAMDNodes &N) {
716   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
717   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
718   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
719 }
720
721 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
722   // Handle 'dbg' as a special case since it is not stored in the hash table.
723   if (KindID == LLVMContext::MD_dbg)
724     return DbgLoc.getAsMDNode(getContext());
725   
726   if (!hasMetadataHashEntry()) return nullptr;
727   
728   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
729   assert(!Info.empty() && "bit out of sync with hash table");
730
731   for (const auto &I : Info)
732     if (I.first == KindID)
733       return I.second;
734   return nullptr;
735 }
736
737 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
738                                        MDNode*> > &Result) const {
739   Result.clear();
740   
741   // Handle 'dbg' as a special case since it is not stored in the hash table.
742   if (!DbgLoc.isUnknown()) {
743     Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
744                                     DbgLoc.getAsMDNode(getContext())));
745     if (!hasMetadataHashEntry()) return;
746   }
747   
748   assert(hasMetadataHashEntry() &&
749          getContext().pImpl->MetadataStore.count(this) &&
750          "Shouldn't have called this");
751   const LLVMContextImpl::MDMapTy &Info =
752     getContext().pImpl->MetadataStore.find(this)->second;
753   assert(!Info.empty() && "Shouldn't have called this");
754
755   Result.append(Info.begin(), Info.end());
756
757   // Sort the resulting array so it is stable.
758   if (Result.size() > 1)
759     array_pod_sort(Result.begin(), Result.end());
760 }
761
762 void Instruction::
763 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
764                                     MDNode*> > &Result) const {
765   Result.clear();
766   assert(hasMetadataHashEntry() &&
767          getContext().pImpl->MetadataStore.count(this) &&
768          "Shouldn't have called this");
769   const LLVMContextImpl::MDMapTy &Info =
770     getContext().pImpl->MetadataStore.find(this)->second;
771   assert(!Info.empty() && "Shouldn't have called this");
772   Result.append(Info.begin(), Info.end());
773
774   // Sort the resulting array so it is stable.
775   if (Result.size() > 1)
776     array_pod_sort(Result.begin(), Result.end());
777 }
778
779 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
780 /// this instruction.
781 void Instruction::clearMetadataHashEntries() {
782   assert(hasMetadataHashEntry() && "Caller should check");
783   getContext().pImpl->MetadataStore.erase(this);
784   setHasMetadataHashEntry(false);
785 }
786