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   return concatenate(A, B);
930 }
931 
932 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
933   if (!A || !B)
934     return nullptr;
935 
936   APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
937   APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
938   if (AVal < BVal)
939     return A;
940   return B;
941 }
942 
943 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
944   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
945 }
946 
947 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
948   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
949 }
950 
951 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
952                           ConstantInt *Low, ConstantInt *High) {
953   ConstantRange NewRange(Low->getValue(), High->getValue());
954   unsigned Size = EndPoints.size();
955   APInt LB = EndPoints[Size - 2]->getValue();
956   APInt LE = EndPoints[Size - 1]->getValue();
957   ConstantRange LastRange(LB, LE);
958   if (canBeMerged(NewRange, LastRange)) {
959     ConstantRange Union = LastRange.unionWith(NewRange);
960     Type *Ty = High->getType();
961     EndPoints[Size - 2] =
962         cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
963     EndPoints[Size - 1] =
964         cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
965     return true;
966   }
967   return false;
968 }
969 
970 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
971                      ConstantInt *Low, ConstantInt *High) {
972   if (!EndPoints.empty())
973     if (tryMergeRange(EndPoints, Low, High))
974       return;
975 
976   EndPoints.push_back(Low);
977   EndPoints.push_back(High);
978 }
979 
980 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
981   // Given two ranges, we want to compute the union of the ranges. This
982   // is slightly complicated by having to combine the intervals and merge
983   // the ones that overlap.
984 
985   if (!A || !B)
986     return nullptr;
987 
988   if (A == B)
989     return A;
990 
991   // First, walk both lists in order of the lower boundary of each interval.
992   // At each step, try to merge the new interval to the last one we adedd.
993   SmallVector<ConstantInt *, 4> EndPoints;
994   int AI = 0;
995   int BI = 0;
996   int AN = A->getNumOperands() / 2;
997   int BN = B->getNumOperands() / 2;
998   while (AI < AN && BI < BN) {
999     ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
1000     ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
1001 
1002     if (ALow->getValue().slt(BLow->getValue())) {
1003       addRange(EndPoints, ALow,
1004                mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1005       ++AI;
1006     } else {
1007       addRange(EndPoints, BLow,
1008                mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1009       ++BI;
1010     }
1011   }
1012   while (AI < AN) {
1013     addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1014              mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1015     ++AI;
1016   }
1017   while (BI < BN) {
1018     addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1019              mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1020     ++BI;
1021   }
1022 
1023   // If we have more than 2 ranges (4 endpoints) we have to try to merge
1024   // the last and first ones.
1025   unsigned Size = EndPoints.size();
1026   if (Size > 4) {
1027     ConstantInt *FB = EndPoints[0];
1028     ConstantInt *FE = EndPoints[1];
1029     if (tryMergeRange(EndPoints, FB, FE)) {
1030       for (unsigned i = 0; i < Size - 2; ++i) {
1031         EndPoints[i] = EndPoints[i + 2];
1032       }
1033       EndPoints.resize(Size - 2);
1034     }
1035   }
1036 
1037   // If in the end we have a single range, it is possible that it is now the
1038   // full range. Just drop the metadata in that case.
1039   if (EndPoints.size() == 2) {
1040     ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1041     if (Range.isFullSet())
1042       return nullptr;
1043   }
1044 
1045   SmallVector<Metadata *, 4> MDs;
1046   MDs.reserve(EndPoints.size());
1047   for (auto *I : EndPoints)
1048     MDs.push_back(ConstantAsMetadata::get(I));
1049   return MDNode::get(A->getContext(), MDs);
1050 }
1051 
1052 MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1053   if (!A || !B)
1054     return nullptr;
1055 
1056   ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1057   ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1058   if (AVal->getZExtValue() < BVal->getZExtValue())
1059     return A;
1060   return B;
1061 }
1062 
1063 //===----------------------------------------------------------------------===//
1064 // NamedMDNode implementation.
1065 //
1066 
1067 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1068   return *(SmallVector<TrackingMDRef, 4> *)Operands;
1069 }
1070 
1071 NamedMDNode::NamedMDNode(const Twine &N)
1072     : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1073 
1074 NamedMDNode::~NamedMDNode() {
1075   dropAllReferences();
1076   delete &getNMDOps(Operands);
1077 }
1078 
1079 unsigned NamedMDNode::getNumOperands() const {
1080   return (unsigned)getNMDOps(Operands).size();
1081 }
1082 
1083 MDNode *NamedMDNode::getOperand(unsigned i) const {
1084   assert(i < getNumOperands() && "Invalid Operand number!");
1085   auto *N = getNMDOps(Operands)[i].get();
1086   return cast_or_null<MDNode>(N);
1087 }
1088 
1089 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1090 
1091 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1092   assert(I < getNumOperands() && "Invalid operand number");
1093   getNMDOps(Operands)[I].reset(New);
1094 }
1095 
1096 void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
1097 
1098 void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1099 
1100 StringRef NamedMDNode::getName() const { return StringRef(Name); }
1101 
1102 //===----------------------------------------------------------------------===//
1103 // Instruction Metadata method implementations.
1104 //
1105 
1106 MDNode *MDAttachments::lookup(unsigned ID) const {
1107   for (const auto &A : Attachments)
1108     if (A.MDKind == ID)
1109       return A.Node;
1110   return nullptr;
1111 }
1112 
1113 void MDAttachments::get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const {
1114   for (const auto &A : Attachments)
1115     if (A.MDKind == ID)
1116       Result.push_back(A.Node);
1117 }
1118 
1119 void MDAttachments::getAll(
1120     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1121   for (const auto &A : Attachments)
1122     Result.emplace_back(A.MDKind, A.Node);
1123 
1124   // Sort the resulting array so it is stable with respect to metadata IDs. We
1125   // need to preserve the original insertion order though.
1126   if (Result.size() > 1)
1127     llvm::stable_sort(Result, less_first());
1128 }
1129 
1130 void MDAttachments::set(unsigned ID, MDNode *MD) {
1131   erase(ID);
1132   if (MD)
1133     insert(ID, *MD);
1134 }
1135 
1136 void MDAttachments::insert(unsigned ID, MDNode &MD) {
1137   Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1138 }
1139 
1140 bool MDAttachments::erase(unsigned ID) {
1141   if (empty())
1142     return false;
1143 
1144   // Common case is one value.
1145   if (Attachments.size() == 1 && Attachments.back().MDKind == ID) {
1146     Attachments.pop_back();
1147     return true;
1148   }
1149 
1150   auto I = std::remove_if(Attachments.begin(), Attachments.end(),
1151                           [ID](const Attachment &A) { return A.MDKind == ID; });
1152   bool Changed = I != Attachments.end();
1153   Attachments.erase(I, Attachments.end());
1154   return Changed;
1155 }
1156 
1157 MDNode *Value::getMetadata(unsigned KindID) const {
1158   if (!hasMetadata())
1159     return nullptr;
1160   const auto &Info = getContext().pImpl->ValueMetadata[this];
1161   assert(!Info.empty() && "bit out of sync with hash table");
1162   return Info.lookup(KindID);
1163 }
1164 
1165 MDNode *Value::getMetadata(StringRef Kind) const {
1166   if (!hasMetadata())
1167     return nullptr;
1168   const auto &Info = getContext().pImpl->ValueMetadata[this];
1169   assert(!Info.empty() && "bit out of sync with hash table");
1170   return Info.lookup(getContext().getMDKindID(Kind));
1171 }
1172 
1173 void Value::getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const {
1174   if (hasMetadata())
1175     getContext().pImpl->ValueMetadata[this].get(KindID, MDs);
1176 }
1177 
1178 void Value::getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const {
1179   if (hasMetadata())
1180     getMetadata(getContext().getMDKindID(Kind), MDs);
1181 }
1182 
1183 void Value::getAllMetadata(
1184     SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1185   if (hasMetadata()) {
1186     assert(getContext().pImpl->ValueMetadata.count(this) &&
1187            "bit out of sync with hash table");
1188     const auto &Info = getContext().pImpl->ValueMetadata.find(this)->second;
1189     assert(!Info.empty() && "Shouldn't have called this");
1190     Info.getAll(MDs);
1191   }
1192 }
1193 
1194 void Value::setMetadata(unsigned KindID, MDNode *Node) {
1195   assert(isa<Instruction>(this) || isa<GlobalObject>(this));
1196 
1197   // Handle the case when we're adding/updating metadata on a value.
1198   if (Node) {
1199     auto &Info = getContext().pImpl->ValueMetadata[this];
1200     assert(!Info.empty() == HasMetadata && "bit out of sync with hash table");
1201     if (Info.empty())
1202       HasMetadata = true;
1203     Info.set(KindID, Node);
1204     return;
1205   }
1206 
1207   // Otherwise, we're removing metadata from an instruction.
1208   assert((HasMetadata == (getContext().pImpl->ValueMetadata.count(this) > 0)) &&
1209          "bit out of sync with hash table");
1210   if (!HasMetadata)
1211     return; // Nothing to remove!
1212   auto &Info = getContext().pImpl->ValueMetadata[this];
1213 
1214   // Handle removal of an existing value.
1215   Info.erase(KindID);
1216   if (!Info.empty())
1217     return;
1218   getContext().pImpl->ValueMetadata.erase(this);
1219   HasMetadata = false;
1220 }
1221 
1222 void Value::setMetadata(StringRef Kind, MDNode *Node) {
1223   if (!Node && !HasMetadata)
1224     return;
1225   setMetadata(getContext().getMDKindID(Kind), Node);
1226 }
1227 
1228 void Value::addMetadata(unsigned KindID, MDNode &MD) {
1229   assert(isa<Instruction>(this) || isa<GlobalObject>(this));
1230   if (!HasMetadata)
1231     HasMetadata = true;
1232   getContext().pImpl->ValueMetadata[this].insert(KindID, MD);
1233 }
1234 
1235 void Value::addMetadata(StringRef Kind, MDNode &MD) {
1236   addMetadata(getContext().getMDKindID(Kind), MD);
1237 }
1238 
1239 bool Value::eraseMetadata(unsigned KindID) {
1240   // Nothing to unset.
1241   if (!HasMetadata)
1242     return false;
1243 
1244   auto &Store = getContext().pImpl->ValueMetadata[this];
1245   bool Changed = Store.erase(KindID);
1246   if (Store.empty())
1247     clearMetadata();
1248   return Changed;
1249 }
1250 
1251 void Value::clearMetadata() {
1252   if (!HasMetadata)
1253     return;
1254   assert(getContext().pImpl->ValueMetadata.count(this) &&
1255          "bit out of sync with hash table");
1256   getContext().pImpl->ValueMetadata.erase(this);
1257   HasMetadata = false;
1258 }
1259 
1260 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1261   if (!Node && !hasMetadata())
1262     return;
1263   setMetadata(getContext().getMDKindID(Kind), Node);
1264 }
1265 
1266 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1267   return getMetadataImpl(getContext().getMDKindID(Kind));
1268 }
1269 
1270 void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
1271   if (!Value::hasMetadata())
1272     return; // Nothing to remove!
1273 
1274   if (KnownIDs.empty()) {
1275     // Just drop our entry at the store.
1276     clearMetadata();
1277     return;
1278   }
1279 
1280   SmallSet<unsigned, 4> KnownSet;
1281   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1282 
1283   auto &MetadataStore = getContext().pImpl->ValueMetadata;
1284   auto &Info = MetadataStore[this];
1285   assert(!Info.empty() && "bit out of sync with hash table");
1286   Info.remove_if([&KnownSet](const MDAttachments::Attachment &I) {
1287     return !KnownSet.count(I.MDKind);
1288   });
1289 
1290   if (Info.empty()) {
1291     // Drop our entry at the store.
1292     clearMetadata();
1293   }
1294 }
1295 
1296 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1297   if (!Node && !hasMetadata())
1298     return;
1299 
1300   // Handle 'dbg' as a special case since it is not stored in the hash table.
1301   if (KindID == LLVMContext::MD_dbg) {
1302     DbgLoc = DebugLoc(Node);
1303     return;
1304   }
1305 
1306   Value::setMetadata(KindID, Node);
1307 }
1308 
1309 void Instruction::addAnnotationMetadata(StringRef Name) {
1310   MDBuilder MDB(getContext());
1311 
1312   auto *Existing = getMetadata(LLVMContext::MD_annotation);
1313   SmallVector<Metadata *, 4> Names;
1314   bool AppendName = true;
1315   if (Existing) {
1316     auto *Tuple = cast<MDTuple>(Existing);
1317     for (auto &N : Tuple->operands()) {
1318       if (cast<MDString>(N.get())->getString() == Name)
1319         AppendName = false;
1320       Names.push_back(N.get());
1321     }
1322   }
1323   if (AppendName)
1324     Names.push_back(MDB.createString(Name));
1325 
1326   MDNode *MD = MDTuple::get(getContext(), Names);
1327   setMetadata(LLVMContext::MD_annotation, MD);
1328 }
1329 
1330 void Instruction::setAAMetadata(const AAMDNodes &N) {
1331   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1332   setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
1333   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1334   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1335 }
1336 
1337 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1338   // Handle 'dbg' as a special case since it is not stored in the hash table.
1339   if (KindID == LLVMContext::MD_dbg)
1340     return DbgLoc.getAsMDNode();
1341   return Value::getMetadata(KindID);
1342 }
1343 
1344 void Instruction::getAllMetadataImpl(
1345     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1346   Result.clear();
1347 
1348   // Handle 'dbg' as a special case since it is not stored in the hash table.
1349   if (DbgLoc) {
1350     Result.push_back(
1351         std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1352   }
1353   Value::getAllMetadata(Result);
1354 }
1355 
1356 bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1357                                       uint64_t &FalseVal) const {
1358   assert(
1359       (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1360       "Looking for branch weights on something besides branch or select");
1361 
1362   auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1363   if (!ProfileData || ProfileData->getNumOperands() != 3)
1364     return false;
1365 
1366   auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1367   if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1368     return false;
1369 
1370   auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1371   auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1372   if (!CITrue || !CIFalse)
1373     return false;
1374 
1375   TrueVal = CITrue->getValue().getZExtValue();
1376   FalseVal = CIFalse->getValue().getZExtValue();
1377 
1378   return true;
1379 }
1380 
1381 bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
1382   assert((getOpcode() == Instruction::Br ||
1383           getOpcode() == Instruction::Select ||
1384           getOpcode() == Instruction::Call ||
1385           getOpcode() == Instruction::Invoke ||
1386           getOpcode() == Instruction::Switch) &&
1387          "Looking for branch weights on something besides branch");
1388 
1389   TotalVal = 0;
1390   auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1391   if (!ProfileData)
1392     return false;
1393 
1394   auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1395   if (!ProfDataName)
1396     return false;
1397 
1398   if (ProfDataName->getString().equals("branch_weights")) {
1399     TotalVal = 0;
1400     for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1401       auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1402       if (!V)
1403         return false;
1404       TotalVal += V->getValue().getZExtValue();
1405     }
1406     return true;
1407   } else if (ProfDataName->getString().equals("VP") &&
1408              ProfileData->getNumOperands() > 3) {
1409     TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1410                    ->getValue()
1411                    .getZExtValue();
1412     return true;
1413   }
1414   return false;
1415 }
1416 
1417 void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
1418   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1419   Other->getAllMetadata(MDs);
1420   for (auto &MD : MDs) {
1421     // We need to adjust the type metadata offset.
1422     if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1423       auto *OffsetConst = cast<ConstantInt>(
1424           cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1425       Metadata *TypeId = MD.second->getOperand(1);
1426       auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1427           OffsetConst->getType(), OffsetConst->getValue() + Offset));
1428       addMetadata(LLVMContext::MD_type,
1429                   *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1430       continue;
1431     }
1432     // If an offset adjustment was specified we need to modify the DIExpression
1433     // to prepend the adjustment:
1434     // !DIExpression(DW_OP_plus, Offset, [original expr])
1435     auto *Attachment = MD.second;
1436     if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1437       DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1438       DIExpression *E = nullptr;
1439       if (!GV) {
1440         auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1441         GV = GVE->getVariable();
1442         E = GVE->getExpression();
1443       }
1444       ArrayRef<uint64_t> OrigElements;
1445       if (E)
1446         OrigElements = E->getElements();
1447       std::vector<uint64_t> Elements(OrigElements.size() + 2);
1448       Elements[0] = dwarf::DW_OP_plus_uconst;
1449       Elements[1] = Offset;
1450       llvm::copy(OrigElements, Elements.begin() + 2);
1451       E = DIExpression::get(getContext(), Elements);
1452       Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1453     }
1454     addMetadata(MD.first, *Attachment);
1455   }
1456 }
1457 
1458 void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1459   addMetadata(
1460       LLVMContext::MD_type,
1461       *MDTuple::get(getContext(),
1462                     {ConstantAsMetadata::get(ConstantInt::get(
1463                          Type::getInt64Ty(getContext()), Offset)),
1464                      TypeID}));
1465 }
1466 
1467 void GlobalObject::setVCallVisibilityMetadata(VCallVisibility Visibility) {
1468   // Remove any existing vcall visibility metadata first in case we are
1469   // updating.
1470   eraseMetadata(LLVMContext::MD_vcall_visibility);
1471   addMetadata(LLVMContext::MD_vcall_visibility,
1472               *MDNode::get(getContext(),
1473                            {ConstantAsMetadata::get(ConstantInt::get(
1474                                Type::getInt64Ty(getContext()), Visibility))}));
1475 }
1476 
1477 GlobalObject::VCallVisibility GlobalObject::getVCallVisibility() const {
1478   if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
1479     uint64_t Val = cast<ConstantInt>(
1480                        cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
1481                        ->getZExtValue();
1482     assert(Val <= 2 && "unknown vcall visibility!");
1483     return (VCallVisibility)Val;
1484   }
1485   return VCallVisibility::VCallVisibilityPublic;
1486 }
1487 
1488 void Function::setSubprogram(DISubprogram *SP) {
1489   setMetadata(LLVMContext::MD_dbg, SP);
1490 }
1491 
1492 DISubprogram *Function::getSubprogram() const {
1493   return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1494 }
1495 
1496 bool Function::isDebugInfoForProfiling() const {
1497   if (DISubprogram *SP = getSubprogram()) {
1498     if (DICompileUnit *CU = SP->getUnit()) {
1499       return CU->getDebugInfoForProfiling();
1500     }
1501   }
1502   return false;
1503 }
1504 
1505 void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
1506   addMetadata(LLVMContext::MD_dbg, *GV);
1507 }
1508 
1509 void GlobalVariable::getDebugInfo(
1510     SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
1511   SmallVector<MDNode *, 1> MDs;
1512   getMetadata(LLVMContext::MD_dbg, MDs);
1513   for (MDNode *MD : MDs)
1514     GVs.push_back(cast<DIGlobalVariableExpression>(MD));
1515 }
1516