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