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