LLVM  6.0.0svn
Metadata.cpp
Go to the documentation of this file.
1 //===- Metadata.cpp - Implement Metadata classes --------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Metadata classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LLVMContextImpl.h"
15 #include "MetadataImpl.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"
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/Metadata.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"
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 
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.
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 
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 
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)
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 
195  return ReplaceableMetadataImpl::isReplaceable(MD);
196 }
197 
198 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
199  bool WasInserted =
200  UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
201  .second;
202  (void)WasInserted;
203  assert(WasInserted && "Expected to add a reference");
204 
205  ++NextIndex;
206  assert(NextIndex != 0 && "Unexpected overflow");
207 }
208 
209 void ReplaceableMetadataImpl::dropRef(void *Ref) {
210  bool WasErased = UseMap.erase(Ref);
211  (void)WasErased;
212  assert(WasErased && "Expected to drop a reference");
213 }
214 
215 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
216  const Metadata &MD) {
217  auto I = UseMap.find(Ref);
218  assert(I != UseMap.end() && "Expected to move a reference");
219  auto OwnerAndIndex = I->second;
220  UseMap.erase(I);
221  bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
222  (void)WasInserted;
223  assert(WasInserted && "Expected to add a reference");
224 
225  // Check that the references are direct if there's no owner.
226  (void)MD;
227  assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
228  "Reference without owner must be direct");
229  assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
230  "Reference without owner must be direct");
231 }
232 
234  if (UseMap.empty())
235  return;
236 
237  // Copy out uses since UseMap will get touched below.
238  using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
239  SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
240  std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
241  return L.second.second < R.second.second;
242  });
243  for (const auto &Pair : Uses) {
244  // Check that this Ref hasn't disappeared after RAUW (when updating a
245  // previous Ref).
246  if (!UseMap.count(Pair.first))
247  continue;
248 
249  OwnerTy Owner = Pair.second.first;
250  if (!Owner) {
251  // Update unowned tracking references directly.
252  Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
253  Ref = MD;
254  if (MD)
256  UseMap.erase(Pair.first);
257  continue;
258  }
259 
260  // Check for MetadataAsValue.
261  if (Owner.is<MetadataAsValue *>()) {
262  Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
263  continue;
264  }
265 
266  // There's a Metadata owner -- dispatch.
267  Metadata *OwnerMD = Owner.get<Metadata *>();
268  switch (OwnerMD->getMetadataID()) {
269 #define HANDLE_METADATA_LEAF(CLASS) \
270  case Metadata::CLASS##Kind: \
271  cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
272  continue;
273 #include "llvm/IR/Metadata.def"
274  default:
275  llvm_unreachable("Invalid metadata subclass");
276  }
277  }
278  assert(UseMap.empty() && "Expected all uses to be replaced");
279 }
280 
282  if (UseMap.empty())
283  return;
284 
285  if (!ResolveUsers) {
286  UseMap.clear();
287  return;
288  }
289 
290  // Copy out uses since UseMap could get touched below.
291  using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
292  SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
293  std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
294  return L.second.second < R.second.second;
295  });
296  UseMap.clear();
297  for (const auto &Pair : Uses) {
298  auto Owner = Pair.second.first;
299  if (!Owner)
300  continue;
301  if (Owner.is<MetadataAsValue *>())
302  continue;
303 
304  // Resolve MDNodes that point at this.
305  auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
306  if (!OwnerMD)
307  continue;
308  if (OwnerMD->isResolved())
309  continue;
310  OwnerMD->decrementUnresolvedOperandCount();
311  }
312 }
313 
314 ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
315  if (auto *N = dyn_cast<MDNode>(&MD))
316  return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
317  return dyn_cast<ValueAsMetadata>(&MD);
318 }
319 
320 ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
321  if (auto *N = dyn_cast<MDNode>(&MD))
322  return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
323  return dyn_cast<ValueAsMetadata>(&MD);
324 }
325 
326 bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
327  if (auto *N = dyn_cast<MDNode>(&MD))
328  return !N->isResolved();
329  return dyn_cast<ValueAsMetadata>(&MD);
330 }
331 
333  assert(V && "Expected value");
334  if (auto *A = dyn_cast<Argument>(V))
335  return A->getParent();
336  if (BasicBlock *BB = cast<Instruction>(V)->getParent())
337  return BB->getParent();
338  return nullptr;
339 }
340 
342  assert(V && "Unexpected null Value");
343 
344  auto &Context = V->getContext();
345  auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
346  if (!Entry) {
347  assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
348  "Expected constant or function-local value");
349  assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
350  V->IsUsedByMD = true;
351  if (auto *C = dyn_cast<Constant>(V))
352  Entry = new ConstantAsMetadata(C);
353  else
354  Entry = new LocalAsMetadata(V);
355  }
356 
357  return Entry;
358 }
359 
361  assert(V && "Unexpected null Value");
362  return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
363 }
364 
366  assert(V && "Expected valid value");
367 
368  auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
369  auto I = Store.find(V);
370  if (I == Store.end())
371  return;
372 
373  // Remove old entry from the map.
374  ValueAsMetadata *MD = I->second;
375  assert(MD && "Expected valid metadata");
376  assert(MD->getValue() == V && "Expected valid mapping");
377  Store.erase(I);
378 
379  // Delete the metadata.
380  MD->replaceAllUsesWith(nullptr);
381  delete MD;
382 }
383 
385  assert(From && "Expected valid value");
386  assert(To && "Expected valid value");
387  assert(From != To && "Expected changed value");
388  assert(From->getType() == To->getType() && "Unexpected type change");
389 
390  LLVMContext &Context = From->getType()->getContext();
391  auto &Store = Context.pImpl->ValuesAsMetadata;
392  auto I = Store.find(From);
393  if (I == Store.end()) {
394  assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
395  return;
396  }
397 
398  // Remove old entry from the map.
399  assert(From->IsUsedByMD && "Expected From to be used by metadata");
400  From->IsUsedByMD = false;
401  ValueAsMetadata *MD = I->second;
402  assert(MD && "Expected valid metadata");
403  assert(MD->getValue() == From && "Expected valid mapping");
404  Store.erase(I);
405 
406  if (isa<LocalAsMetadata>(MD)) {
407  if (auto *C = dyn_cast<Constant>(To)) {
408  // Local became a constant.
410  delete MD;
411  return;
412  }
413  if (getLocalFunction(From) && getLocalFunction(To) &&
414  getLocalFunction(From) != getLocalFunction(To)) {
415  // Function changed.
416  MD->replaceAllUsesWith(nullptr);
417  delete MD;
418  return;
419  }
420  } else if (!isa<Constant>(To)) {
421  // Changed to function-local value.
422  MD->replaceAllUsesWith(nullptr);
423  delete MD;
424  return;
425  }
426 
427  auto *&Entry = Store[To];
428  if (Entry) {
429  // The target already exists.
430  MD->replaceAllUsesWith(Entry);
431  delete MD;
432  return;
433  }
434 
435  // Update MD in place (and update the map entry).
436  assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
437  To->IsUsedByMD = true;
438  MD->V = To;
439  Entry = MD;
440 }
441 
442 //===----------------------------------------------------------------------===//
443 // MDString implementation.
444 //
445 
447  auto &Store = Context.pImpl->MDStringCache;
448  auto I = Store.try_emplace(Str);
449  auto &MapEntry = I.first->getValue();
450  if (!I.second)
451  return &MapEntry;
452  MapEntry.Entry = &*I.first;
453  return &MapEntry;
454 }
455 
457  assert(Entry && "Expected to find string map entry");
458  return Entry->first();
459 }
460 
461 //===----------------------------------------------------------------------===//
462 // MDNode implementation.
463 //
464 
465 // Assert that the MDNode types will not be unaligned by the objects
466 // prepended to them.
467 #define HANDLE_MDNODE_LEAF(CLASS) \
468  static_assert( \
469  alignof(uint64_t) >= alignof(CLASS), \
470  "Alignment is insufficient after objects prepended to " #CLASS);
471 #include "llvm/IR/Metadata.def"
472 
473 void *MDNode::operator new(size_t Size, unsigned NumOps) {
474  size_t OpSize = NumOps * sizeof(MDOperand);
475  // uint64_t is the most aligned type we need support (ensured by static_assert
476  // above)
477  OpSize = alignTo(OpSize, alignof(uint64_t));
478  void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
479  MDOperand *O = static_cast<MDOperand *>(Ptr);
480  for (MDOperand *E = O - NumOps; O != E; --O)
481  (void)new (O - 1) MDOperand;
482  return Ptr;
483 }
484 
485 void MDNode::operator delete(void *Mem) {
486  MDNode *N = static_cast<MDNode *>(Mem);
487  size_t OpSize = N->NumOperands * sizeof(MDOperand);
488  OpSize = alignTo(OpSize, alignof(uint64_t));
489 
490  MDOperand *O = static_cast<MDOperand *>(Mem);
491  for (MDOperand *E = O - N->NumOperands; O != E; --O)
492  (O - 1)->~MDOperand();
493  ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
494 }
495 
496 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
498  : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
499  NumUnresolved(0), Context(Context) {
500  unsigned Op = 0;
501  for (Metadata *MD : Ops1)
502  setOperand(Op++, MD);
503  for (Metadata *MD : Ops2)
504  setOperand(Op++, MD);
505 
506  if (!isUniqued())
507  return;
508 
509  // Count the unresolved operands. If there are any, RAUW support will be
510  // added lazily on first reference.
511  countUnresolvedOperands();
512 }
513 
514 TempMDNode MDNode::clone() const {
515  switch (getMetadataID()) {
516  default:
517  llvm_unreachable("Invalid MDNode subclass");
518 #define HANDLE_MDNODE_LEAF(CLASS) \
519  case CLASS##Kind: \
520  return cast<CLASS>(this)->cloneImpl();
521 #include "llvm/IR/Metadata.def"
522  }
523 }
524 
526  if (auto *N = dyn_cast_or_null<MDNode>(Op))
527  return !N->isResolved();
528  return false;
529 }
530 
531 void MDNode::countUnresolvedOperands() {
532  assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
533  assert(isUniqued() && "Expected this to be uniqued");
534  NumUnresolved = count_if(operands(), isOperandUnresolved);
535 }
536 
537 void MDNode::makeUniqued() {
538  assert(isTemporary() && "Expected this to be temporary");
539  assert(!isResolved() && "Expected this to be unresolved");
540 
541  // Enable uniquing callbacks.
542  for (auto &Op : mutable_operands())
543  Op.reset(Op.get(), this);
544 
545  // Make this 'uniqued'.
546  Storage = Uniqued;
547  countUnresolvedOperands();
548  if (!NumUnresolved) {
549  dropReplaceableUses();
550  assert(isResolved() && "Expected this to be resolved");
551  }
552 
553  assert(isUniqued() && "Expected this to be uniqued");
554 }
555 
556 void MDNode::makeDistinct() {
557  assert(isTemporary() && "Expected this to be temporary");
558  assert(!isResolved() && "Expected this to be unresolved");
559 
560  // Drop RAUW support and store as a distinct node.
561  dropReplaceableUses();
563 
564  assert(isDistinct() && "Expected this to be distinct");
565  assert(isResolved() && "Expected this to be resolved");
566 }
567 
568 void MDNode::resolve() {
569  assert(isUniqued() && "Expected this to be uniqued");
570  assert(!isResolved() && "Expected this to be unresolved");
571 
572  NumUnresolved = 0;
573  dropReplaceableUses();
574 
575  assert(isResolved() && "Expected this to be resolved");
576 }
577 
578 void MDNode::dropReplaceableUses() {
579  assert(!NumUnresolved && "Unexpected unresolved operand");
580 
581  // Drop any RAUW support.
582  if (Context.hasReplaceableUses())
583  Context.takeReplaceableUses()->resolveAllUses();
584 }
585 
586 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
587  assert(isUniqued() && "Expected this to be uniqued");
588  assert(NumUnresolved != 0 && "Expected unresolved operands");
589 
590  // Check if an operand was resolved.
591  if (!isOperandUnresolved(Old)) {
592  if (isOperandUnresolved(New))
593  // An operand was un-resolved!
594  ++NumUnresolved;
595  } else if (!isOperandUnresolved(New))
596  decrementUnresolvedOperandCount();
597 }
598 
599 void MDNode::decrementUnresolvedOperandCount() {
600  assert(!isResolved() && "Expected this to be unresolved");
601  if (isTemporary())
602  return;
603 
604  assert(isUniqued() && "Expected this to be uniqued");
605  if (--NumUnresolved)
606  return;
607 
608  // Last unresolved operand has just been resolved.
609  dropReplaceableUses();
610  assert(isResolved() && "Expected this to become resolved");
611 }
612 
614  if (isResolved())
615  return;
616 
617  // Resolve this node immediately.
618  resolve();
619 
620  // Resolve all operands.
621  for (const auto &Op : operands()) {
622  auto *N = dyn_cast_or_null<MDNode>(Op);
623  if (!N)
624  continue;
625 
626  assert(!N->isTemporary() &&
627  "Expected all forward declarations to be resolved");
628  if (!N->isResolved())
629  N->resolveCycles();
630  }
631 }
632 
633 static bool hasSelfReference(MDNode *N) {
634  for (Metadata *MD : N->operands())
635  if (MD == N)
636  return true;
637  return false;
638 }
639 
640 MDNode *MDNode::replaceWithPermanentImpl() {
641  switch (getMetadataID()) {
642  default:
643  // If this type isn't uniquable, replace with a distinct node.
644  return replaceWithDistinctImpl();
645 
646 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
647  case CLASS##Kind: \
648  break;
649 #include "llvm/IR/Metadata.def"
650  }
651 
652  // Even if this type is uniquable, self-references have to be distinct.
653  if (hasSelfReference(this))
654  return replaceWithDistinctImpl();
655  return replaceWithUniquedImpl();
656 }
657 
658 MDNode *MDNode::replaceWithUniquedImpl() {
659  // Try to uniquify in place.
660  MDNode *UniquedNode = uniquify();
661 
662  if (UniquedNode == this) {
663  makeUniqued();
664  return this;
665  }
666 
667  // Collision, so RAUW instead.
668  replaceAllUsesWith(UniquedNode);
669  deleteAsSubclass();
670  return UniquedNode;
671 }
672 
673 MDNode *MDNode::replaceWithDistinctImpl() {
674  makeDistinct();
675  return this;
676 }
677 
678 void MDTuple::recalculateHash() {
679  setHash(MDTupleInfo::KeyTy::calculateHash(this));
680 }
681 
683  for (unsigned I = 0, E = NumOperands; I != E; ++I)
684  setOperand(I, nullptr);
685  if (Context.hasReplaceableUses()) {
686  Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
687  (void)Context.takeReplaceableUses();
688  }
689 }
690 
691 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
692  unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
693  assert(Op < getNumOperands() && "Expected valid operand");
694 
695  if (!isUniqued()) {
696  // This node is not uniqued. Just set the operand and be done with it.
697  setOperand(Op, New);
698  return;
699  }
700 
701  // This node is uniqued.
702  eraseFromStore();
703 
704  Metadata *Old = getOperand(Op);
705  setOperand(Op, New);
706 
707  // Drop uniquing for self-reference cycles and deleted constants.
708  if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
709  if (!isResolved())
710  resolve();
712  return;
713  }
714 
715  // Re-unique the node.
716  auto *Uniqued = uniquify();
717  if (Uniqued == this) {
718  if (!isResolved())
719  resolveAfterOperandChange(Old, New);
720  return;
721  }
722 
723  // Collision.
724  if (!isResolved()) {
725  // Still unresolved, so RAUW.
726  //
727  // First, clear out all operands to prevent any recursion (similar to
728  // dropAllReferences(), but we still need the use-list).
729  for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
730  setOperand(O, nullptr);
731  if (Context.hasReplaceableUses())
733  deleteAsSubclass();
734  return;
735  }
736 
737  // Store in non-uniqued form if RAUW isn't possible.
739 }
740 
741 void MDNode::deleteAsSubclass() {
742  switch (getMetadataID()) {
743  default:
744  llvm_unreachable("Invalid subclass of MDNode");
745 #define HANDLE_MDNODE_LEAF(CLASS) \
746  case CLASS##Kind: \
747  delete cast<CLASS>(this); \
748  break;
749 #include "llvm/IR/Metadata.def"
750  }
751 }
752 
753 template <class T, class InfoT>
755  if (T *U = getUniqued(Store, N))
756  return U;
757 
758  Store.insert(N);
759  return N;
760 }
761 
762 template <class NodeTy> struct MDNode::HasCachedHash {
763  using Yes = char[1];
764  using No = char[2];
765  template <class U, U Val> struct SFINAE {};
766 
767  template <class U>
768  static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
769  template <class U> static No &check(...);
770 
771  static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
772 };
773 
774 MDNode *MDNode::uniquify() {
775  assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
776 
777  // Try to insert into uniquing store.
778  switch (getMetadataID()) {
779  default:
780  llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
781 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
782  case CLASS##Kind: { \
783  CLASS *SubclassThis = cast<CLASS>(this); \
784  std::integral_constant<bool, HasCachedHash<CLASS>::value> \
785  ShouldRecalculateHash; \
786  dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
787  return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
788  }
789 #include "llvm/IR/Metadata.def"
790  }
791 }
792 
793 void MDNode::eraseFromStore() {
794  switch (getMetadataID()) {
795  default:
796  llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
797 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
798  case CLASS##Kind: \
799  getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
800  break;
801 #include "llvm/IR/Metadata.def"
802  }
803 }
804 
805 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
806  StorageType Storage, bool ShouldCreate) {
807  unsigned Hash = 0;
808  if (Storage == Uniqued) {
809  MDTupleInfo::KeyTy Key(MDs);
810  if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
811  return N;
812  if (!ShouldCreate)
813  return nullptr;
814  Hash = Key.getHash();
815  } else {
816  assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
817  }
818 
819  return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
820  Storage, Context.pImpl->MDTuples);
821 }
822 
824  assert(N->isTemporary() && "Expected temporary node");
825  N->replaceAllUsesWith(nullptr);
826  N->deleteAsSubclass();
827 }
828 
830  assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
831  assert(!NumUnresolved && "Unexpected unresolved nodes");
832  Storage = Distinct;
833  assert(isResolved() && "Expected this to be resolved");
834 
835  // Reset the hash.
836  switch (getMetadataID()) {
837  default:
838  llvm_unreachable("Invalid subclass of MDNode");
839 #define HANDLE_MDNODE_LEAF(CLASS) \
840  case CLASS##Kind: { \
841  std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
842  dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
843  break; \
844  }
845 #include "llvm/IR/Metadata.def"
846  }
847 
848  getContext().pImpl->DistinctMDNodes.push_back(this);
849 }
850 
851 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
852  if (getOperand(I) == New)
853  return;
854 
855  if (!isUniqued()) {
856  setOperand(I, New);
857  return;
858  }
859 
860  handleChangedOperand(mutable_begin() + I, New);
861 }
862 
863 void MDNode::setOperand(unsigned I, Metadata *New) {
864  assert(I < NumOperands);
865  mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
866 }
867 
868 /// Get a node or a self-reference that looks like it.
869 ///
870 /// Special handling for finding self-references, for use by \a
871 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
872 /// when self-referencing nodes were still uniqued. If the first operand has
873 /// the same operands as \c Ops, return the first operand instead.
875  ArrayRef<Metadata *> Ops) {
876  if (!Ops.empty())
877  if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
878  if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
879  for (unsigned I = 1, E = Ops.size(); I != E; ++I)
880  if (Ops[I] != N->getOperand(I))
881  return MDNode::get(Context, Ops);
882  return N;
883  }
884 
885  return MDNode::get(Context, Ops);
886 }
887 
889  if (!A)
890  return B;
891  if (!B)
892  return A;
893 
895  MDs.insert(B->op_begin(), B->op_end());
896 
897  // FIXME: This preserves long-standing behaviour, but is it really the right
898  // behaviour? Or was that an unintended side-effect of node uniquing?
899  return getOrSelfReference(A->getContext(), MDs.getArrayRef());
900 }
901 
903  if (!A || !B)
904  return nullptr;
905 
907  SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
908  MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
909 
910  // FIXME: This preserves long-standing behaviour, but is it really the right
911  // behaviour? Or was that an unintended side-effect of node uniquing?
912  return getOrSelfReference(A->getContext(), MDs.getArrayRef());
913 }
914 
916  if (!A || !B)
917  return nullptr;
918 
919  return concatenate(A, B);
920 }
921 
923  if (!A || !B)
924  return nullptr;
925 
926  APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
927  APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
928  if (AVal.compare(BVal) == APFloat::cmpLessThan)
929  return A;
930  return B;
931 }
932 
933 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
934  return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
935 }
936 
937 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
938  return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
939 }
940 
942  ConstantInt *Low, ConstantInt *High) {
943  ConstantRange NewRange(Low->getValue(), High->getValue());
944  unsigned Size = EndPoints.size();
945  APInt LB = EndPoints[Size - 2]->getValue();
946  APInt LE = EndPoints[Size - 1]->getValue();
947  ConstantRange LastRange(LB, LE);
948  if (canBeMerged(NewRange, LastRange)) {
949  ConstantRange Union = LastRange.unionWith(NewRange);
950  Type *Ty = High->getType();
951  EndPoints[Size - 2] =
952  cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
953  EndPoints[Size - 1] =
954  cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
955  return true;
956  }
957  return false;
958 }
959 
961  ConstantInt *Low, ConstantInt *High) {
962  if (!EndPoints.empty())
963  if (tryMergeRange(EndPoints, Low, High))
964  return;
965 
966  EndPoints.push_back(Low);
967  EndPoints.push_back(High);
968 }
969 
971  // Given two ranges, we want to compute the union of the ranges. This
972  // is slightly complicated by having to combine the intervals and merge
973  // the ones that overlap.
974 
975  if (!A || !B)
976  return nullptr;
977 
978  if (A == B)
979  return A;
980 
981  // First, walk both lists in order of the lower boundary of each interval.
982  // At each step, try to merge the new interval to the last one we adedd.
984  int AI = 0;
985  int BI = 0;
986  int AN = A->getNumOperands() / 2;
987  int BN = B->getNumOperands() / 2;
988  while (AI < AN && BI < BN) {
989  ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
990  ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
991 
992  if (ALow->getValue().slt(BLow->getValue())) {
993  addRange(EndPoints, ALow,
994  mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
995  ++AI;
996  } else {
997  addRange(EndPoints, BLow,
998  mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
999  ++BI;
1000  }
1001  }
1002  while (AI < AN) {
1003  addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1004  mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1005  ++AI;
1006  }
1007  while (BI < BN) {
1008  addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1009  mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1010  ++BI;
1011  }
1012 
1013  // If we have more than 2 ranges (4 endpoints) we have to try to merge
1014  // the last and first ones.
1015  unsigned Size = EndPoints.size();
1016  if (Size > 4) {
1017  ConstantInt *FB = EndPoints[0];
1018  ConstantInt *FE = EndPoints[1];
1019  if (tryMergeRange(EndPoints, FB, FE)) {
1020  for (unsigned i = 0; i < Size - 2; ++i) {
1021  EndPoints[i] = EndPoints[i + 2];
1022  }
1023  EndPoints.resize(Size - 2);
1024  }
1025  }
1026 
1027  // If in the end we have a single range, it is possible that it is now the
1028  // full range. Just drop the metadata in that case.
1029  if (EndPoints.size() == 2) {
1030  ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1031  if (Range.isFullSet())
1032  return nullptr;
1033  }
1034 
1036  MDs.reserve(EndPoints.size());
1037  for (auto *I : EndPoints)
1039  return MDNode::get(A->getContext(), MDs);
1040 }
1041 
1043  if (!A || !B)
1044  return nullptr;
1045 
1046  ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1047  ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1048  if (AVal->getZExtValue() < BVal->getZExtValue())
1049  return A;
1050  return B;
1051 }
1052 
1053 //===----------------------------------------------------------------------===//
1054 // NamedMDNode implementation.
1055 //
1056 
1057 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1058  return *(SmallVector<TrackingMDRef, 4> *)Operands;
1059 }
1060 
1061 NamedMDNode::NamedMDNode(const Twine &N)
1062  : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1063 
1066  delete &getNMDOps(Operands);
1067 }
1068 
1070  return (unsigned)getNMDOps(Operands).size();
1071 }
1072 
1073 MDNode *NamedMDNode::getOperand(unsigned i) const {
1074  assert(i < getNumOperands() && "Invalid Operand number!");
1075  auto *N = getNMDOps(Operands)[i].get();
1076  return cast_or_null<MDNode>(N);
1077 }
1078 
1079 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1080 
1081 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1082  assert(I < getNumOperands() && "Invalid operand number");
1083  getNMDOps(Operands)[I].reset(New);
1084 }
1085 
1086 void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
1087 
1088 void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1089 
1091 
1092 //===----------------------------------------------------------------------===//
1093 // Instruction Metadata method implementations.
1094 //
1095 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1096  for (auto &I : Attachments)
1097  if (I.first == ID) {
1098  I.second.reset(&MD);
1099  return;
1100  }
1101  Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1102  std::make_tuple(&MD));
1103 }
1104 
1105 void MDAttachmentMap::erase(unsigned ID) {
1106  if (empty())
1107  return;
1108 
1109  // Common case is one/last value.
1110  if (Attachments.back().first == ID) {
1111  Attachments.pop_back();
1112  return;
1113  }
1114 
1115  for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1116  ++I)
1117  if (I->first == ID) {
1118  *I = std::move(Attachments.back());
1119  Attachments.pop_back();
1120  return;
1121  }
1122 }
1123 
1125  for (const auto &I : Attachments)
1126  if (I.first == ID)
1127  return I.second;
1128  return nullptr;
1129 }
1130 
1132  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1133  Result.append(Attachments.begin(), Attachments.end());
1134 
1135  // Sort the resulting array so it is stable.
1136  if (Result.size() > 1)
1137  array_pod_sort(Result.begin(), Result.end());
1138 }
1139 
1141  Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1142 }
1143 
1145  SmallVectorImpl<MDNode *> &Result) {
1146  for (auto A : Attachments)
1147  if (A.MDKind == ID)
1148  Result.push_back(A.Node);
1149 }
1150 
1152  auto Follower = Attachments.begin();
1153  for (auto Leader = Attachments.begin(), E = Attachments.end(); Leader != E;
1154  ++Leader) {
1155  if (Leader->MDKind != ID) {
1156  if (Follower != Leader)
1157  *Follower = std::move(*Leader);
1158  ++Follower;
1159  }
1160  }
1161  Attachments.resize(Follower - Attachments.begin());
1162 }
1163 
1165  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1166  for (auto &A : Attachments)
1167  Result.emplace_back(A.MDKind, A.Node);
1168 
1169  // Sort the resulting array so it is stable with respect to metadata IDs. We
1170  // need to preserve the original insertion order though.
1171  std::stable_sort(
1172  Result.begin(), Result.end(),
1173  [](const std::pair<unsigned, MDNode *> &A,
1174  const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1175 }
1176 
1178  if (!Node && !hasMetadata())
1179  return;
1180  setMetadata(getContext().getMDKindID(Kind), Node);
1181 }
1182 
1183 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1184  return getMetadataImpl(getContext().getMDKindID(Kind));
1185 }
1186 
1188  if (!hasMetadataHashEntry())
1189  return; // Nothing to remove!
1190 
1191  auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1192 
1193  SmallSet<unsigned, 4> KnownSet;
1194  KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1195  if (KnownSet.empty()) {
1196  // Just drop our entry at the store.
1197  InstructionMetadata.erase(this);
1198  setHasMetadataHashEntry(false);
1199  return;
1200  }
1201 
1202  auto &Info = InstructionMetadata[this];
1203  Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1204  return !KnownSet.count(I.first);
1205  });
1206 
1207  if (Info.empty()) {
1208  // Drop our entry at the store.
1209  InstructionMetadata.erase(this);
1210  setHasMetadataHashEntry(false);
1211  }
1212 }
1213 
1214 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1215  if (!Node && !hasMetadata())
1216  return;
1217 
1218  // Handle 'dbg' as a special case since it is not stored in the hash table.
1219  if (KindID == LLVMContext::MD_dbg) {
1220  DbgLoc = DebugLoc(Node);
1221  return;
1222  }
1223 
1224  // Handle the case when we're adding/updating metadata on an instruction.
1225  if (Node) {
1226  auto &Info = getContext().pImpl->InstructionMetadata[this];
1227  assert(!Info.empty() == hasMetadataHashEntry() &&
1228  "HasMetadata bit is wonked");
1229  if (Info.empty())
1230  setHasMetadataHashEntry(true);
1231  Info.set(KindID, *Node);
1232  return;
1233  }
1234 
1235  // Otherwise, we're removing metadata from an instruction.
1236  assert((hasMetadataHashEntry() ==
1237  (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
1238  "HasMetadata bit out of date!");
1239  if (!hasMetadataHashEntry())
1240  return; // Nothing to remove!
1241  auto &Info = getContext().pImpl->InstructionMetadata[this];
1242 
1243  // Handle removal of an existing value.
1244  Info.erase(KindID);
1245 
1246  if (!Info.empty())
1247  return;
1248 
1249  getContext().pImpl->InstructionMetadata.erase(this);
1250  setHasMetadataHashEntry(false);
1251 }
1252 
1257 }
1258 
1259 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1260  // Handle 'dbg' as a special case since it is not stored in the hash table.
1261  if (KindID == LLVMContext::MD_dbg)
1262  return DbgLoc.getAsMDNode();
1263 
1264  if (!hasMetadataHashEntry())
1265  return nullptr;
1266  auto &Info = getContext().pImpl->InstructionMetadata[this];
1267  assert(!Info.empty() && "bit out of sync with hash table");
1268 
1269  return Info.lookup(KindID);
1270 }
1271 
1272 void Instruction::getAllMetadataImpl(
1273  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1274  Result.clear();
1275 
1276  // Handle 'dbg' as a special case since it is not stored in the hash table.
1277  if (DbgLoc) {
1278  Result.push_back(
1279  std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1280  if (!hasMetadataHashEntry())
1281  return;
1282  }
1283 
1284  assert(hasMetadataHashEntry() &&
1285  getContext().pImpl->InstructionMetadata.count(this) &&
1286  "Shouldn't have called this");
1287  const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1288  assert(!Info.empty() && "Shouldn't have called this");
1289  Info.getAll(Result);
1290 }
1291 
1292 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1293  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1294  Result.clear();
1295  assert(hasMetadataHashEntry() &&
1296  getContext().pImpl->InstructionMetadata.count(this) &&
1297  "Shouldn't have called this");
1298  const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1299  assert(!Info.empty() && "Shouldn't have called this");
1300  Info.getAll(Result);
1301 }
1302 
1303 bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1304  uint64_t &FalseVal) const {
1305  assert(
1306  (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1307  "Looking for branch weights on something besides branch or select");
1308 
1309  auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1310  if (!ProfileData || ProfileData->getNumOperands() != 3)
1311  return false;
1312 
1313  auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1314  if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1315  return false;
1316 
1317  auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1318  auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1319  if (!CITrue || !CIFalse)
1320  return false;
1321 
1322  TrueVal = CITrue->getValue().getZExtValue();
1323  FalseVal = CIFalse->getValue().getZExtValue();
1324 
1325  return true;
1326 }
1327 
1328 bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
1329  assert((getOpcode() == Instruction::Br ||
1330  getOpcode() == Instruction::Select ||
1331  getOpcode() == Instruction::Call ||
1332  getOpcode() == Instruction::Invoke ||
1333  getOpcode() == Instruction::Switch) &&
1334  "Looking for branch weights on something besides branch");
1335 
1336  TotalVal = 0;
1337  auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1338  if (!ProfileData)
1339  return false;
1340 
1341  auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1342  if (!ProfDataName)
1343  return false;
1344 
1345  if (ProfDataName->getString().equals("branch_weights")) {
1346  TotalVal = 0;
1347  for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1348  auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1349  if (!V)
1350  return false;
1351  TotalVal += V->getValue().getZExtValue();
1352  }
1353  return true;
1354  } else if (ProfDataName->getString().equals("VP") &&
1355  ProfileData->getNumOperands() > 3) {
1356  TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1357  ->getValue()
1358  .getZExtValue();
1359  return true;
1360  }
1361  return false;
1362 }
1363 
1364 void Instruction::clearMetadataHashEntries() {
1365  assert(hasMetadataHashEntry() && "Caller should check");
1366  getContext().pImpl->InstructionMetadata.erase(this);
1367  setHasMetadataHashEntry(false);
1368 }
1369 
1370 void GlobalObject::getMetadata(unsigned KindID,
1371  SmallVectorImpl<MDNode *> &MDs) const {
1372  if (hasMetadata())
1373  getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
1374 }
1375 
1377  SmallVectorImpl<MDNode *> &MDs) const {
1378  if (hasMetadata())
1379  getMetadata(getContext().getMDKindID(Kind), MDs);
1380 }
1381 
1382 void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1383  if (!hasMetadata())
1384  setHasMetadataHashEntry(true);
1385 
1386  getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1387 }
1388 
1390  addMetadata(getContext().getMDKindID(Kind), MD);
1391 }
1392 
1393 void GlobalObject::eraseMetadata(unsigned KindID) {
1394  // Nothing to unset.
1395  if (!hasMetadata())
1396  return;
1397 
1398  auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
1399  Store.erase(KindID);
1400  if (Store.empty())
1401  clearMetadata();
1402 }
1403 
1405  SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1406  MDs.clear();
1407 
1408  if (!hasMetadata())
1409  return;
1410 
1411  getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
1412 }
1413 
1415  if (!hasMetadata())
1416  return;
1417  getContext().pImpl->GlobalObjectMetadata.erase(this);
1418  setHasMetadataHashEntry(false);
1419 }
1420 
1421 void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1422  eraseMetadata(KindID);
1423  if (N)
1424  addMetadata(KindID, *N);
1425 }
1426 
1428  setMetadata(getContext().getMDKindID(Kind), N);
1429 }
1430 
1431 MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1433  getMetadata(KindID, MDs);
1434  assert(MDs.size() <= 1 && "Expected at most one metadata attachment");
1435  if (MDs.empty())
1436  return nullptr;
1437  return MDs[0];
1438 }
1439 
1441  return getMetadata(getContext().getMDKindID(Kind));
1442 }
1443 
1444 void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
1446  Other->getAllMetadata(MDs);
1447  for (auto &MD : MDs) {
1448  // We need to adjust the type metadata offset.
1449  if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1450  auto *OffsetConst = cast<ConstantInt>(
1451  cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1452  Metadata *TypeId = MD.second->getOperand(1);
1453  auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1454  OffsetConst->getType(), OffsetConst->getValue() + Offset));
1455  addMetadata(LLVMContext::MD_type,
1456  *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1457  continue;
1458  }
1459  // If an offset adjustment was specified we need to modify the DIExpression
1460  // to prepend the adjustment:
1461  // !DIExpression(DW_OP_plus, Offset, [original expr])
1462  auto *Attachment = MD.second;
1463  if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1464  DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1465  DIExpression *E = nullptr;
1466  if (!GV) {
1467  auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1468  GV = GVE->getVariable();
1469  E = GVE->getExpression();
1470  }
1471  ArrayRef<uint64_t> OrigElements;
1472  if (E)
1473  OrigElements = E->getElements();
1474  std::vector<uint64_t> Elements(OrigElements.size() + 2);
1475  Elements[0] = dwarf::DW_OP_plus_uconst;
1476  Elements[1] = Offset;
1477  std::copy(OrigElements.begin(), OrigElements.end(), Elements.begin() + 2);
1478  E = DIExpression::get(getContext(), Elements);
1479  Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1480  }
1481  addMetadata(MD.first, *Attachment);
1482  }
1483 }
1484 
1486  addMetadata(
1490  Type::getInt64Ty(getContext()), Offset)),
1491  TypeID}));
1492 }
1493 
1496 }
1497 
1499  return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1500 }
1501 
1503  if (DISubprogram *SP = getSubprogram()) {
1504  if (DICompileUnit *CU = SP->getUnit()) {
1505  return CU->getDebugInfoForProfiling();
1506  }
1507  }
1508  return false;
1509 }
1510 
1512  addMetadata(LLVMContext::MD_dbg, *GV);
1513 }
1514 
1518  getMetadata(LLVMContext::MD_dbg, MDs);
1519  for (MDNode *MD : MDs)
1520  GVs.push_back(cast<DIGlobalVariableExpression>(MD));
1521 }
uint64_t CallInst * C
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:172
static void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
Definition: Metadata.cpp:823
bool isUniqued() const
Definition: Metadata.h:940
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:709
unsigned char Storage
Storage flag for non-uniqued, otherwise unowned, metadata.
Definition: Metadata.h:69
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1131
bool isDistinct() const
Definition: Metadata.h:941
StringMap< MDString, BumpPtrAllocator > MDStringCache
LLVMContext & Context
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition: Metadata.h:659
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1073
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
const APInt & getUpper() const
Return the upper value for this range.
MDNode * TBAA
The tag for type-based alias analysis.
Definition: Metadata.h:656
iterator begin() const
Definition: ArrayRef.h:137
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
Definition: Metadata.cpp:851
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:446
void clearOperands()
Drop all references to this node&#39;s operands.
Definition: Metadata.cpp:1088
Implements a dense probed hash-table based set.
Definition: DenseSet.h:221
std::unique_ptr< ReplaceableMetadataImpl > takeReplaceableUses()
Drop RAUW support.
Definition: Metadata.h:828
DenseMap< Value *, ValueAsMetadata * > ValuesAsMetadata
static MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
Definition: Metadata.cpp:915
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1183
void addOperand(MDNode *M)
Definition: Metadata.cpp:1079
This file contains the declarations for metadata subclasses.
void storeDistinctInContext()
Definition: Metadata.cpp:829
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:697
void dropAllReferences()
Definition: Metadata.cpp:682
Shared implementation of use-lists for replaceable metadata.
Definition: Metadata.h:277
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:862
static bool canBeMerged(const ConstantRange &A, const ConstantRange &B)
Definition: Metadata.cpp:937
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
Definition: MetadataImpl.h:43
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
void setOperand(unsigned I, Metadata *New)
Set an operand.
Definition: Metadata.cpp:863
static Type * getMetadataTy(LLVMContext &C)
Definition: Type.cpp:166
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
Definition: Metadata.cpp:1404
void reserve(size_type N)
Definition: SmallVector.h:380
void setOperand(unsigned I, MDNode *New)
Definition: Metadata.cpp:1081
op_iterator op_end() const
Definition: Metadata.h:1061
uint64_t High
Tuple of metadata.
Definition: Metadata.h:1104
TempMDNode clone() const
Create a (temporary) clone of this.
Definition: Metadata.cpp:514
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
void set(unsigned ID, MDNode &MD)
Set an attachment to a particular node.
Definition: Metadata.cpp:1095
TypedTrackingMDRef< MDNode > TrackingMDNodeRef
void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
Definition: Metadata.cpp:1444
DenseMap< const Instruction *, MDAttachmentMap > InstructionMetadata
Collection of per-instruction metadata used in this context.
LLVM_NODISCARD bool empty() const
Definition: SmallSet.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
bool isResolved() const
Check if node is fully resolved.
Definition: Metadata.h:938
void eraseFromParent()
Drop all references and remove the node from parent module.
Definition: Metadata.cpp:1086
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition: Metadata.h:219
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1431
void get(unsigned ID, SmallVectorImpl< MDNode *> &Result)
Appends all attachments with the given ID to Result in insertion order.
Definition: Metadata.cpp:1144
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:55
unsigned getNumOperands() const
Definition: Metadata.cpp:1069
std::vector< MDNode * > DistinctMDNodes
This file implements a class to represent arbitrary precision integral constant values and operations...
void resolveCycles()
Resolve cycles.
Definition: Metadata.cpp:613
op_iterator op_begin() const
Definition: Metadata.h:1057
void erase(unsigned ID)
Definition: Metadata.cpp:1151
static Metadata * canonicalizeMetadataForValue(LLVMContext &Context, Metadata *MD)
Canonicalize metadata arguments to intrinsics.
Definition: Metadata.cpp:84
Subprogram description.
static void handleRAUW(Value *From, Value *To)
Definition: Metadata.cpp:384
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static SmallVector< TrackingMDRef, 4 > & getNMDOps(void *Operands)
Definition: Metadata.cpp:1057
void dropUnknownNonDebugMetadata()
Definition: Instruction.h:249
op_range operands() const
Definition: Metadata.h:1065
LLVMContext & getContext() const
Definition: Metadata.h:922
unsigned getMetadataID() const
Definition: Metadata.h:98
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
static Function * getLocalFunction(Value *V)
Definition: Metadata.cpp:332
static MDNode * intersect(MDNode *A, MDNode *B)
Definition: Metadata.cpp:902
static T * uniquifyImpl(T *N, DenseSet< T *, InfoT > &Store)
Definition: Metadata.cpp:754
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition: Metadata.cpp:1328
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:337
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition: Metadata.h:947
MDNode * lookup(unsigned ID) const
Get a particular attachment (if any).
Definition: Metadata.cpp:1124
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:408
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:106
StringRef getString() const
Definition: Metadata.cpp:456
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1164
bool isDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
Definition: Metadata.cpp:1502
static MDNode * getMostGenericRange(MDNode *A, MDNode *B)
Definition: Metadata.cpp:970
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
Definition: Metadata.cpp:1494
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition: STLExtras.h:769
static T * getUniqued(DenseSet< T *, InfoT > &Store, const typename InfoT::KeyTy &Key)
Definition: MetadataImpl.h:23
void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition: Metadata.cpp:281
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void addTypeMetadata(unsigned Offset, Metadata *TypeID)
Definition: Metadata.cpp:1485
static ValueAsMetadata * getIfExists(Value *V)
Definition: Metadata.cpp:360
static MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:114
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1253
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1498
static MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1042
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
Definition: Metadata.cpp:933
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:36
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression *> &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1515
StorageType
Active type of storage.
Definition: Metadata.h:66
A pair of DIGlobalVariable and DIExpression.
void getAll(SmallVectorImpl< std::pair< unsigned, MDNode *>> &Result) const
Appends all attachments for the global to Result, sorting by attachment ID.
Definition: Metadata.cpp:1164
This file declares a class to represent arbitrary precision floating point values and provide a varie...
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition: Metadata.h:255
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type. ...
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:81
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:172
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&... Args)
Definition: DIBuilder.cpp:679
static wasm::ValType getType(const TargetRegisterClass *RC)
C setMetadata(LLVMContext::MD_range, MDNode::get(Context, LowAndHigh))
Value * getValue() const
Definition: Metadata.h:377
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1214
mutable_op_range mutable_operands()
Definition: Metadata.h:896
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:71
static bool isOperandUnresolved(Metadata *Op)
Definition: Metadata.cpp:525
bool isEmptySet() const
Return true if this set contains no members.
DenseMap< Metadata *, MetadataAsValue * > MetadataAsValues
bool hasReplaceableUses() const
Whether this contains RAUW support.
Definition: Metadata.h:789
DenseMap< const GlobalObject *, MDGlobalAttachmentMap > GlobalObjectMetadata
Collection of per-GlobalObject metadata used in this context.
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
static MDNode * getOrSelfReference(LLVMContext &Context, ArrayRef< Metadata *> Ops)
Get a node or a self-reference that looks like it.
Definition: Metadata.cpp:874
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:410
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
unsigned IsUsedByMD
Definition: Value.h:118
MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata *> Ops1, ArrayRef< Metadata *> Ops2=None)
Definition: Metadata.cpp:496
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:341
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
Module.h This file contains the declarations for the Module class.
This class represents a range of values.
Definition: ConstantRange.h:47
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1382
iterator end() const
Definition: ArrayRef.h:138
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:642
MDNode * NoAlias
The tag specifying the noalias scope.
Definition: Metadata.h:662
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:560
void reset()
Definition: Metadata.h:725
DWARF expression.
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition: Metadata.h:244
Class for arbitrary precision integers.
Definition: APInt.h:69
void erase(unsigned ID)
Remove an attachment.
Definition: Metadata.cpp:1105
void insert(unsigned ID, MDNode &MD)
Definition: Metadata.cpp:1140
StringRef getName() const
Definition: Metadata.cpp:1090
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1421
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
MDOperand * mutable_begin()
Definition: Metadata.h:891
void getAll(SmallVectorImpl< std::pair< unsigned, MDNode *>> &Result) const
Copy out all the attachments.
Definition: Metadata.cpp:1131
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:61
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition: Metadata.h:390
static MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
Definition: Metadata.cpp:888
const APInt & getLower() const
Return the lower value for this range.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition: Metadata.cpp:233
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
static void addRange(SmallVectorImpl< ConstantInt *> &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:960
static bool hasSelfReference(MDNode *N)
Definition: Metadata.cpp:633
const unsigned Kind
T get() const
Returns the value of the specified pointer type.
Definition: PointerUnion.h:135
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
Definition: Metadata.cpp:1393
static void handleDeletion(Value *V)
Definition: Metadata.cpp:365
LLVM Value Representation.
Definition: Value.h:73
static const Function * getParent(const Value *V)
bool isTemporary() const
Definition: Metadata.h:942
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1511
std::string Hash(const Unit &U)
Definition: FuzzerSHA1.cpp:216
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:602
int is() const
Test if the Union currently holds the type matching T.
Definition: PointerUnion.h:123
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:199
static bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition: Metadata.cpp:194
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
Definition: Metadata.cpp:1303
static bool tryMergeRange(SmallVectorImpl< ConstantInt *> &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:941
static MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Definition: Metadata.cpp:922
ReplaceableMetadataImpl * getReplaceableUses() const
Definition: Metadata.h:799
Root of the metadata hierarchy.
Definition: Metadata.h:58
auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:886
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
cmpResult compare(const APFloat &RHS) const
Definition: APFloat.h:1102
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:87
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:65
void resize(size_type N)
Definition: SmallVector.h:355
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:870