ab1ba5e2035bc6ff3bed2439d4a0dc7c9083c983
[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 "MetadataImpl.h"
17 #include "SymbolTableListTraitsImpl.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/IR/ConstantRange.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/IR/Instruction.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ValueHandle.h"
29
30 using namespace llvm;
31
32 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
33     : Value(Ty, MetadataAsValueVal), MD(MD) {
34   track();
35 }
36
37 MetadataAsValue::~MetadataAsValue() {
38   getType()->getContext().pImpl->MetadataAsValues.erase(MD);
39   untrack();
40 }
41
42 /// \brief Canonicalize metadata arguments to intrinsics.
43 ///
44 /// To support bitcode upgrades (and assembly semantic sugar) for \a
45 /// MetadataAsValue, we need to canonicalize certain metadata.
46 ///
47 ///   - nullptr is replaced by an empty MDNode.
48 ///   - An MDNode with a single null operand is replaced by an empty MDNode.
49 ///   - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
50 ///
51 /// This maintains readability of bitcode from when metadata was a type of
52 /// value, and these bridges were unnecessary.
53 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
54                                               Metadata *MD) {
55   if (!MD)
56     // !{}
57     return MDNode::get(Context, None);
58
59   // Return early if this isn't a single-operand MDNode.
60   auto *N = dyn_cast<MDNode>(MD);
61   if (!N || N->getNumOperands() != 1)
62     return MD;
63
64   if (!N->getOperand(0))
65     // !{}
66     return MDNode::get(Context, None);
67
68   if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
69     // Look through the MDNode.
70     return C;
71
72   return MD;
73 }
74
75 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
76   MD = canonicalizeMetadataForValue(Context, MD);
77   auto *&Entry = Context.pImpl->MetadataAsValues[MD];
78   if (!Entry)
79     Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
80   return Entry;
81 }
82
83 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
84                                               Metadata *MD) {
85   MD = canonicalizeMetadataForValue(Context, MD);
86   auto &Store = Context.pImpl->MetadataAsValues;
87   return Store.lookup(MD);
88 }
89
90 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
91   LLVMContext &Context = getContext();
92   MD = canonicalizeMetadataForValue(Context, MD);
93   auto &Store = Context.pImpl->MetadataAsValues;
94
95   // Stop tracking the old metadata.
96   Store.erase(this->MD);
97   untrack();
98   this->MD = nullptr;
99
100   // Start tracking MD, or RAUW if necessary.
101   auto *&Entry = Store[MD];
102   if (Entry) {
103     replaceAllUsesWith(Entry);
104     delete this;
105     return;
106   }
107
108   this->MD = MD;
109   track();
110   Entry = this;
111 }
112
113 void MetadataAsValue::track() {
114   if (MD)
115     MetadataTracking::track(&MD, *MD, *this);
116 }
117
118 void MetadataAsValue::untrack() {
119   if (MD)
120     MetadataTracking::untrack(MD);
121 }
122
123 bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
124   assert(Ref && "Expected live reference");
125   assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
126          "Reference without owner must be direct");
127   if (auto *R = ReplaceableMetadataImpl::get(MD)) {
128     R->addRef(Ref, Owner);
129     return true;
130   }
131   return false;
132 }
133
134 void MetadataTracking::untrack(void *Ref, Metadata &MD) {
135   assert(Ref && "Expected live reference");
136   if (auto *R = ReplaceableMetadataImpl::get(MD))
137     R->dropRef(Ref);
138 }
139
140 bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
141   assert(Ref && "Expected live reference");
142   assert(New && "Expected live reference");
143   assert(Ref != New && "Expected change");
144   if (auto *R = ReplaceableMetadataImpl::get(MD)) {
145     R->moveRef(Ref, New, MD);
146     return true;
147   }
148   return false;
149 }
150
151 bool MetadataTracking::isReplaceable(const Metadata &MD) {
152   return ReplaceableMetadataImpl::get(const_cast<Metadata &>(MD));
153 }
154
155 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
156   bool WasInserted =
157       UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
158           .second;
159   (void)WasInserted;
160   assert(WasInserted && "Expected to add a reference");
161
162   ++NextIndex;
163   assert(NextIndex != 0 && "Unexpected overflow");
164 }
165
166 void ReplaceableMetadataImpl::dropRef(void *Ref) {
167   bool WasErased = UseMap.erase(Ref);
168   (void)WasErased;
169   assert(WasErased && "Expected to drop a reference");
170 }
171
172 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
173                                       const Metadata &MD) {
174   auto I = UseMap.find(Ref);
175   assert(I != UseMap.end() && "Expected to move a reference");
176   auto OwnerAndIndex = I->second;
177   UseMap.erase(I);
178   bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
179   (void)WasInserted;
180   assert(WasInserted && "Expected to add a reference");
181
182   // Check that the references are direct if there's no owner.
183   (void)MD;
184   assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
185          "Reference without owner must be direct");
186   assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
187          "Reference without owner must be direct");
188 }
189
190 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
191   assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
192          "Expected non-temp node");
193
194   if (UseMap.empty())
195     return;
196
197   // Copy out uses since UseMap will get touched below.
198   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
199   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
200   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
201     return L.second.second < R.second.second;
202   });
203   for (const auto &Pair : Uses) {
204     // Check that this Ref hasn't disappeared after RAUW (when updating a
205     // previous Ref).
206     if (!UseMap.count(Pair.first))
207       continue;
208
209     OwnerTy Owner = Pair.second.first;
210     if (!Owner) {
211       // Update unowned tracking references directly.
212       Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
213       Ref = MD;
214       if (MD)
215         MetadataTracking::track(Ref);
216       UseMap.erase(Pair.first);
217       continue;
218     }
219
220     // Check for MetadataAsValue.
221     if (Owner.is<MetadataAsValue *>()) {
222       Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
223       continue;
224     }
225
226     // There's a Metadata owner -- dispatch.
227     Metadata *OwnerMD = Owner.get<Metadata *>();
228     switch (OwnerMD->getMetadataID()) {
229 #define HANDLE_METADATA_LEAF(CLASS)                                            \
230   case Metadata::CLASS##Kind:                                                  \
231     cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD);                \
232     continue;
233 #include "llvm/IR/Metadata.def"
234     default:
235       llvm_unreachable("Invalid metadata subclass");
236     }
237   }
238   assert(UseMap.empty() && "Expected all uses to be replaced");
239 }
240
241 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
242   if (UseMap.empty())
243     return;
244
245   if (!ResolveUsers) {
246     UseMap.clear();
247     return;
248   }
249
250   // Copy out uses since UseMap could get touched below.
251   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
252   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
253   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
254     return L.second.second < R.second.second;
255   });
256   UseMap.clear();
257   for (const auto &Pair : Uses) {
258     auto Owner = Pair.second.first;
259     if (!Owner)
260       continue;
261     if (Owner.is<MetadataAsValue *>())
262       continue;
263
264     // Resolve MDNodes that point at this.
265     auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
266     if (!OwnerMD)
267       continue;
268     if (OwnerMD->isResolved())
269       continue;
270     OwnerMD->decrementUnresolvedOperandCount();
271   }
272 }
273
274 ReplaceableMetadataImpl *ReplaceableMetadataImpl::get(Metadata &MD) {
275   if (auto *N = dyn_cast<MDNode>(&MD))
276     return N->Context.getReplaceableUses();
277   return dyn_cast<ValueAsMetadata>(&MD);
278 }
279
280 static Function *getLocalFunction(Value *V) {
281   assert(V && "Expected value");
282   if (auto *A = dyn_cast<Argument>(V))
283     return A->getParent();
284   if (BasicBlock *BB = cast<Instruction>(V)->getParent())
285     return BB->getParent();
286   return nullptr;
287 }
288
289 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
290   assert(V && "Unexpected null Value");
291
292   auto &Context = V->getContext();
293   auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
294   if (!Entry) {
295     assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
296            "Expected constant or function-local value");
297     assert(!V->IsUsedByMD &&
298            "Expected this to be the only metadata use");
299     V->IsUsedByMD = true;
300     if (auto *C = dyn_cast<Constant>(V))
301       Entry = new ConstantAsMetadata(C);
302     else
303       Entry = new LocalAsMetadata(V);
304   }
305
306   return Entry;
307 }
308
309 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
310   assert(V && "Unexpected null Value");
311   return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
312 }
313
314 void ValueAsMetadata::handleDeletion(Value *V) {
315   assert(V && "Expected valid value");
316
317   auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
318   auto I = Store.find(V);
319   if (I == Store.end())
320     return;
321
322   // Remove old entry from the map.
323   ValueAsMetadata *MD = I->second;
324   assert(MD && "Expected valid metadata");
325   assert(MD->getValue() == V && "Expected valid mapping");
326   Store.erase(I);
327
328   // Delete the metadata.
329   MD->replaceAllUsesWith(nullptr);
330   delete MD;
331 }
332
333 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
334   assert(From && "Expected valid value");
335   assert(To && "Expected valid value");
336   assert(From != To && "Expected changed value");
337   assert(From->getType() == To->getType() && "Unexpected type change");
338
339   LLVMContext &Context = From->getType()->getContext();
340   auto &Store = Context.pImpl->ValuesAsMetadata;
341   auto I = Store.find(From);
342   if (I == Store.end()) {
343     assert(!From->IsUsedByMD &&
344            "Expected From not to be used by metadata");
345     return;
346   }
347
348   // Remove old entry from the map.
349   assert(From->IsUsedByMD &&
350          "Expected From to be used by metadata");
351   From->IsUsedByMD = false;
352   ValueAsMetadata *MD = I->second;
353   assert(MD && "Expected valid metadata");
354   assert(MD->getValue() == From && "Expected valid mapping");
355   Store.erase(I);
356
357   if (isa<LocalAsMetadata>(MD)) {
358     if (auto *C = dyn_cast<Constant>(To)) {
359       // Local became a constant.
360       MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
361       delete MD;
362       return;
363     }
364     if (getLocalFunction(From) && getLocalFunction(To) &&
365         getLocalFunction(From) != getLocalFunction(To)) {
366       // Function changed.
367       MD->replaceAllUsesWith(nullptr);
368       delete MD;
369       return;
370     }
371   } else if (!isa<Constant>(To)) {
372     // Changed to function-local value.
373     MD->replaceAllUsesWith(nullptr);
374     delete MD;
375     return;
376   }
377
378   auto *&Entry = Store[To];
379   if (Entry) {
380     // The target already exists.
381     MD->replaceAllUsesWith(Entry);
382     delete MD;
383     return;
384   }
385
386   // Update MD in place (and update the map entry).
387   assert(!To->IsUsedByMD &&
388          "Expected this to be the only metadata use");
389   To->IsUsedByMD = true;
390   MD->V = To;
391   Entry = MD;
392 }
393
394 //===----------------------------------------------------------------------===//
395 // MDString implementation.
396 //
397
398 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
399   auto &Store = Context.pImpl->MDStringCache;
400   auto I = Store.find(Str);
401   if (I != Store.end())
402     return &I->second;
403
404   auto *Entry =
405       StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
406   bool WasInserted = Store.insert(Entry);
407   (void)WasInserted;
408   assert(WasInserted && "Expected entry to be inserted");
409   Entry->second.Entry = Entry;
410   return &Entry->second;
411 }
412
413 StringRef MDString::getString() const {
414   assert(Entry && "Expected to find string map entry");
415   return Entry->first();
416 }
417
418 //===----------------------------------------------------------------------===//
419 // MDNode implementation.
420 //
421
422 // Assert that the MDNode types will not be unaligned by the objects
423 // prepended to them.
424 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
425   static_assert(                                                               \
426       llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment,   \
427       "Alignment is insufficient after objects prepended to " #CLASS);
428 #include "llvm/IR/Metadata.def"
429
430 void *MDNode::operator new(size_t Size, unsigned NumOps) {
431   size_t OpSize = NumOps * sizeof(MDOperand);
432   // uint64_t is the most aligned type we need support (ensured by static_assert
433   // above)
434   OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
435   void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
436   MDOperand *O = static_cast<MDOperand *>(Ptr);
437   for (MDOperand *E = O - NumOps; O != E; --O)
438     (void)new (O - 1) MDOperand;
439   return Ptr;
440 }
441
442 void MDNode::operator delete(void *Mem) {
443   MDNode *N = static_cast<MDNode *>(Mem);
444   size_t OpSize = N->NumOperands * sizeof(MDOperand);
445   OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
446
447   MDOperand *O = static_cast<MDOperand *>(Mem);
448   for (MDOperand *E = O - N->NumOperands; O != E; --O)
449     (O - 1)->~MDOperand();
450   ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
451 }
452
453 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
454                ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
455     : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
456       NumUnresolved(0), Context(Context) {
457   unsigned Op = 0;
458   for (Metadata *MD : Ops1)
459     setOperand(Op++, MD);
460   for (Metadata *MD : Ops2)
461     setOperand(Op++, MD);
462
463   if (isDistinct())
464     return;
465
466   if (isUniqued())
467     // Check whether any operands are unresolved, requiring re-uniquing.  If
468     // not, don't support RAUW.
469     if (!countUnresolvedOperands())
470       return;
471
472   this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
473 }
474
475 TempMDNode MDNode::clone() const {
476   switch (getMetadataID()) {
477   default:
478     llvm_unreachable("Invalid MDNode subclass");
479 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
480   case CLASS##Kind:                                                            \
481     return cast<CLASS>(this)->cloneImpl();
482 #include "llvm/IR/Metadata.def"
483   }
484 }
485
486 static bool isOperandUnresolved(Metadata *Op) {
487   if (auto *N = dyn_cast_or_null<MDNode>(Op))
488     return !N->isResolved();
489   return false;
490 }
491
492 unsigned MDNode::countUnresolvedOperands() {
493   assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
494   NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
495   return NumUnresolved;
496 }
497
498 void MDNode::makeUniqued() {
499   assert(isTemporary() && "Expected this to be temporary");
500   assert(!isResolved() && "Expected this to be unresolved");
501
502   // Enable uniquing callbacks.
503   for (auto &Op : mutable_operands())
504     Op.reset(Op.get(), this);
505
506   // Make this 'uniqued'.
507   Storage = Uniqued;
508   if (!countUnresolvedOperands())
509     resolve();
510
511   assert(isUniqued() && "Expected this to be uniqued");
512 }
513
514 void MDNode::makeDistinct() {
515   assert(isTemporary() && "Expected this to be temporary");
516   assert(!isResolved() && "Expected this to be unresolved");
517
518   // Pretend to be uniqued, resolve the node, and then store in distinct table.
519   Storage = Uniqued;
520   resolve();
521   storeDistinctInContext();
522
523   assert(isDistinct() && "Expected this to be distinct");
524   assert(isResolved() && "Expected this to be resolved");
525 }
526
527 void MDNode::resolve() {
528   assert(isUniqued() && "Expected this to be uniqued");
529   assert(!isResolved() && "Expected this to be unresolved");
530
531   // Move the map, so that this immediately looks resolved.
532   auto Uses = Context.takeReplaceableUses();
533   NumUnresolved = 0;
534   assert(isResolved() && "Expected this to be resolved");
535
536   // Drop RAUW support.
537   Uses->resolveAllUses();
538 }
539
540 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
541   assert(NumUnresolved != 0 && "Expected unresolved operands");
542
543   // Check if an operand was resolved.
544   if (!isOperandUnresolved(Old)) {
545     if (isOperandUnresolved(New))
546       // An operand was un-resolved!
547       ++NumUnresolved;
548   } else if (!isOperandUnresolved(New))
549     decrementUnresolvedOperandCount();
550 }
551
552 void MDNode::decrementUnresolvedOperandCount() {
553   if (!--NumUnresolved)
554     // Last unresolved operand has just been resolved.
555     resolve();
556 }
557
558 void MDNode::resolveCycles(bool MDMaterialized) {
559   if (isResolved())
560     return;
561
562   // Resolve this node immediately.
563   resolve();
564
565   // Resolve all operands.
566   for (const auto &Op : operands()) {
567     auto *N = dyn_cast_or_null<MDNode>(Op);
568     if (!N)
569       continue;
570
571     if (N->isTemporary() && !MDMaterialized)
572       continue;
573     assert(!N->isTemporary() &&
574            "Expected all forward declarations to be resolved");
575     if (!N->isResolved())
576       N->resolveCycles();
577   }
578 }
579
580 static bool hasSelfReference(MDNode *N) {
581   for (Metadata *MD : N->operands())
582     if (MD == N)
583       return true;
584   return false;
585 }
586
587 MDNode *MDNode::replaceWithPermanentImpl() {
588   switch (getMetadataID()) {
589   default:
590     // If this type isn't uniquable, replace with a distinct node.
591     return replaceWithDistinctImpl();
592
593 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
594   case CLASS##Kind:                                                            \
595     break;
596 #include "llvm/IR/Metadata.def"
597   }
598
599   // Even if this type is uniquable, self-references have to be distinct.
600   if (hasSelfReference(this))
601     return replaceWithDistinctImpl();
602   return replaceWithUniquedImpl();
603 }
604
605 MDNode *MDNode::replaceWithUniquedImpl() {
606   // Try to uniquify in place.
607   MDNode *UniquedNode = uniquify();
608
609   if (UniquedNode == this) {
610     makeUniqued();
611     return this;
612   }
613
614   // Collision, so RAUW instead.
615   replaceAllUsesWith(UniquedNode);
616   deleteAsSubclass();
617   return UniquedNode;
618 }
619
620 MDNode *MDNode::replaceWithDistinctImpl() {
621   makeDistinct();
622   return this;
623 }
624
625 void MDTuple::recalculateHash() {
626   setHash(MDTupleInfo::KeyTy::calculateHash(this));
627 }
628
629 void MDNode::dropAllReferences() {
630   for (unsigned I = 0, E = NumOperands; I != E; ++I)
631     setOperand(I, nullptr);
632   if (!isResolved()) {
633     Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
634     (void)Context.takeReplaceableUses();
635   }
636 }
637
638 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
639   unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
640   assert(Op < getNumOperands() && "Expected valid operand");
641
642   if (!isUniqued()) {
643     // This node is not uniqued.  Just set the operand and be done with it.
644     setOperand(Op, New);
645     return;
646   }
647
648   // This node is uniqued.
649   eraseFromStore();
650
651   Metadata *Old = getOperand(Op);
652   setOperand(Op, New);
653
654   // Drop uniquing for self-reference cycles.
655   if (New == this) {
656     if (!isResolved())
657       resolve();
658     storeDistinctInContext();
659     return;
660   }
661
662   // Re-unique the node.
663   auto *Uniqued = uniquify();
664   if (Uniqued == this) {
665     if (!isResolved())
666       resolveAfterOperandChange(Old, New);
667     return;
668   }
669
670   // Collision.
671   if (!isResolved()) {
672     // Still unresolved, so RAUW.
673     //
674     // First, clear out all operands to prevent any recursion (similar to
675     // dropAllReferences(), but we still need the use-list).
676     for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
677       setOperand(O, nullptr);
678     Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
679     deleteAsSubclass();
680     return;
681   }
682
683   // Store in non-uniqued form if RAUW isn't possible.
684   storeDistinctInContext();
685 }
686
687 void MDNode::deleteAsSubclass() {
688   switch (getMetadataID()) {
689   default:
690     llvm_unreachable("Invalid subclass of MDNode");
691 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
692   case CLASS##Kind:                                                            \
693     delete cast<CLASS>(this);                                                  \
694     break;
695 #include "llvm/IR/Metadata.def"
696   }
697 }
698
699 template <class T, class InfoT>
700 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
701   if (T *U = getUniqued(Store, N))
702     return U;
703
704   Store.insert(N);
705   return N;
706 }
707
708 template <class NodeTy> struct MDNode::HasCachedHash {
709   typedef char Yes[1];
710   typedef char No[2];
711   template <class U, U Val> struct SFINAE {};
712
713   template <class U>
714   static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
715   template <class U> static No &check(...);
716
717   static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
718 };
719
720 MDNode *MDNode::uniquify() {
721   assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
722
723   // Try to insert into uniquing store.
724   switch (getMetadataID()) {
725   default:
726     llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
727 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
728   case CLASS##Kind: {                                                          \
729     CLASS *SubclassThis = cast<CLASS>(this);                                   \
730     std::integral_constant<bool, HasCachedHash<CLASS>::value>                  \
731         ShouldRecalculateHash;                                                 \
732     dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash);              \
733     return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s);           \
734   }
735 #include "llvm/IR/Metadata.def"
736   }
737 }
738
739 void MDNode::eraseFromStore() {
740   switch (getMetadataID()) {
741   default:
742     llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
743 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
744   case CLASS##Kind:                                                            \
745     getContext().pImpl->CLASS##s.erase(cast<CLASS>(this));                     \
746     break;
747 #include "llvm/IR/Metadata.def"
748   }
749 }
750
751 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
752                           StorageType Storage, bool ShouldCreate) {
753   unsigned Hash = 0;
754   if (Storage == Uniqued) {
755     MDTupleInfo::KeyTy Key(MDs);
756     if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
757       return N;
758     if (!ShouldCreate)
759       return nullptr;
760     Hash = Key.getHash();
761   } else {
762     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
763   }
764
765   return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
766                    Storage, Context.pImpl->MDTuples);
767 }
768
769 void MDNode::deleteTemporary(MDNode *N) {
770   assert(N->isTemporary() && "Expected temporary node");
771   N->replaceAllUsesWith(nullptr);
772   N->deleteAsSubclass();
773 }
774
775 void MDNode::storeDistinctInContext() {
776   assert(isResolved() && "Expected resolved nodes");
777   Storage = Distinct;
778
779   // Reset the hash.
780   switch (getMetadataID()) {
781   default:
782     llvm_unreachable("Invalid subclass of MDNode");
783 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
784   case CLASS##Kind: {                                                          \
785     std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
786     dispatchResetHash(cast<CLASS>(this), ShouldResetHash);                     \
787     break;                                                                     \
788   }
789 #include "llvm/IR/Metadata.def"
790   }
791
792   getContext().pImpl->DistinctMDNodes.insert(this);
793 }
794
795 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
796   if (getOperand(I) == New)
797     return;
798
799   if (!isUniqued()) {
800     setOperand(I, New);
801     return;
802   }
803
804   handleChangedOperand(mutable_begin() + I, New);
805 }
806
807 void MDNode::setOperand(unsigned I, Metadata *New) {
808   assert(I < NumOperands);
809   mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
810 }
811
812 /// \brief Get a node, or a self-reference that looks like it.
813 ///
814 /// Special handling for finding self-references, for use by \a
815 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
816 /// when self-referencing nodes were still uniqued.  If the first operand has
817 /// the same operands as \c Ops, return the first operand instead.
818 static MDNode *getOrSelfReference(LLVMContext &Context,
819                                   ArrayRef<Metadata *> Ops) {
820   if (!Ops.empty())
821     if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
822       if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
823         for (unsigned I = 1, E = Ops.size(); I != E; ++I)
824           if (Ops[I] != N->getOperand(I))
825             return MDNode::get(Context, Ops);
826         return N;
827       }
828
829   return MDNode::get(Context, Ops);
830 }
831
832 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
833   if (!A)
834     return B;
835   if (!B)
836     return A;
837
838   SmallVector<Metadata *, 4> MDs;
839   MDs.reserve(A->getNumOperands() + B->getNumOperands());
840   MDs.append(A->op_begin(), A->op_end());
841   MDs.append(B->op_begin(), B->op_end());
842
843   // FIXME: This preserves long-standing behaviour, but is it really the right
844   // behaviour?  Or was that an unintended side-effect of node uniquing?
845   return getOrSelfReference(A->getContext(), MDs);
846 }
847
848 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
849   if (!A || !B)
850     return nullptr;
851
852   SmallVector<Metadata *, 4> MDs;
853   for (Metadata *MD : A->operands())
854     if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
855       MDs.push_back(MD);
856
857   // FIXME: This preserves long-standing behaviour, but is it really the right
858   // behaviour?  Or was that an unintended side-effect of node uniquing?
859   return getOrSelfReference(A->getContext(), MDs);
860 }
861
862 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
863   if (!A || !B)
864     return nullptr;
865
866   SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
867   for (Metadata *MD : A->operands())
868     if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
869       MDs.push_back(MD);
870
871   // FIXME: This preserves long-standing behaviour, but is it really the right
872   // behaviour?  Or was that an unintended side-effect of node uniquing?
873   return getOrSelfReference(A->getContext(), MDs);
874 }
875
876 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
877   if (!A || !B)
878     return nullptr;
879
880   APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
881   APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
882   if (AVal.compare(BVal) == APFloat::cmpLessThan)
883     return A;
884   return B;
885 }
886
887 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
888   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
889 }
890
891 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
892   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
893 }
894
895 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
896                           ConstantInt *Low, ConstantInt *High) {
897   ConstantRange NewRange(Low->getValue(), High->getValue());
898   unsigned Size = EndPoints.size();
899   APInt LB = EndPoints[Size - 2]->getValue();
900   APInt LE = EndPoints[Size - 1]->getValue();
901   ConstantRange LastRange(LB, LE);
902   if (canBeMerged(NewRange, LastRange)) {
903     ConstantRange Union = LastRange.unionWith(NewRange);
904     Type *Ty = High->getType();
905     EndPoints[Size - 2] =
906         cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
907     EndPoints[Size - 1] =
908         cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
909     return true;
910   }
911   return false;
912 }
913
914 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
915                      ConstantInt *Low, ConstantInt *High) {
916   if (!EndPoints.empty())
917     if (tryMergeRange(EndPoints, Low, High))
918       return;
919
920   EndPoints.push_back(Low);
921   EndPoints.push_back(High);
922 }
923
924 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
925   // Given two ranges, we want to compute the union of the ranges. This
926   // is slightly complitade by having to combine the intervals and merge
927   // the ones that overlap.
928
929   if (!A || !B)
930     return nullptr;
931
932   if (A == B)
933     return A;
934
935   // First, walk both lists in older of the lower boundary of each interval.
936   // At each step, try to merge the new interval to the last one we adedd.
937   SmallVector<ConstantInt *, 4> EndPoints;
938   int AI = 0;
939   int BI = 0;
940   int AN = A->getNumOperands() / 2;
941   int BN = B->getNumOperands() / 2;
942   while (AI < AN && BI < BN) {
943     ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
944     ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
945
946     if (ALow->getValue().slt(BLow->getValue())) {
947       addRange(EndPoints, ALow,
948                mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
949       ++AI;
950     } else {
951       addRange(EndPoints, BLow,
952                mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
953       ++BI;
954     }
955   }
956   while (AI < AN) {
957     addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
958              mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
959     ++AI;
960   }
961   while (BI < BN) {
962     addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
963              mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
964     ++BI;
965   }
966
967   // If we have more than 2 ranges (4 endpoints) we have to try to merge
968   // the last and first ones.
969   unsigned Size = EndPoints.size();
970   if (Size > 4) {
971     ConstantInt *FB = EndPoints[0];
972     ConstantInt *FE = EndPoints[1];
973     if (tryMergeRange(EndPoints, FB, FE)) {
974       for (unsigned i = 0; i < Size - 2; ++i) {
975         EndPoints[i] = EndPoints[i + 2];
976       }
977       EndPoints.resize(Size - 2);
978     }
979   }
980
981   // If in the end we have a single range, it is possible that it is now the
982   // full range. Just drop the metadata in that case.
983   if (EndPoints.size() == 2) {
984     ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
985     if (Range.isFullSet())
986       return nullptr;
987   }
988
989   SmallVector<Metadata *, 4> MDs;
990   MDs.reserve(EndPoints.size());
991   for (auto *I : EndPoints)
992     MDs.push_back(ConstantAsMetadata::get(I));
993   return MDNode::get(A->getContext(), MDs);
994 }
995
996 MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
997   if (!A || !B)
998     return nullptr;
999
1000   ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1001   ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1002   if (AVal->getZExtValue() < BVal->getZExtValue())
1003     return A;
1004   return B;
1005 }
1006
1007 //===----------------------------------------------------------------------===//
1008 // NamedMDNode implementation.
1009 //
1010
1011 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1012   return *(SmallVector<TrackingMDRef, 4> *)Operands;
1013 }
1014
1015 NamedMDNode::NamedMDNode(const Twine &N)
1016     : Name(N.str()), Parent(nullptr),
1017       Operands(new SmallVector<TrackingMDRef, 4>()) {}
1018
1019 NamedMDNode::~NamedMDNode() {
1020   dropAllReferences();
1021   delete &getNMDOps(Operands);
1022 }
1023
1024 unsigned NamedMDNode::getNumOperands() const {
1025   return (unsigned)getNMDOps(Operands).size();
1026 }
1027
1028 MDNode *NamedMDNode::getOperand(unsigned i) const {
1029   assert(i < getNumOperands() && "Invalid Operand number!");
1030   auto *N = getNMDOps(Operands)[i].get();
1031   return cast_or_null<MDNode>(N);
1032 }
1033
1034 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1035
1036 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1037   assert(I < getNumOperands() && "Invalid operand number");
1038   getNMDOps(Operands)[I].reset(New);
1039 }
1040
1041 void NamedMDNode::eraseFromParent() {
1042   getParent()->eraseNamedMetadata(this);
1043 }
1044
1045 void NamedMDNode::dropAllReferences() {
1046   getNMDOps(Operands).clear();
1047 }
1048
1049 StringRef NamedMDNode::getName() const {
1050   return StringRef(Name);
1051 }
1052
1053 //===----------------------------------------------------------------------===//
1054 // Instruction Metadata method implementations.
1055 //
1056 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1057   for (auto &I : Attachments)
1058     if (I.first == ID) {
1059       I.second.reset(&MD);
1060       return;
1061     }
1062   Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1063                            std::make_tuple(&MD));
1064 }
1065
1066 void MDAttachmentMap::erase(unsigned ID) {
1067   if (empty())
1068     return;
1069
1070   // Common case is one/last value.
1071   if (Attachments.back().first == ID) {
1072     Attachments.pop_back();
1073     return;
1074   }
1075
1076   for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1077        ++I)
1078     if (I->first == ID) {
1079       *I = std::move(Attachments.back());
1080       Attachments.pop_back();
1081       return;
1082     }
1083 }
1084
1085 MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1086   for (const auto &I : Attachments)
1087     if (I.first == ID)
1088       return I.second;
1089   return nullptr;
1090 }
1091
1092 void MDAttachmentMap::getAll(
1093     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1094   Result.append(Attachments.begin(), Attachments.end());
1095
1096   // Sort the resulting array so it is stable.
1097   if (Result.size() > 1)
1098     array_pod_sort(Result.begin(), Result.end());
1099 }
1100
1101 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1102   if (!Node && !hasMetadata())
1103     return;
1104   setMetadata(getContext().getMDKindID(Kind), Node);
1105 }
1106
1107 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1108   return getMetadataImpl(getContext().getMDKindID(Kind));
1109 }
1110
1111 void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
1112   SmallSet<unsigned, 5> KnownSet;
1113   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1114
1115   if (!hasMetadataHashEntry())
1116     return; // Nothing to remove!
1117
1118   auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1119
1120   if (KnownSet.empty()) {
1121     // Just drop our entry at the store.
1122     InstructionMetadata.erase(this);
1123     setHasMetadataHashEntry(false);
1124     return;
1125   }
1126
1127   auto &Info = InstructionMetadata[this];
1128   Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1129     return !KnownSet.count(I.first);
1130   });
1131
1132   if (Info.empty()) {
1133     // Drop our entry at the store.
1134     InstructionMetadata.erase(this);
1135     setHasMetadataHashEntry(false);
1136   }
1137 }
1138
1139 /// setMetadata - Set the metadata of the specified kind to the specified
1140 /// node.  This updates/replaces metadata if already present, or removes it if
1141 /// Node is null.
1142 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1143   if (!Node && !hasMetadata())
1144     return;
1145
1146   // Handle 'dbg' as a special case since it is not stored in the hash table.
1147   if (KindID == LLVMContext::MD_dbg) {
1148     DbgLoc = DebugLoc(Node);
1149     return;
1150   }
1151   
1152   // Handle the case when we're adding/updating metadata on an instruction.
1153   if (Node) {
1154     auto &Info = getContext().pImpl->InstructionMetadata[this];
1155     assert(!Info.empty() == hasMetadataHashEntry() &&
1156            "HasMetadata bit is wonked");
1157     if (Info.empty())
1158       setHasMetadataHashEntry(true);
1159     Info.set(KindID, *Node);
1160     return;
1161   }
1162
1163   // Otherwise, we're removing metadata from an instruction.
1164   assert((hasMetadataHashEntry() ==
1165           (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
1166          "HasMetadata bit out of date!");
1167   if (!hasMetadataHashEntry())
1168     return;  // Nothing to remove!
1169   auto &Info = getContext().pImpl->InstructionMetadata[this];
1170
1171   // Handle removal of an existing value.
1172   Info.erase(KindID);
1173
1174   if (!Info.empty())
1175     return;
1176
1177   getContext().pImpl->InstructionMetadata.erase(this);
1178   setHasMetadataHashEntry(false);
1179 }
1180
1181 void Instruction::setAAMetadata(const AAMDNodes &N) {
1182   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1183   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1184   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1185 }
1186
1187 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1188   // Handle 'dbg' as a special case since it is not stored in the hash table.
1189   if (KindID == LLVMContext::MD_dbg)
1190     return DbgLoc.getAsMDNode();
1191
1192   if (!hasMetadataHashEntry())
1193     return nullptr;
1194   auto &Info = getContext().pImpl->InstructionMetadata[this];
1195   assert(!Info.empty() && "bit out of sync with hash table");
1196
1197   return Info.lookup(KindID);
1198 }
1199
1200 void Instruction::getAllMetadataImpl(
1201     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1202   Result.clear();
1203   
1204   // Handle 'dbg' as a special case since it is not stored in the hash table.
1205   if (DbgLoc) {
1206     Result.push_back(
1207         std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1208     if (!hasMetadataHashEntry()) return;
1209   }
1210
1211   assert(hasMetadataHashEntry() &&
1212          getContext().pImpl->InstructionMetadata.count(this) &&
1213          "Shouldn't have called this");
1214   const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1215   assert(!Info.empty() && "Shouldn't have called this");
1216   Info.getAll(Result);
1217 }
1218
1219 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1220     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1221   Result.clear();
1222   assert(hasMetadataHashEntry() &&
1223          getContext().pImpl->InstructionMetadata.count(this) &&
1224          "Shouldn't have called this");
1225   const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1226   assert(!Info.empty() && "Shouldn't have called this");
1227   Info.getAll(Result);
1228 }
1229
1230 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1231 /// this instruction.
1232 void Instruction::clearMetadataHashEntries() {
1233   assert(hasMetadataHashEntry() && "Caller should check");
1234   getContext().pImpl->InstructionMetadata.erase(this);
1235   setHasMetadataHashEntry(false);
1236 }
1237
1238 MDNode *Function::getMetadata(unsigned KindID) const {
1239   if (!hasMetadata())
1240     return nullptr;
1241   return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1242 }
1243
1244 MDNode *Function::getMetadata(StringRef Kind) const {
1245   if (!hasMetadata())
1246     return nullptr;
1247   return getMetadata(getContext().getMDKindID(Kind));
1248 }
1249
1250 void Function::setMetadata(unsigned KindID, MDNode *MD) {
1251   if (MD) {
1252     if (!hasMetadata())
1253       setHasMetadataHashEntry(true);
1254
1255     getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1256     return;
1257   }
1258
1259   // Nothing to unset.
1260   if (!hasMetadata())
1261     return;
1262
1263   auto &Store = getContext().pImpl->FunctionMetadata[this];
1264   Store.erase(KindID);
1265   if (Store.empty())
1266     clearMetadata();
1267 }
1268
1269 void Function::setMetadata(StringRef Kind, MDNode *MD) {
1270   if (!MD && !hasMetadata())
1271     return;
1272   setMetadata(getContext().getMDKindID(Kind), MD);
1273 }
1274
1275 void Function::getAllMetadata(
1276     SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1277   MDs.clear();
1278
1279   if (!hasMetadata())
1280     return;
1281
1282   getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1283 }
1284
1285 void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1286   if (!hasMetadata())
1287     return;
1288   if (KnownIDs.empty()) {
1289     clearMetadata();
1290     return;
1291   }
1292
1293   SmallSet<unsigned, 5> KnownSet;
1294   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1295
1296   auto &Store = getContext().pImpl->FunctionMetadata[this];
1297   assert(!Store.empty());
1298
1299   Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1300     return !KnownSet.count(I.first);
1301   });
1302
1303   if (Store.empty())
1304     clearMetadata();
1305 }
1306
1307 void Function::clearMetadata() {
1308   if (!hasMetadata())
1309     return;
1310   getContext().pImpl->FunctionMetadata.erase(this);
1311   setHasMetadataHashEntry(false);
1312 }
1313
1314 void Function::setSubprogram(DISubprogram *SP) {
1315   setMetadata(LLVMContext::MD_dbg, SP);
1316 }
1317
1318 DISubprogram *Function::getSubprogram() const {
1319   return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1320 }