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