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