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