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->NameAndIsUsedByMD.getInt() &&
260            "Expected this to be the only metadata use");
261     V->NameAndIsUsedByMD.setInt(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->NameAndIsUsedByMD.getInt() &&
306            "Expected From not to be used by metadata");
307     return;
308   }
309 
310   // Remove old entry from the map.
311   assert(From->NameAndIsUsedByMD.getInt() &&
312          "Expected From to be used by metadata");
313   From->NameAndIsUsedByMD.setInt(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->NameAndIsUsedByMD.getInt() &&
350          "Expected this to be the only metadata use");
351   To->NameAndIsUsedByMD.setInt(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 void *MDNode::operator new(size_t Size, unsigned NumOps) {
385   void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
386   MDOperand *O = static_cast<MDOperand *>(Ptr);
387   for (MDOperand *E = O + NumOps; O != E; ++O)
388     (void)new (O) MDOperand;
389   return O;
390 }
391 
392 void MDNode::operator delete(void *Mem) {
393   MDNode *N = static_cast<MDNode *>(Mem);
394   MDOperand *O = static_cast<MDOperand *>(Mem);
395   for (MDOperand *E = O - N->NumOperands; O != E; --O)
396     (O - 1)->~MDOperand();
397   ::operator delete(O);
398 }
399 
400 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
401                ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
402     : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
403       NumUnresolved(0), Context(Context) {
404   unsigned Op = 0;
405   for (Metadata *MD : Ops1)
406     setOperand(Op++, MD);
407   for (Metadata *MD : Ops2)
408     setOperand(Op++, MD);
409 
410   if (isDistinct())
411     return;
412 
413   if (isUniqued())
414     // Check whether any operands are unresolved, requiring re-uniquing.  If
415     // not, don't support RAUW.
416     if (!countUnresolvedOperands())
417       return;
418 
419   this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
420 }
421 
422 TempMDNode MDNode::clone() const {
423   switch (getMetadataID()) {
424   default:
425     llvm_unreachable("Invalid MDNode subclass");
426 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
427   case CLASS##Kind:                                                            \
428     return cast<CLASS>(this)->cloneImpl();
429 #include "llvm/IR/Metadata.def"
430   }
431 }
432 
433 static bool isOperandUnresolved(Metadata *Op) {
434   if (auto *N = dyn_cast_or_null<MDNode>(Op))
435     return !N->isResolved();
436   return false;
437 }
438 
439 unsigned MDNode::countUnresolvedOperands() {
440   assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
441   NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
442   return NumUnresolved;
443 }
444 
445 void MDNode::makeUniqued() {
446   assert(isTemporary() && "Expected this to be temporary");
447   assert(!isResolved() && "Expected this to be unresolved");
448 
449   // Make this 'uniqued'.
450   Storage = Uniqued;
451   if (!countUnresolvedOperands())
452     resolve();
453 
454   assert(isUniqued() && "Expected this to be uniqued");
455 }
456 
457 void MDNode::makeDistinct() {
458   assert(isTemporary() && "Expected this to be temporary");
459   assert(!isResolved() && "Expected this to be unresolved");
460 
461   // Pretend to be uniqued, resolve the node, and then store in distinct table.
462   Storage = Uniqued;
463   resolve();
464   storeDistinctInContext();
465 
466   assert(isDistinct() && "Expected this to be distinct");
467   assert(isResolved() && "Expected this to be resolved");
468 }
469 
470 void MDNode::resolve() {
471   assert(isUniqued() && "Expected this to be uniqued");
472   assert(!isResolved() && "Expected this to be unresolved");
473 
474   // Move the map, so that this immediately looks resolved.
475   auto Uses = Context.takeReplaceableUses();
476   NumUnresolved = 0;
477   assert(isResolved() && "Expected this to be resolved");
478 
479   // Drop RAUW support.
480   Uses->resolveAllUses();
481 }
482 
483 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
484   assert(NumUnresolved != 0 && "Expected unresolved operands");
485 
486   // Check if an operand was resolved.
487   if (!isOperandUnresolved(Old)) {
488     if (isOperandUnresolved(New))
489       // An operand was un-resolved!
490       ++NumUnresolved;
491   } else if (!isOperandUnresolved(New))
492     decrementUnresolvedOperandCount();
493 }
494 
495 void MDNode::decrementUnresolvedOperandCount() {
496   if (!--NumUnresolved)
497     // Last unresolved operand has just been resolved.
498     resolve();
499 }
500 
501 void MDNode::resolveCycles() {
502   if (isResolved())
503     return;
504 
505   // Resolve this node immediately.
506   resolve();
507 
508   // Resolve all operands.
509   for (const auto &Op : operands()) {
510     auto *N = dyn_cast_or_null<MDNode>(Op);
511     if (!N)
512       continue;
513 
514     assert(!N->isTemporary() &&
515            "Expected all forward declarations to be resolved");
516     if (!N->isResolved())
517       N->resolveCycles();
518   }
519 }
520 
521 MDNode *MDNode::replaceWithUniquedImpl() {
522   // Try to uniquify in place.
523   MDNode *UniquedNode = uniquify();
524   if (UniquedNode == this) {
525     makeUniqued();
526     return this;
527   }
528 
529   // Collision, so RAUW instead.
530   replaceAllUsesWith(UniquedNode);
531   deleteAsSubclass();
532   return UniquedNode;
533 }
534 
535 MDNode *MDNode::replaceWithDistinctImpl() {
536   makeDistinct();
537   return this;
538 }
539 
540 void MDTuple::recalculateHash() {
541   setHash(MDTupleInfo::KeyTy::calculateHash(this));
542 }
543 
544 void MDNode::dropAllReferences() {
545   for (unsigned I = 0, E = NumOperands; I != E; ++I)
546     setOperand(I, nullptr);
547   if (!isResolved()) {
548     Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
549     (void)Context.takeReplaceableUses();
550   }
551 }
552 
553 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
554   unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
555   assert(Op < getNumOperands() && "Expected valid operand");
556 
557   if (!isUniqued()) {
558     // This node is not uniqued.  Just set the operand and be done with it.
559     setOperand(Op, New);
560     return;
561   }
562 
563   // This node is uniqued.
564   eraseFromStore();
565 
566   Metadata *Old = getOperand(Op);
567   setOperand(Op, New);
568 
569   // Drop uniquing for self-reference cycles.
570   if (New == this) {
571     if (!isResolved())
572       resolve();
573     storeDistinctInContext();
574     return;
575   }
576 
577   // Re-unique the node.
578   auto *Uniqued = uniquify();
579   if (Uniqued == this) {
580     if (!isResolved())
581       resolveAfterOperandChange(Old, New);
582     return;
583   }
584 
585   // Collision.
586   if (!isResolved()) {
587     // Still unresolved, so RAUW.
588     //
589     // First, clear out all operands to prevent any recursion (similar to
590     // dropAllReferences(), but we still need the use-list).
591     for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
592       setOperand(O, nullptr);
593     Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
594     deleteAsSubclass();
595     return;
596   }
597 
598   // Store in non-uniqued form if RAUW isn't possible.
599   storeDistinctInContext();
600 }
601 
602 void MDNode::deleteAsSubclass() {
603   switch (getMetadataID()) {
604   default:
605     llvm_unreachable("Invalid subclass of MDNode");
606 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
607   case CLASS##Kind:                                                            \
608     delete cast<CLASS>(this);                                                  \
609     break;
610 #include "llvm/IR/Metadata.def"
611   }
612 }
613 
614 template <class T, class InfoT>
615 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
616   if (T *U = getUniqued(Store, N))
617     return U;
618 
619   Store.insert(N);
620   return N;
621 }
622 
623 template <class NodeTy> struct MDNode::HasCachedHash {
624   typedef char Yes[1];
625   typedef char No[2];
626   template <class U, U Val> struct SFINAE {};
627 
628   template <class U>
629   static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
630   template <class U> static No &check(...);
631 
632   static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
633 };
634 
635 MDNode *MDNode::uniquify() {
636   // Try to insert into uniquing store.
637   switch (getMetadataID()) {
638   default:
639     llvm_unreachable("Invalid subclass of MDNode");
640 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
641   case CLASS##Kind: {                                                          \
642     CLASS *SubclassThis = cast<CLASS>(this);                                   \
643     std::integral_constant<bool, HasCachedHash<CLASS>::value>                  \
644         ShouldRecalculateHash;                                                 \
645     dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash);              \
646     return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s);           \
647   }
648 #include "llvm/IR/Metadata.def"
649   }
650 }
651 
652 void MDNode::eraseFromStore() {
653   switch (getMetadataID()) {
654   default:
655     llvm_unreachable("Invalid subclass of MDNode");
656 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
657   case CLASS##Kind:                                                            \
658     getContext().pImpl->CLASS##s.erase(cast<CLASS>(this));                     \
659     break;
660 #include "llvm/IR/Metadata.def"
661   }
662 }
663 
664 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
665                           StorageType Storage, bool ShouldCreate) {
666   unsigned Hash = 0;
667   if (Storage == Uniqued) {
668     MDTupleInfo::KeyTy Key(MDs);
669     if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
670       return N;
671     if (!ShouldCreate)
672       return nullptr;
673     Hash = Key.getHash();
674   } else {
675     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
676   }
677 
678   return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
679                    Storage, Context.pImpl->MDTuples);
680 }
681 
682 void MDNode::deleteTemporary(MDNode *N) {
683   assert(N->isTemporary() && "Expected temporary node");
684   N->replaceAllUsesWith(nullptr);
685   N->deleteAsSubclass();
686 }
687 
688 void MDNode::storeDistinctInContext() {
689   assert(isResolved() && "Expected resolved nodes");
690   Storage = Distinct;
691 
692   // Reset the hash.
693   switch (getMetadataID()) {
694   default:
695     llvm_unreachable("Invalid subclass of MDNode");
696 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
697   case CLASS##Kind: {                                                          \
698     std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
699     dispatchResetHash(cast<CLASS>(this), ShouldResetHash);                     \
700     break;                                                                     \
701   }
702 #include "llvm/IR/Metadata.def"
703   }
704 
705   getContext().pImpl->DistinctMDNodes.insert(this);
706 }
707 
708 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
709   if (getOperand(I) == New)
710     return;
711 
712   if (!isUniqued()) {
713     setOperand(I, New);
714     return;
715   }
716 
717   handleChangedOperand(mutable_begin() + I, New);
718 }
719 
720 void MDNode::setOperand(unsigned I, Metadata *New) {
721   assert(I < NumOperands);
722   mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
723 }
724 
725 /// \brief Get a node, or a self-reference that looks like it.
726 ///
727 /// Special handling for finding self-references, for use by \a
728 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
729 /// when self-referencing nodes were still uniqued.  If the first operand has
730 /// the same operands as \c Ops, return the first operand instead.
731 static MDNode *getOrSelfReference(LLVMContext &Context,
732                                   ArrayRef<Metadata *> Ops) {
733   if (!Ops.empty())
734     if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
735       if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
736         for (unsigned I = 1, E = Ops.size(); I != E; ++I)
737           if (Ops[I] != N->getOperand(I))
738             return MDNode::get(Context, Ops);
739         return N;
740       }
741 
742   return MDNode::get(Context, Ops);
743 }
744 
745 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
746   if (!A)
747     return B;
748   if (!B)
749     return A;
750 
751   SmallVector<Metadata *, 4> MDs;
752   MDs.reserve(A->getNumOperands() + B->getNumOperands());
753   MDs.append(A->op_begin(), A->op_end());
754   MDs.append(B->op_begin(), B->op_end());
755 
756   // FIXME: This preserves long-standing behaviour, but is it really the right
757   // behaviour?  Or was that an unintended side-effect of node uniquing?
758   return getOrSelfReference(A->getContext(), MDs);
759 }
760 
761 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
762   if (!A || !B)
763     return nullptr;
764 
765   SmallVector<Metadata *, 4> MDs;
766   for (Metadata *MD : A->operands())
767     if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
768       MDs.push_back(MD);
769 
770   // FIXME: This preserves long-standing behaviour, but is it really the right
771   // behaviour?  Or was that an unintended side-effect of node uniquing?
772   return getOrSelfReference(A->getContext(), MDs);
773 }
774 
775 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
776   if (!A || !B)
777     return nullptr;
778 
779   SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
780   for (Metadata *MD : A->operands())
781     if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
782       MDs.push_back(MD);
783 
784   // FIXME: This preserves long-standing behaviour, but is it really the right
785   // behaviour?  Or was that an unintended side-effect of node uniquing?
786   return getOrSelfReference(A->getContext(), MDs);
787 }
788 
789 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
790   if (!A || !B)
791     return nullptr;
792 
793   APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
794   APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
795   if (AVal.compare(BVal) == APFloat::cmpLessThan)
796     return A;
797   return B;
798 }
799 
800 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
801   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
802 }
803 
804 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
805   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
806 }
807 
808 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
809                           ConstantInt *Low, ConstantInt *High) {
810   ConstantRange NewRange(Low->getValue(), High->getValue());
811   unsigned Size = EndPoints.size();
812   APInt LB = EndPoints[Size - 2]->getValue();
813   APInt LE = EndPoints[Size - 1]->getValue();
814   ConstantRange LastRange(LB, LE);
815   if (canBeMerged(NewRange, LastRange)) {
816     ConstantRange Union = LastRange.unionWith(NewRange);
817     Type *Ty = High->getType();
818     EndPoints[Size - 2] =
819         cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
820     EndPoints[Size - 1] =
821         cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
822     return true;
823   }
824   return false;
825 }
826 
827 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
828                      ConstantInt *Low, ConstantInt *High) {
829   if (!EndPoints.empty())
830     if (tryMergeRange(EndPoints, Low, High))
831       return;
832 
833   EndPoints.push_back(Low);
834   EndPoints.push_back(High);
835 }
836 
837 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
838   // Given two ranges, we want to compute the union of the ranges. This
839   // is slightly complitade by having to combine the intervals and merge
840   // the ones that overlap.
841 
842   if (!A || !B)
843     return nullptr;
844 
845   if (A == B)
846     return A;
847 
848   // First, walk both lists in older of the lower boundary of each interval.
849   // At each step, try to merge the new interval to the last one we adedd.
850   SmallVector<ConstantInt *, 4> EndPoints;
851   int AI = 0;
852   int BI = 0;
853   int AN = A->getNumOperands() / 2;
854   int BN = B->getNumOperands() / 2;
855   while (AI < AN && BI < BN) {
856     ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
857     ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
858 
859     if (ALow->getValue().slt(BLow->getValue())) {
860       addRange(EndPoints, ALow,
861                mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
862       ++AI;
863     } else {
864       addRange(EndPoints, BLow,
865                mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
866       ++BI;
867     }
868   }
869   while (AI < AN) {
870     addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
871              mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
872     ++AI;
873   }
874   while (BI < BN) {
875     addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
876              mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
877     ++BI;
878   }
879 
880   // If we have more than 2 ranges (4 endpoints) we have to try to merge
881   // the last and first ones.
882   unsigned Size = EndPoints.size();
883   if (Size > 4) {
884     ConstantInt *FB = EndPoints[0];
885     ConstantInt *FE = EndPoints[1];
886     if (tryMergeRange(EndPoints, FB, FE)) {
887       for (unsigned i = 0; i < Size - 2; ++i) {
888         EndPoints[i] = EndPoints[i + 2];
889       }
890       EndPoints.resize(Size - 2);
891     }
892   }
893 
894   // If in the end we have a single range, it is possible that it is now the
895   // full range. Just drop the metadata in that case.
896   if (EndPoints.size() == 2) {
897     ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
898     if (Range.isFullSet())
899       return nullptr;
900   }
901 
902   SmallVector<Metadata *, 4> MDs;
903   MDs.reserve(EndPoints.size());
904   for (auto *I : EndPoints)
905     MDs.push_back(ConstantAsMetadata::get(I));
906   return MDNode::get(A->getContext(), MDs);
907 }
908 
909 //===----------------------------------------------------------------------===//
910 // NamedMDNode implementation.
911 //
912 
913 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
914   return *(SmallVector<TrackingMDRef, 4> *)Operands;
915 }
916 
917 NamedMDNode::NamedMDNode(const Twine &N)
918     : Name(N.str()), Parent(nullptr),
919       Operands(new SmallVector<TrackingMDRef, 4>()) {}
920 
921 NamedMDNode::~NamedMDNode() {
922   dropAllReferences();
923   delete &getNMDOps(Operands);
924 }
925 
926 unsigned NamedMDNode::getNumOperands() const {
927   return (unsigned)getNMDOps(Operands).size();
928 }
929 
930 MDNode *NamedMDNode::getOperand(unsigned i) const {
931   assert(i < getNumOperands() && "Invalid Operand number!");
932   auto *N = getNMDOps(Operands)[i].get();
933   return cast_or_null<MDNode>(N);
934 }
935 
936 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
937 
938 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
939   assert(I < getNumOperands() && "Invalid operand number");
940   getNMDOps(Operands)[I].reset(New);
941 }
942 
943 void NamedMDNode::eraseFromParent() {
944   getParent()->eraseNamedMetadata(this);
945 }
946 
947 void NamedMDNode::dropAllReferences() {
948   getNMDOps(Operands).clear();
949 }
950 
951 StringRef NamedMDNode::getName() const {
952   return StringRef(Name);
953 }
954 
955 //===----------------------------------------------------------------------===//
956 // Instruction Metadata method implementations.
957 //
958 
959 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
960   if (!Node && !hasMetadata())
961     return;
962   setMetadata(getContext().getMDKindID(Kind), Node);
963 }
964 
965 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
966   return getMetadataImpl(getContext().getMDKindID(Kind));
967 }
968 
969 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
970   SmallSet<unsigned, 5> KnownSet;
971   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
972 
973   // Drop debug if needed
974   if (KnownSet.erase(LLVMContext::MD_dbg))
975     DbgLoc = DebugLoc();
976 
977   if (!hasMetadataHashEntry())
978     return; // Nothing to remove!
979 
980   DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
981       getContext().pImpl->MetadataStore;
982 
983   if (KnownSet.empty()) {
984     // Just drop our entry at the store.
985     MetadataStore.erase(this);
986     setHasMetadataHashEntry(false);
987     return;
988   }
989 
990   LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
991   unsigned I;
992   unsigned E;
993   // Walk the array and drop any metadata we don't know.
994   for (I = 0, E = Info.size(); I != E;) {
995     if (KnownSet.count(Info[I].first)) {
996       ++I;
997       continue;
998     }
999 
1000     Info[I] = std::move(Info.back());
1001     Info.pop_back();
1002     --E;
1003   }
1004   assert(E == Info.size());
1005 
1006   if (E == 0) {
1007     // Drop our entry at the store.
1008     MetadataStore.erase(this);
1009     setHasMetadataHashEntry(false);
1010   }
1011 }
1012 
1013 /// setMetadata - Set the metadata of of the specified kind to the specified
1014 /// node.  This updates/replaces metadata if already present, or removes it if
1015 /// Node is null.
1016 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1017   if (!Node && !hasMetadata())
1018     return;
1019 
1020   // Handle 'dbg' as a special case since it is not stored in the hash table.
1021   if (KindID == LLVMContext::MD_dbg) {
1022     DbgLoc = DebugLoc::getFromDILocation(Node);
1023     return;
1024   }
1025 
1026   // Handle the case when we're adding/updating metadata on an instruction.
1027   if (Node) {
1028     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1029     assert(!Info.empty() == hasMetadataHashEntry() &&
1030            "HasMetadata bit is wonked");
1031     if (Info.empty()) {
1032       setHasMetadataHashEntry(true);
1033     } else {
1034       // Handle replacement of an existing value.
1035       for (auto &P : Info)
1036         if (P.first == KindID) {
1037           P.second.reset(Node);
1038           return;
1039         }
1040     }
1041 
1042     // No replacement, just add it to the list.
1043     Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
1044                       std::make_tuple(Node));
1045     return;
1046   }
1047 
1048   // Otherwise, we're removing metadata from an instruction.
1049   assert((hasMetadataHashEntry() ==
1050           (getContext().pImpl->MetadataStore.count(this) > 0)) &&
1051          "HasMetadata bit out of date!");
1052   if (!hasMetadataHashEntry())
1053     return;  // Nothing to remove!
1054   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1055 
1056   // Common case is removing the only entry.
1057   if (Info.size() == 1 && Info[0].first == KindID) {
1058     getContext().pImpl->MetadataStore.erase(this);
1059     setHasMetadataHashEntry(false);
1060     return;
1061   }
1062 
1063   // Handle removal of an existing value.
1064   for (unsigned i = 0, e = Info.size(); i != e; ++i)
1065     if (Info[i].first == KindID) {
1066       Info[i] = std::move(Info.back());
1067       Info.pop_back();
1068       assert(!Info.empty() && "Removing last entry should be handled above");
1069       return;
1070     }
1071   // Otherwise, removing an entry that doesn't exist on the instruction.
1072 }
1073 
1074 void Instruction::setAAMetadata(const AAMDNodes &N) {
1075   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1076   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1077   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1078 }
1079 
1080 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1081   // Handle 'dbg' as a special case since it is not stored in the hash table.
1082   if (KindID == LLVMContext::MD_dbg)
1083     return DbgLoc.getAsMDNode();
1084 
1085   if (!hasMetadataHashEntry()) return nullptr;
1086 
1087   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
1088   assert(!Info.empty() && "bit out of sync with hash table");
1089 
1090   for (const auto &I : Info)
1091     if (I.first == KindID)
1092       return I.second;
1093   return nullptr;
1094 }
1095 
1096 void Instruction::getAllMetadataImpl(
1097     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1098   Result.clear();
1099 
1100   // Handle 'dbg' as a special case since it is not stored in the hash table.
1101   if (!DbgLoc.isUnknown()) {
1102     Result.push_back(
1103         std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1104     if (!hasMetadataHashEntry()) return;
1105   }
1106 
1107   assert(hasMetadataHashEntry() &&
1108          getContext().pImpl->MetadataStore.count(this) &&
1109          "Shouldn't have called this");
1110   const LLVMContextImpl::MDMapTy &Info =
1111     getContext().pImpl->MetadataStore.find(this)->second;
1112   assert(!Info.empty() && "Shouldn't have called this");
1113 
1114   Result.reserve(Result.size() + Info.size());
1115   for (auto &I : Info)
1116     Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1117 
1118   // Sort the resulting array so it is stable.
1119   if (Result.size() > 1)
1120     array_pod_sort(Result.begin(), Result.end());
1121 }
1122 
1123 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1124     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1125   Result.clear();
1126   assert(hasMetadataHashEntry() &&
1127          getContext().pImpl->MetadataStore.count(this) &&
1128          "Shouldn't have called this");
1129   const LLVMContextImpl::MDMapTy &Info =
1130     getContext().pImpl->MetadataStore.find(this)->second;
1131   assert(!Info.empty() && "Shouldn't have called this");
1132   Result.reserve(Result.size() + Info.size());
1133   for (auto &I : Info)
1134     Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
1135 
1136   // Sort the resulting array so it is stable.
1137   if (Result.size() > 1)
1138     array_pod_sort(Result.begin(), Result.end());
1139 }
1140 
1141 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
1142 /// this instruction.
1143 void Instruction::clearMetadataHashEntries() {
1144   assert(hasMetadataHashEntry() && "Caller should check");
1145   getContext().pImpl->MetadataStore.erase(this);
1146   setHasMetadataHashEntry(false);
1147 }
1148