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