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