LLVM 24.0.0git
Metadata.cpp
Go to the documentation of this file.
1//===- Metadata.cpp - Implement Metadata classes --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Metadata classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Metadata.h"
14#include "LLVMContextImpl.h"
15#include "MetadataImpl.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/Twine.h"
29#include "llvm/IR/Argument.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
36#include "llvm/IR/DebugLoc.h"
38#include "llvm/IR/Function.h"
41#include "llvm/IR/Instruction.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/MDBuilder.h"
44#include "llvm/IR/Module.h"
47#include "llvm/IR/Type.h"
48#include "llvm/IR/Value.h"
51
54#include "llvm/Support/ModRef.h"
55#include <cassert>
56#include <cstddef>
57#include <cstdint>
58#include <type_traits>
59#include <utility>
60#include <vector>
61
62using namespace llvm;
63
64MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
65 : Value(Ty, MetadataAsValueVal), MD(MD) {
66 track();
67}
68
73
74/// Canonicalize metadata arguments to intrinsics.
75///
76/// To support bitcode upgrades (and assembly semantic sugar) for \a
77/// MetadataAsValue, we need to canonicalize certain metadata.
78///
79/// - nullptr is replaced by an empty MDNode.
80/// - An MDNode with a single null operand is replaced by an empty MDNode.
81/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
82///
83/// This maintains readability of bitcode from when metadata was a type of
84/// value, and these bridges were unnecessary.
86 Metadata *MD) {
87 if (!MD)
88 // !{}
89 return MDNode::get(Context, {});
90
91 // Return early if this isn't a single-operand MDNode.
92 auto *N = dyn_cast<MDNode>(MD);
93 if (!N || N->getNumOperands() != 1)
94 return MD;
95
96 if (!N->getOperand(0))
97 // !{}
98 return MDNode::get(Context, {});
99
100 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
101 // Look through the MDNode.
102 return C;
103
104 return MD;
105}
106
107MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
108 MD = canonicalizeMetadataForValue(Context, MD);
109 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
110 if (!Entry)
111 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
112 return Entry;
113}
114
116 Metadata *MD) {
117 MD = canonicalizeMetadataForValue(Context, MD);
118 auto &Store = Context.pImpl->MetadataAsValues;
119 return Store.lookup(MD);
120}
121
122void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
123 LLVMContext &Context = getContext();
124 MD = canonicalizeMetadataForValue(Context, MD);
125 auto &Store = Context.pImpl->MetadataAsValues;
126
127 // Stop tracking the old metadata.
128 Store.erase(this->MD);
129 untrack();
130 this->MD = nullptr;
131
132 // Start tracking MD, or RAUW if necessary.
133 auto *&Entry = Store[MD];
134 if (Entry) {
135 replaceAllUsesWith(Entry);
136 delete this;
137 return;
138 }
139
140 this->MD = MD;
141 track();
142 Entry = this;
143}
144
145void MetadataAsValue::track() {
146 if (MD)
147 MetadataTracking::track(&MD, *MD, *this);
148}
149
150void MetadataAsValue::untrack() {
151 if (MD)
153}
154
156 return static_cast<DbgVariableRecord *>(this);
157}
159 return static_cast<const DbgVariableRecord *>(this);
160}
161
163 // NOTE: We could inform the "owner" that a value has changed through
164 // getOwner, if needed.
165 auto OldMD = static_cast<Metadata **>(Old);
166 ptrdiff_t Idx = std::distance(&*DebugValues.begin(), OldMD);
167 // If replacing a ValueAsMetadata with a nullptr, replace it with a
168 // PoisonValue instead.
169 if (OldMD && isa<ValueAsMetadata>(*OldMD) && !New) {
170 auto *OldVAM = cast<ValueAsMetadata>(*OldMD);
171 New = ValueAsMetadata::get(PoisonValue::get(OldVAM->getValue()->getType()));
172 }
173 resetDebugValue(Idx, New);
174}
175
176void DebugValueUser::trackDebugValue(size_t Idx) {
177 assert(Idx < 3 && "Invalid debug value index.");
178 Metadata *&MD = DebugValues[Idx];
179 if (MD)
180 MetadataTracking::track(&MD, *MD, *this);
181}
182
183void DebugValueUser::trackDebugValues() {
184 for (Metadata *&MD : DebugValues)
185 if (MD)
186 MetadataTracking::track(&MD, *MD, *this);
187}
188
189void DebugValueUser::untrackDebugValue(size_t Idx) {
190 assert(Idx < 3 && "Invalid debug value index.");
191 Metadata *&MD = DebugValues[Idx];
192 if (MD)
194}
195
196void DebugValueUser::untrackDebugValues() {
197 for (Metadata *&MD : DebugValues)
198 if (MD)
200}
201
202void DebugValueUser::retrackDebugValues(DebugValueUser &X) {
203 assert(DebugValueUser::operator==(X) && "Expected values to match");
204 for (const auto &[MD, XMD] : zip(DebugValues, X.DebugValues))
205 if (XMD)
207 X.DebugValues.fill(nullptr);
208}
209
210bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
211 assert(Ref && "Expected live reference");
212 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
213 "Reference without owner must be direct");
214 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
215 R->addRef(Ref, Owner);
216 return true;
217 }
218 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
219 assert(!PH->Use && "Placeholders can only be used once");
220 assert(!Owner && "Unexpected callback to owner");
221 PH->Use = static_cast<Metadata **>(Ref);
222 return true;
223 }
224 return false;
225}
226
228 assert(Ref && "Expected live reference");
229 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
230 R->dropRef(Ref);
231 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
232 PH->Use = nullptr;
233}
234
235bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
236 assert(Ref && "Expected live reference");
237 assert(New && "Expected live reference");
238 assert(Ref != New && "Expected change");
239 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
240 R->moveRef(Ref, New, MD);
241 return true;
242 }
244 "Unexpected move of an MDOperand");
245 assert(!isReplaceable(MD) &&
246 "Expected un-replaceable metadata, since we didn't move a reference");
247 return false;
248}
249
251 return ReplaceableMetadataImpl::isReplaceable(MD);
252}
253
256 for (auto Pair : UseMap) {
257 OwnerTy Owner = Pair.second.first;
258 if (Owner.isNull())
259 continue;
261 continue;
262 Metadata *OwnerMD = cast<Metadata *>(Owner);
263 if (OwnerMD->getMetadataID() == Metadata::DIArgListKind)
264 MDUsersWithID.push_back(&UseMap[Pair.first]);
265 }
266 llvm::sort(MDUsersWithID, [](auto UserA, auto UserB) {
267 return UserA->second < UserB->second;
268 });
270 for (auto *UserWithID : MDUsersWithID)
271 MDUsers.push_back(cast<Metadata *>(UserWithID->first));
272 return MDUsers;
273}
274
278 for (auto Pair : UseMap) {
279 OwnerTy Owner = Pair.second.first;
280 if (Owner.isNull())
281 continue;
283 continue;
284 DVRUsersWithID.push_back(&UseMap[Pair.first]);
285 }
286 // Order DbgVariableRecord users in reverse-creation order. Normal dbg.value
287 // users of MetadataAsValues are ordered by their UseList, i.e. reverse order
288 // of when they were added: we need to replicate that here. The structure of
289 // debug-info output depends on the ordering of intrinsics, thus we need
290 // to keep them consistent for comparisons sake.
291 llvm::sort(DVRUsersWithID, [](auto UserA, auto UserB) {
292 return UserA->second > UserB->second;
293 });
295 for (auto UserWithID : DVRUsersWithID)
296 DVRUsers.push_back(cast<DebugValueUser *>(UserWithID->first)->getUser());
297 return DVRUsers;
298}
299
300void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
301 bool WasInserted =
302 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
303 .second;
304 (void)WasInserted;
305 assert(WasInserted && "Expected to add a reference");
306
307 ++NextIndex;
308 assert(NextIndex != 0 && "Unexpected overflow");
309}
310
311void ReplaceableMetadataImpl::dropRef(void *Ref) {
312 bool WasErased = UseMap.erase(Ref);
313 (void)WasErased;
314 assert(WasErased && "Expected to drop a reference");
315}
316
317void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
318 const Metadata &MD) {
319 auto I = UseMap.find(Ref);
320 assert(I != UseMap.end() && "Expected to move a reference");
321 auto OwnerAndIndex = I->second;
322 UseMap.erase(I);
323 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
324 (void)WasInserted;
325 assert(WasInserted && "Expected to add a reference");
326
327 // Check that the references are direct if there's no owner.
328 (void)MD;
329 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
330 "Reference without owner must be direct");
331 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
332 "Reference without owner must be direct");
333}
334
336 if (!C.isUsedByMetadata()) {
337 return;
338 }
339
340 LLVMContext &Context = C.getType()->getContext();
341 auto &Store = Context.pImpl->ValuesAsMetadata;
342 auto I = Store.find(&C);
343 ValueAsMetadata *MD = I->second;
344 using UseTy =
345 std::pair<void *, std::pair<MetadataTracking::OwnerTy, uint64_t>>;
346 // Copy out uses and update value of Constant used by debug info metadata with
347 // poison below
348 SmallVector<UseTy, 8> Uses(MD->UseMap.begin(), MD->UseMap.end());
349
350 for (const auto &Pair : Uses) {
351 MetadataTracking::OwnerTy Owner = Pair.second.first;
352 if (!Owner)
353 continue;
354 // Check for MetadataAsValue.
356 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(
358 continue;
359 }
361 continue;
363 if (!OwnerMD)
364 continue;
365 if (isa<DINode>(OwnerMD)) {
366 OwnerMD->handleChangedOperand(
367 Pair.first, ValueAsMetadata::get(PoisonValue::get(C.getType())));
368 }
369 }
370}
371
373 if (UseMap.empty())
374 return;
375
376 // Copy out uses since UseMap will get touched below.
377 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
378 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
379 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
380 return L.second.second < R.second.second;
381 });
382 for (const auto &Pair : Uses) {
383 // Check that this Ref hasn't disappeared after RAUW (when updating a
384 // previous Ref).
385 if (!UseMap.count(Pair.first))
386 continue;
387
388 OwnerTy Owner = Pair.second.first;
389 if (!Owner) {
390 // Update unowned tracking references directly.
391 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
392 Ref = MD;
393 if (MD)
395 UseMap.erase(Pair.first);
396 continue;
397 }
398
399 // Check for MetadataAsValue.
401 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(MD);
402 continue;
403 }
404
405 if (auto *DVU = dyn_cast<DebugValueUser *>(Owner)) {
406 DVU->handleChangedValue(Pair.first, MD);
407 continue;
408 }
409
410 // There's a Metadata owner -- dispatch.
411 Metadata *OwnerMD = cast<Metadata *>(Owner);
412 switch (OwnerMD->getMetadataID()) {
413#define HANDLE_METADATA_LEAF(CLASS) \
414 case Metadata::CLASS##Kind: \
415 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
416 continue;
417#include "llvm/IR/Metadata.def"
418 default:
419 llvm_unreachable("Invalid metadata subclass");
420 }
421 }
422 assert(UseMap.empty() && "Expected all uses to be replaced");
423}
424
426 if (UseMap.empty())
427 return;
428
429 if (!ResolveUsers) {
430 UseMap.clear();
431 return;
432 }
433
434 // Copy out uses since UseMap could get touched below.
435 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
436 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
437 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
438 return L.second.second < R.second.second;
439 });
440 UseMap.clear();
441 for (const auto &Pair : Uses) {
442 auto Owner = Pair.second.first;
443 if (!Owner)
444 continue;
446 continue;
447
448 // Resolve MDNodes that point at this.
450 if (!OwnerMD)
451 continue;
452 if (OwnerMD->isResolved())
453 continue;
454 OwnerMD->decrementUnresolvedOperandCount();
455 }
456}
457
458// Special handing of DIArgList is required in the RemoveDIs project, see
459// commentry in DIArgList::handleChangedOperand for details. Hidden behind
460// conditional compilation to avoid a compile time regression.
461ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
462 if (auto *N = dyn_cast<MDNode>(&MD)) {
463 return !N->isResolved() || N->isAlwaysReplaceable()
464 ? N->Context.getOrCreateReplaceableUses()
465 : nullptr;
466 }
467 if (auto ArgList = dyn_cast<DIArgList>(&MD))
468 return ArgList;
469 return dyn_cast<ValueAsMetadata>(&MD);
470}
471
472ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
473 if (auto *N = dyn_cast<MDNode>(&MD)) {
474 return !N->isResolved() || N->isAlwaysReplaceable()
475 ? N->Context.getReplaceableUses()
476 : nullptr;
477 }
478 if (auto ArgList = dyn_cast<DIArgList>(&MD))
479 return ArgList;
480 return dyn_cast<ValueAsMetadata>(&MD);
481}
482
483bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
484 if (auto *N = dyn_cast<MDNode>(&MD))
485 return !N->isResolved() || N->isAlwaysReplaceable();
486 return isa<ValueAsMetadata>(&MD) || isa<DIArgList>(&MD);
487}
488
490 assert(V && "Expected value");
491 if (auto *A = dyn_cast<Argument>(V)) {
492 if (auto *Fn = A->getParent())
493 return Fn->getSubprogram();
494 return nullptr;
495 }
496
497 if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
498 if (auto *Fn = BB->getParent())
499 return Fn->getSubprogram();
500 return nullptr;
501 }
502
503 return nullptr;
504}
505
507 assert(V && "Unexpected null Value");
508
509 auto &Context = V->getContext();
510 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
511 if (!Entry) {
513 "Expected constant or function-local value");
514 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
515 V->IsUsedByMD = true;
516 if (auto *C = dyn_cast<Constant>(V))
517 Entry = new ConstantAsMetadata(C);
518 else
519 Entry = new LocalAsMetadata(V);
520 }
521
522 return Entry;
523}
524
526 assert(V && "Unexpected null Value");
527 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
528}
529
531 assert(V && "Expected valid value");
532
533 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
534 auto I = Store.find(V);
535 if (I == Store.end())
536 return;
537
538 // Remove old entry from the map.
539 ValueAsMetadata *MD = I->second;
540 assert(MD && "Expected valid metadata");
541 assert(MD->getValue() == V && "Expected valid mapping");
542 Store.erase(I);
543
544 // Delete the metadata.
545 MD->replaceAllUsesWith(nullptr);
546 delete MD;
547}
548
550 assert(From && "Expected valid value");
551 assert(To && "Expected valid value");
552 assert(From != To && "Expected changed value");
553 assert(&From->getContext() == &To->getContext() && "Expected same context");
554
555 LLVMContext &Context = From->getType()->getContext();
556 auto &Store = Context.pImpl->ValuesAsMetadata;
557 auto I = Store.find(From);
558 if (I == Store.end()) {
559 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
560 return;
561 }
562
563 // Remove old entry from the map.
564 assert(From->IsUsedByMD && "Expected From to be used by metadata");
565 From->IsUsedByMD = false;
566 ValueAsMetadata *MD = I->second;
567 assert(MD && "Expected valid metadata");
568 assert(MD->getValue() == From && "Expected valid mapping");
569 Store.erase(I);
570
571 if (isa<LocalAsMetadata>(MD)) {
572 if (auto *C = dyn_cast<Constant>(To)) {
573 // Local became a constant.
575 delete MD;
576 return;
577 }
580 // DISubprogram changed.
581 MD->replaceAllUsesWith(nullptr);
582 delete MD;
583 return;
584 }
585 } else if (!isa<Constant>(To)) {
586 // Changed to function-local value.
587 MD->replaceAllUsesWith(nullptr);
588 delete MD;
589 return;
590 }
591
592 auto *&Entry = Store[To];
593 if (Entry) {
594 // The target already exists.
596 delete MD;
597 return;
598 }
599
600 // Update MD in place (and update the map entry).
601 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
602 To->IsUsedByMD = true;
603 MD->V = To;
604 Entry = MD;
605}
606
607//===----------------------------------------------------------------------===//
608// MDString implementation.
609//
610
611MDString *MDString::get(LLVMContext &Context, StringRef Str) {
612 auto &Store = Context.pImpl->MDStringCache;
613 auto I = Store.try_emplace(Str);
614 auto &MapEntry = I.first->getValue();
615 if (!I.second)
616 return &MapEntry;
617 MapEntry.Entry = &*I.first;
618 return &MapEntry;
619}
620
622 auto &Store = Context.pImpl->MDStringCache;
623 auto I = Store.find(Str);
624 if (I == Store.end())
625 return nullptr;
626 return &I->getValue();
627}
628
630 assert(Entry && "Expected to find string map entry");
631 return Entry->first();
632}
633
634//===----------------------------------------------------------------------===//
635// MDNode implementation.
636//
637
638// Assert that the MDNode types will not be unaligned by the objects
639// prepended to them.
640#define HANDLE_MDNODE_LEAF(CLASS) \
641 static_assert( \
642 alignof(uint64_t) >= alignof(CLASS), \
643 "Alignment is insufficient after objects prepended to " #CLASS);
644#include "llvm/IR/Metadata.def"
645
646void *MDNode::operator new(size_t Size, size_t NumOps, StorageType Storage) {
647 // uint64_t is the most aligned type we need support (ensured by static_assert
648 // above)
649 static_assert(sizeof(Header) == sizeof(size_t) + 2 * sizeof(uint32_t),
650 "MDNode header fields poorly packed");
651 size_t AllocSize =
652 alignTo(Header::getAllocSize(Storage, NumOps), alignof(uint64_t));
653 char *Mem = reinterpret_cast<char *>(::operator new(AllocSize + Size));
654 Header *H = new (Mem + AllocSize - sizeof(Header)) Header(NumOps, Storage);
655 return reinterpret_cast<void *>(H + 1);
656}
657
658void MDNode::operator delete(void *N) {
659 Header *H = reinterpret_cast<Header *>(N) - 1;
660 void *Mem = H->getAllocation();
661 H->~Header();
662 ::operator delete(Mem);
663}
664
667 : Metadata(ID, Storage), Context(Context) {
668 getHeader().MetadataPrintID = Context.pImpl->allocateMetadataPrintID();
669
670 unsigned Op = 0;
671 for (Metadata *MD : Ops1)
672 setOperand(Op++, MD);
673 for (Metadata *MD : Ops2)
674 setOperand(Op++, MD);
675
676 if (!isUniqued())
677 return;
678
679 // Count the unresolved operands. If there are any, RAUW support will be
680 // added lazily on first reference.
681 countUnresolvedOperands();
682}
683
684TempMDNode MDNode::clone() const {
685 switch (getMetadataID()) {
686 default:
687 llvm_unreachable("Invalid MDNode subclass");
688#define HANDLE_MDNODE_LEAF(CLASS) \
689 case CLASS##Kind: \
690 return cast<CLASS>(this)->cloneImpl();
691#include "llvm/IR/Metadata.def"
692 }
693}
694
695MDNode::Header::Header(size_t NumOps, StorageType Storage) {
696 IsLarge = isLarge(NumOps);
697 IsResizable = isResizable(Storage);
698 SmallSize = getSmallSize(NumOps, IsResizable, IsLarge);
699 if (IsLarge) {
700 SmallNumOps = 0;
701 new (getLargePtr()) LargeStorageVector();
702 getLarge().resize(NumOps);
703 return;
704 }
705 SmallNumOps = NumOps;
706 MDOperand *O = reinterpret_cast<MDOperand *>(this) - SmallSize;
707 for (MDOperand *E = O + SmallSize; O != E;)
708 (void)new (O++) MDOperand();
709}
710
711MDNode::Header::~Header() {
712 if (IsLarge) {
713 getLarge().~LargeStorageVector();
714 return;
715 }
716 MDOperand *O = reinterpret_cast<MDOperand *>(this);
717 for (MDOperand *E = O - SmallSize; O != E; --O)
718 (O - 1)->~MDOperand();
719}
720
721void *MDNode::Header::getSmallPtr() {
722 static_assert(alignof(MDOperand) <= alignof(Header),
723 "MDOperand too strongly aligned");
724 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
725 sizeof(MDOperand) * SmallSize;
726}
727
728void MDNode::Header::resize(size_t NumOps) {
729 assert(IsResizable && "Node is not resizable");
730 if (operands().size() == NumOps)
731 return;
732
733 if (IsLarge)
734 getLarge().resize(NumOps);
735 else if (NumOps <= SmallSize)
736 resizeSmall(NumOps);
737 else
738 resizeSmallToLarge(NumOps);
739}
740
741void MDNode::Header::resizeSmall(size_t NumOps) {
742 assert(!IsLarge && "Expected a small MDNode");
743 assert(NumOps <= SmallSize && "NumOps too large for small resize");
744
745 MutableArrayRef<MDOperand> ExistingOps = operands();
746 assert(NumOps != ExistingOps.size() && "Expected a different size");
747
748 int NumNew = (int)NumOps - (int)ExistingOps.size();
749 MDOperand *O = ExistingOps.end();
750 for (int I = 0, E = NumNew; I < E; ++I)
751 (O++)->reset();
752 for (int I = 0, E = NumNew; I > E; --I)
753 (--O)->reset();
754 SmallNumOps = NumOps;
755 assert(O == operands().end() && "Operands not (un)initialized until the end");
756}
757
758void MDNode::Header::resizeSmallToLarge(size_t NumOps) {
759 assert(!IsLarge && "Expected a small MDNode");
760 assert(NumOps > SmallSize && "Expected NumOps to be larger than allocation");
761 LargeStorageVector NewOps;
762 NewOps.resize(NumOps);
763 llvm::move(operands(), NewOps.begin());
764 resizeSmall(0);
765 new (getLargePtr()) LargeStorageVector(std::move(NewOps));
766 IsLarge = true;
767}
768
770 if (auto *N = dyn_cast_or_null<MDNode>(Op))
771 return !N->isResolved();
772 return false;
773}
774
775void MDNode::countUnresolvedOperands() {
776 assert(getNumUnresolved() == 0 && "Expected unresolved ops to be uncounted");
777 assert(isUniqued() && "Expected this to be uniqued");
779}
780
781void MDNode::makeUniqued() {
782 assert(isTemporary() && "Expected this to be temporary");
783 assert(!isResolved() && "Expected this to be unresolved");
784 bool WasTracked = getContext().pImpl->TemporaryMDNodes.erase(this);
785 assert(WasTracked && "Temporary node not tracked");
786 (void)WasTracked;
787
788 // Enable uniquing callbacks.
789 for (auto &Op : mutable_operands())
790 Op.reset(Op.get(), this);
791
792 // Make this 'uniqued'.
794 countUnresolvedOperands();
795 if (!getNumUnresolved()) {
796 dropReplaceableUses();
797 assert(isResolved() && "Expected this to be resolved");
798 }
799
800 assert(isUniqued() && "Expected this to be uniqued");
801}
802
803void MDNode::makeDistinct() {
804 assert(isTemporary() && "Expected this to be temporary");
805 assert(!isResolved() && "Expected this to be unresolved");
806
807 // Drop RAUW support and store as a distinct node.
808 dropReplaceableUses();
810
811 assert(isDistinct() && "Expected this to be distinct");
812 assert(isResolved() && "Expected this to be resolved");
813}
814
816 assert(isUniqued() && "Expected this to be uniqued");
817 assert(!isResolved() && "Expected this to be unresolved");
818
820 dropReplaceableUses();
821
822 assert(isResolved() && "Expected this to be resolved");
823}
824
825void MDNode::dropReplaceableUses() {
826 assert(!getNumUnresolved() && "Unexpected unresolved operand");
827
828 // Drop any RAUW support.
829 if (Context.hasReplaceableUses())
830 Context.takeReplaceableUses()->resolveAllUses();
831}
832
833void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
834 assert(isUniqued() && "Expected this to be uniqued");
835 assert(getNumUnresolved() != 0 && "Expected unresolved operands");
836
837 // Check if an operand was resolved.
838 if (!isOperandUnresolved(Old)) {
839 if (isOperandUnresolved(New))
840 // An operand was un-resolved!
842 } else if (!isOperandUnresolved(New))
843 decrementUnresolvedOperandCount();
844}
845
846void MDNode::decrementUnresolvedOperandCount() {
847 assert(!isResolved() && "Expected this to be unresolved");
848 if (isTemporary())
849 return;
850
851 assert(isUniqued() && "Expected this to be uniqued");
853 if (getNumUnresolved())
854 return;
855
856 // Last unresolved operand has just been resolved.
857 dropReplaceableUses();
858 assert(isResolved() && "Expected this to become resolved");
859}
860
862 if (isResolved())
863 return;
864
865 // Resolve this node immediately.
866 resolve();
867
868 // Resolve all operands.
869 for (const auto &Op : operands()) {
871 if (!N)
872 continue;
873
874 assert(!N->isTemporary() &&
875 "Expected all forward declarations to be resolved");
876 if (!N->isResolved())
877 N->resolveCycles();
878 }
879}
880
881static bool hasSelfReference(MDNode *N) {
882 return llvm::is_contained(N->operands(), N);
883}
884
885MDNode *MDNode::replaceWithPermanentImpl() {
886 switch (getMetadataID()) {
887 default:
888 // If this type isn't uniquable, replace with a distinct node.
889 return replaceWithDistinctImpl();
890
891#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
892 case CLASS##Kind: \
893 break;
894#include "llvm/IR/Metadata.def"
895 }
896
897 // Even if this type is uniquable, self-references have to be distinct.
898 if (hasSelfReference(this))
899 return replaceWithDistinctImpl();
900 return replaceWithUniquedImpl();
901}
902
903MDNode *MDNode::replaceWithUniquedImpl() {
904 // Try to uniquify in place.
905 MDNode *UniquedNode = uniquify();
906
907 if (UniquedNode == this) {
908 makeUniqued();
909 return this;
910 }
911
912 // Collision, so RAUW instead.
913 replaceAllUsesWith(UniquedNode);
914 deleteAsSubclass();
915 return UniquedNode;
916}
917
918MDNode *MDNode::replaceWithDistinctImpl() {
919 makeDistinct();
920 return this;
921}
922
923void MDTuple::recalculateHash() {
924 setHash(MDTupleInfo::KeyTy::calculateHash(this));
925}
926
928 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
929 setOperand(I, nullptr);
930 if (Context.hasReplaceableUses()) {
931 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
932 (void)Context.takeReplaceableUses();
933 }
934}
935
936void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
937 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
938 assert(Op < getNumOperands() && "Expected valid operand");
939
940 if (!isUniqued()) {
941 // This node is not uniqued. Just set the operand and be done with it.
942 setOperand(Op, New);
943 return;
944 }
945
946 // This node is uniqued.
947 eraseFromStore();
948
949 Metadata *Old = getOperand(Op);
950 setOperand(Op, New);
951
952 // Drop uniquing for self-reference cycles and deleted constants.
953 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
954 if (!isResolved())
955 resolve();
957 return;
958 }
959
960 // Re-unique the node.
961 auto *Uniqued = uniquify();
962 if (Uniqued == this) {
963 if (!isResolved())
964 resolveAfterOperandChange(Old, New);
965 return;
966 }
967
968 // Collision.
969 if (!isResolved()) {
970 // Still unresolved, so RAUW.
971 //
972 // First, clear out all operands to prevent any recursion (similar to
973 // dropAllReferences(), but we still need the use-list).
974 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
975 setOperand(O, nullptr);
976 if (Context.hasReplaceableUses())
977 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
978 deleteAsSubclass();
979 return;
980 }
981
982 // Store in non-uniqued form if RAUW isn't possible.
984}
985
986void MDNode::deleteAsSubclass() {
987 if (isTemporary()) {
988 bool WasTracked = getContext().pImpl->TemporaryMDNodes.erase(this);
989 assert(WasTracked && "Temporary node not tracked");
990 (void)WasTracked;
991 }
992 switch (getMetadataID()) {
993 default:
994 llvm_unreachable("Invalid subclass of MDNode");
995#define HANDLE_MDNODE_LEAF(CLASS) \
996 case CLASS##Kind: \
997 delete cast<CLASS>(this); \
998 break;
999#include "llvm/IR/Metadata.def"
1000 }
1001}
1002
1003template <class T, class InfoT>
1005 if (T *U = getUniqued(Store, N))
1006 return U;
1007
1008 Store.insert(N);
1009 return N;
1010}
1011
1012template <class NodeTy> struct MDNode::HasCachedHash {
1013 template <class U>
1014 static std::true_type check(SameType<void (U::*)(unsigned), &U::setHash> *);
1015 template <class U> static std::false_type check(...);
1016
1017 static constexpr bool value = decltype(check<NodeTy>(nullptr))::value;
1018};
1019
1020MDNode *MDNode::uniquify() {
1021 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
1022
1023 // Try to insert into uniquing store.
1024 switch (getMetadataID()) {
1025 default:
1026 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
1027#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1028 case CLASS##Kind: { \
1029 CLASS *SubclassThis = cast<CLASS>(this); \
1030 dispatchRecalculateHash(SubclassThis); \
1031 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
1032 }
1033#include "llvm/IR/Metadata.def"
1034 }
1035}
1036
1037void MDNode::eraseFromStore() {
1038 switch (getMetadataID()) {
1039 default:
1040 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
1041#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1042 case CLASS##Kind: \
1043 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
1044 break;
1045#include "llvm/IR/Metadata.def"
1046 }
1047}
1048
1049MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1050 StorageType Storage, bool ShouldCreate) {
1051 unsigned Hash = 0;
1052 if (Storage == Uniqued) {
1053 MDTupleInfo::KeyTy Key(MDs);
1054 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
1055 return N;
1056 if (!ShouldCreate)
1057 return nullptr;
1058 Hash = Key.getHash();
1059 } else {
1060 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
1061 }
1062
1063 return storeImpl(new (MDs.size(), Storage)
1064 MDTuple(Context, Storage, Hash, MDs),
1065 Storage, Context.pImpl->MDTuples);
1066}
1067
1069 assert(N->isTemporary() && "Expected temporary node");
1070 N->replaceAllUsesWith(nullptr);
1071 N->deleteAsSubclass();
1072}
1073
1075 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
1076 assert(!getNumUnresolved() && "Unexpected unresolved nodes");
1077 if (isTemporary()) {
1078 bool WasTracked = getContext().pImpl->TemporaryMDNodes.erase(this);
1079 assert(WasTracked && "Temporary node not tracked");
1080 (void)WasTracked;
1081 }
1082 Storage = Distinct;
1083 assert(isResolved() && "Expected this to be resolved");
1084
1085 // Reset the hash.
1086 switch (getMetadataID()) {
1087 default:
1088 llvm_unreachable("Invalid subclass of MDNode");
1089#define HANDLE_MDNODE_LEAF(CLASS) \
1090 case CLASS##Kind: { \
1091 dispatchResetHash(cast<CLASS>(this)); \
1092 break; \
1093 }
1094#include "llvm/IR/Metadata.def"
1095 }
1096
1097 getContext().pImpl->DistinctMDNodes.push_back(this);
1098}
1099
1101 if (getOperand(I) == New)
1102 return;
1103
1104 if (!isUniqued()) {
1105 setOperand(I, New);
1106 return;
1107 }
1108
1109 handleChangedOperand(mutable_begin() + I, New);
1110}
1111
1112void MDNode::setOperand(unsigned I, Metadata *New) {
1113 assert(I < getNumOperands());
1114 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
1115}
1116
1117/// Get a node or a self-reference that looks like it.
1118///
1119/// Special handling for finding self-references, for use by \a
1120/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
1121/// when self-referencing nodes were still uniqued. If the first operand has
1122/// the same operands as \c Ops, return the first operand instead.
1125 if (!Ops.empty())
1127 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
1128 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
1129 if (Ops[I] != N->getOperand(I))
1130 return MDNode::get(Context, Ops);
1131 return N;
1132 }
1133
1134 return MDNode::get(Context, Ops);
1135}
1136
1138 if (!A)
1139 return B;
1140 if (!B)
1141 return A;
1142
1143 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
1144 MDs.insert(B->op_begin(), B->op_end());
1145
1146 // FIXME: This preserves long-standing behaviour, but is it really the right
1147 // behaviour? Or was that an unintended side-effect of node uniquing?
1148 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
1149}
1150
1152 if (!A || !B)
1153 return nullptr;
1154
1155 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
1156 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
1157 MDs.remove_if([&](Metadata *MD) { return !BSet.count(MD); });
1158
1159 // FIXME: This preserves long-standing behaviour, but is it really the right
1160 // behaviour? Or was that an unintended side-effect of node uniquing?
1161 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
1162}
1163
1165 if (!A || !B)
1166 return nullptr;
1167
1168 // Take the intersection of domains then union the scopes
1169 // within those domains
1171 SmallPtrSet<const MDNode *, 16> IntersectDomains;
1173 for (const MDOperand &MDOp : A->operands())
1174 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1175 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1176 ADomains.insert(Domain);
1177
1178 for (const MDOperand &MDOp : B->operands())
1179 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1180 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1181 if (ADomains.contains(Domain)) {
1182 IntersectDomains.insert(Domain);
1183 MDs.insert(MDOp);
1184 }
1185
1186 for (const MDOperand &MDOp : A->operands())
1187 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1188 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1189 if (IntersectDomains.contains(Domain))
1190 MDs.insert(MDOp);
1191
1192 return MDs.empty() ? nullptr
1193 : getOrSelfReference(A->getContext(), MDs.getArrayRef());
1194}
1195
1197 if (!A || !B)
1198 return nullptr;
1199
1200 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
1201 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
1202 if (AVal < BVal)
1203 return A;
1204 return B;
1205}
1206
1207// Call instructions with branch weights are only used in SamplePGO as
1208// documented in
1209/// https://llvm.org/docs/BranchWeightMetadata.html#callinst).
1210MDNode *MDNode::mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1211 const Instruction *AInstr,
1212 const Instruction *BInstr) {
1213 assert(A && B && AInstr && BInstr && "Caller should guarantee");
1214 auto &Ctx = AInstr->getContext();
1215 MDBuilder MDHelper(Ctx);
1216
1217 // LLVM IR verifier verifies !prof metadata has at least 2 operands.
1218 assert(A->getNumOperands() >= 2 && B->getNumOperands() >= 2 &&
1219 "!prof annotations should have no less than 2 operands");
1220 MDString *AMDS = dyn_cast<MDString>(A->getOperand(0));
1221 MDString *BMDS = dyn_cast<MDString>(B->getOperand(0));
1222 // LLVM IR verfier verifies first operand is MDString.
1223 assert(AMDS != nullptr && BMDS != nullptr &&
1224 "first operand should be a non-null MDString");
1225 StringRef AProfName = AMDS->getString();
1226 StringRef BProfName = BMDS->getString();
1227 if (AProfName == MDProfLabels::BranchWeights &&
1228 BProfName == MDProfLabels::BranchWeights) {
1230 A->getOperand(getBranchWeightOffset(A)));
1232 B->getOperand(getBranchWeightOffset(B)));
1233 assert(AInstrWeight && BInstrWeight && "verified by LLVM verifier");
1234 return MDNode::get(Ctx,
1235 {MDHelper.createString(MDProfLabels::BranchWeights),
1236 MDHelper.createConstant(ConstantInt::get(
1237 Type::getInt64Ty(Ctx),
1238 SaturatingAdd(AInstrWeight->getZExtValue(),
1239 BInstrWeight->getZExtValue())))});
1240 }
1241 return nullptr;
1242}
1243
1244// Pass in both instructions and nodes. Instruction information (e.g.,
1245// instruction type) helps interpret profiles and make implementation clearer.
1247 const Instruction *AInstr,
1248 const Instruction *BInstr) {
1249 // Check that it is legal to merge prof metadata based on the opcode.
1250 auto IsLegal = [](const Instruction &I) -> bool {
1251 switch (I.getOpcode()) {
1252 case Instruction::Invoke:
1253 case Instruction::CondBr:
1254 case Instruction::Switch:
1255 case Instruction::Call:
1256 case Instruction::IndirectBr:
1257 case Instruction::Select:
1258 case Instruction::CallBr:
1259 return true;
1260 default:
1261 return false;
1262 }
1263 };
1264 if (AInstr && !IsLegal(*AInstr))
1265 return nullptr;
1266 if (BInstr && !IsLegal(*BInstr))
1267 return nullptr;
1268
1269 if (!(A && B)) {
1270 return A ? A : B;
1271 }
1272
1273 assert(AInstr->getMetadata(LLVMContext::MD_prof) == A &&
1274 "Caller should guarantee");
1275 assert(BInstr->getMetadata(LLVMContext::MD_prof) == B &&
1276 "Caller should guarantee");
1277
1278 const CallInst *ACall = dyn_cast<CallInst>(AInstr);
1279 const CallInst *BCall = dyn_cast<CallInst>(BInstr);
1280
1281 // Both ACall and BCall are direct callsites.
1282 if (ACall && BCall && ACall->getCalledFunction() &&
1283 BCall->getCalledFunction())
1284 return mergeDirectCallProfMetadata(A, B, AInstr, BInstr);
1285
1286 if (A == B)
1287 return A;
1288
1289 // The rest of the cases are not implemented but could be added
1290 // when there are use cases.
1291 return nullptr;
1292}
1293
1294static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1295 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1296}
1297
1298static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
1299 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
1300}
1301
1304 ConstantRange NewRange(Low->getValue(), High->getValue());
1305 unsigned Size = EndPoints.size();
1306 const APInt &LB = EndPoints[Size - 2]->getValue();
1307 const APInt &LE = EndPoints[Size - 1]->getValue();
1308 ConstantRange LastRange(LB, LE);
1309 if (canBeMerged(NewRange, LastRange)) {
1310 ConstantRange Union = LastRange.unionWith(NewRange);
1311 Type *Ty = High->getType();
1312 EndPoints[Size - 2] =
1313 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
1314 EndPoints[Size - 1] =
1315 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
1316 return true;
1317 }
1318 return false;
1319}
1320
1323 if (!EndPoints.empty())
1324 if (tryMergeRange(EndPoints, Low, High))
1325 return;
1326
1327 EndPoints.push_back(Low);
1328 EndPoints.push_back(High);
1329}
1330
1332 // Drop the callee_type metadata if either of the call instructions do not
1333 // have it.
1334 if (!A || !B)
1335 return nullptr;
1337 SmallPtrSet<Metadata *, 8> MergedCallees;
1338 auto AddUniqueCallees = [&AB, &MergedCallees](const MDNode *N) {
1339 for (Metadata *MD : N->operands()) {
1340 if (MergedCallees.insert(MD).second)
1341 AB.push_back(MD);
1342 }
1343 };
1344 AddUniqueCallees(A);
1345 AddUniqueCallees(B);
1346 return MDNode::get(A->getContext(), AB);
1347}
1348
1350 // Drop !alloc_token metadata if either instruction lacks it to avoid mis-
1351 // classifying unclassified allocations, where the fallback token must be
1352 // used instead.
1353 if (!A || !B)
1354 return nullptr;
1355 if (A == B)
1356 return const_cast<MDNode *>(A);
1357 if (A->getNumOperands() != 2 || B->getNumOperands() != 2)
1358 return nullptr;
1359 auto *CIA = mdconst::dyn_extract_or_null<ConstantInt>(A->getOperand(1));
1360 auto *CIB = mdconst::dyn_extract_or_null<ConstantInt>(B->getOperand(1));
1361 if (!CIA || !CIB)
1362 return nullptr;
1363
1364 MDString *NameA = dyn_cast<MDString>(A->getOperand(0));
1365 MDString *NameB = dyn_cast<MDString>(B->getOperand(0));
1366 if (!NameA || !NameB)
1367 return nullptr;
1368
1369 if (NameA == NameB)
1370 return CIA->isOne() ? const_cast<MDNode *>(A) : const_cast<MDNode *>(B);
1371
1372 LLVMContext &Ctx = A->getContext();
1373 StringRef StrA = NameA->getString();
1374 StringRef StrB = NameB->getString();
1375
1376 SmallString<64> Buffer;
1377 Buffer.reserve(StrA.size() + 1 + StrB.size());
1378 Buffer.append(StrA);
1379 Buffer.push_back('|');
1380 Buffer.append(StrB);
1381
1382 bool MergedContainsPointer = CIA->isOne() || CIB->isOne();
1383 Metadata *Ops[] = {MDString::get(Ctx, Buffer),
1384 ConstantAsMetadata::get(ConstantInt::get(
1385 Type::getInt1Ty(Ctx), MergedContainsPointer))};
1386 return MDNode::get(Ctx, Ops);
1387}
1388
1390 // Given two ranges, we want to compute the union of the ranges. This
1391 // is slightly complicated by having to combine the intervals and merge
1392 // the ones that overlap.
1393
1394 if (!A || !B)
1395 return nullptr;
1396
1397 if (A == B)
1398 return A;
1399
1400 // First, walk both lists in order of the lower boundary of each interval.
1401 // At each step, try to merge the new interval to the last one we added.
1403 unsigned AI = 0;
1404 unsigned BI = 0;
1405 unsigned AN = A->getNumOperands() / 2;
1406 unsigned BN = B->getNumOperands() / 2;
1407 while (AI < AN && BI < BN) {
1408 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
1409 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
1410
1411 if (ALow->getValue().slt(BLow->getValue())) {
1412 addRange(EndPoints, ALow,
1413 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1414 ++AI;
1415 } else {
1416 addRange(EndPoints, BLow,
1417 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1418 ++BI;
1419 }
1420 }
1421 while (AI < AN) {
1422 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1423 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1424 ++AI;
1425 }
1426 while (BI < BN) {
1427 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1428 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1429 ++BI;
1430 }
1431
1432 // We haven't handled wrap in the previous merge,
1433 // if we have at least 2 ranges (4 endpoints) we have to try to merge
1434 // the last and first ones.
1435 unsigned Size = EndPoints.size();
1436 if (Size > 2) {
1437 ConstantInt *FB = EndPoints[0];
1438 ConstantInt *FE = EndPoints[1];
1439 if (tryMergeRange(EndPoints, FB, FE)) {
1440 for (unsigned i = 0; i < Size - 2; ++i) {
1441 EndPoints[i] = EndPoints[i + 2];
1442 }
1443 EndPoints.resize(Size - 2);
1444 }
1445 }
1446
1447 // If in the end we have a single range, it is possible that it is now the
1448 // full range. Just drop the metadata in that case.
1449 if (EndPoints.size() == 2) {
1450 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1451 if (Range.isFullSet())
1452 return nullptr;
1453 }
1454
1456 MDs.reserve(EndPoints.size());
1457 for (auto *I : EndPoints)
1459 return MDNode::get(A->getContext(), MDs);
1460}
1461
1463 if (!A || !B)
1464 return nullptr;
1465
1466 if (A == B)
1467 return A;
1468
1469 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1470 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1471 unsigned Intersect = AVal->getZExtValue() & BVal->getZExtValue();
1472 if (Intersect == 0)
1473 return nullptr;
1474
1475 return MDNode::get(A->getContext(), ConstantAsMetadata::get(ConstantInt::get(
1476 AVal->getType(), Intersect)));
1477}
1478
1480 if (!A || !B)
1481 return nullptr;
1482
1483 if (A == B)
1484 return A;
1485
1486 SmallVector<ConstantRange> RangeListA, RangeListB;
1487 for (unsigned I = 0, E = A->getNumOperands() / 2; I != E; ++I) {
1488 auto *LowA = mdconst::extract<ConstantInt>(A->getOperand(2 * I + 0));
1489 auto *HighA = mdconst::extract<ConstantInt>(A->getOperand(2 * I + 1));
1490 RangeListA.push_back(ConstantRange(LowA->getValue(), HighA->getValue()));
1491 }
1492
1493 for (unsigned I = 0, E = B->getNumOperands() / 2; I != E; ++I) {
1494 auto *LowB = mdconst::extract<ConstantInt>(B->getOperand(2 * I + 0));
1495 auto *HighB = mdconst::extract<ConstantInt>(B->getOperand(2 * I + 1));
1496 RangeListB.push_back(ConstantRange(LowB->getValue(), HighB->getValue()));
1497 }
1498
1499 ConstantRangeList CRLA(RangeListA);
1500 ConstantRangeList CRLB(RangeListB);
1501 ConstantRangeList Result = CRLA.intersectWith(CRLB);
1502 if (Result.empty())
1503 return nullptr;
1504
1506 for (const ConstantRange &CR : Result) {
1508 ConstantInt::get(A->getContext(), CR.getLower())));
1510 ConstantInt::get(A->getContext(), CR.getUpper())));
1511 }
1512
1513 return MDNode::get(A->getContext(), MDs);
1514}
1515
1517 if (!A || !B)
1518 return nullptr;
1519
1520 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1521 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1522 if (AVal->getZExtValue() < BVal->getZExtValue())
1523 return A;
1524 return B;
1525}
1526
1528 if (!MD)
1530
1532 for (Metadata *Op : MD->operands()) {
1533 CaptureComponents Component =
1535 .Case("address", CaptureComponents::Address)
1536 .Case("address_is_null", CaptureComponents::AddressIsNull)
1537 .Case("provenance", CaptureComponents::Provenance)
1538 .Case("read_provenance", CaptureComponents::ReadProvenance);
1539 CC |= Component;
1540 }
1541 return CC;
1542}
1543
1545 assert(!capturesNothing(CC) && "Can't encode captures(none)");
1546 if (capturesAll(CC))
1547 return nullptr;
1548
1549 SmallVector<Metadata *> Components;
1551 Components.push_back(MDString::get(Ctx, "address_is_null"));
1552 else if (capturesAddress(CC))
1553 Components.push_back(MDString::get(Ctx, "address"));
1555 Components.push_back(MDString::get(Ctx, "read_provenance"));
1556 else if (capturesFullProvenance(CC))
1557 Components.push_back(MDString::get(Ctx, "provenance"));
1558 return MDNode::get(Ctx, Components);
1559}
1560
1561//===----------------------------------------------------------------------===//
1562// NamedMDNode implementation.
1563//
1564
1568
1569NamedMDNode::NamedMDNode(const Twine &N)
1570 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1571
1574 delete &getNMDOps(Operands);
1575}
1576
1578 return (unsigned)getNMDOps(Operands).size();
1579}
1580
1582 assert(i < getNumOperands() && "Invalid Operand number!");
1583 auto *N = getNMDOps(Operands)[i].get();
1584 return cast_or_null<MDNode>(N);
1585}
1586
1587void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1588
1589void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1590 assert(I < getNumOperands() && "Invalid operand number");
1591 getNMDOps(Operands)[I].reset(New);
1592}
1593
1595
1596void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1597
1599
1600//===----------------------------------------------------------------------===//
1601// Instruction Metadata method implementations.
1602//
1603
1604unsigned &Value::getMetadataIndex() {
1605 if (auto *I = dyn_cast<Instruction>(this))
1606 return I->MetadataIndex;
1607 return cast<GlobalObject>(this)->MetadataIndex;
1608}
1609
1610unsigned Value::getMetadataIndex() const {
1611 return const_cast<Value *>(this)->getMetadataIndex();
1612}
1613
1615 unsigned KindID = getContext().getMDKindID(Kind);
1616 return getMetadataImpl(KindID);
1617}
1618
1619MDNode *Value::getMetadataImpl(unsigned KindID) const {
1620 const LLVMContext &Ctx = getContext();
1621 unsigned Idx = getMetadataIndex();
1622 while (Idx) {
1623 const MDAttachment &A = Ctx.pImpl->Metadatas[Idx];
1624 if (A.MDKind == KindID)
1625 return A.Node;
1626 Idx = A.Next;
1627 }
1628 return nullptr;
1629}
1630
1631void GlobalObject::getMetadata(unsigned KindID,
1632 SmallVectorImpl<MDNode *> &MDs) const {
1633 const LLVMContext &Ctx = getContext();
1634 unsigned Idx = MetadataIndex;
1635 while (Idx) {
1636 const MDAttachment &A = Ctx.pImpl->Metadatas[Idx];
1637 if (A.MDKind == KindID)
1638 MDs.push_back(A.Node);
1639 Idx = A.Next;
1640 }
1641 // We store metadata in reverse order, so reverse for output.
1642 std::reverse(MDs.begin(), MDs.end());
1643}
1644
1646 SmallVectorImpl<MDNode *> &MDs) const {
1647 getMetadata(getContext().getMDKindID(Kind), MDs);
1648}
1649
1651 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1652 const LLVMContext &Ctx = getContext();
1653 unsigned Idx = getMetadataIndex();
1654 while (Idx) {
1655 const MDAttachment &A = Ctx.pImpl->Metadatas[Idx];
1656 MDs.emplace_back(A.MDKind, A.Node);
1657 Idx = A.Next;
1658 }
1659 // We store metadata in reverse order, so reverse for output in insertion
1660 // order. Sort by metadata ID for stable output.
1661 if (MDs.size() > 1) {
1662 std::reverse(MDs.begin(), MDs.end());
1664 }
1665}
1666
1667void Value::setMetadata(unsigned KindID, MDNode *Node) {
1669
1670 if (getMetadataIndex() != 0)
1671 eraseMetadata(KindID);
1672 if (Node)
1673 addMetadata(KindID, *Node);
1674}
1675
1677 if (!Node && getMetadataIndex() == 0)
1678 return;
1679 setMetadata(getContext().getMDKindID(Kind), Node);
1680}
1681
1682void Value::addMetadata(unsigned KindID, MDNode &MD) {
1683 const LLVMContext &Ctx = getContext();
1684 unsigned &Idx = getMetadataIndex();
1685 unsigned NewIdx = Ctx.pImpl->MetadataRecycleHead;
1686 if (NewIdx == 0) {
1687 NewIdx = Ctx.pImpl->Metadatas.size();
1688 if (NewIdx == 0)
1689 NewIdx = 1;
1690 Ctx.pImpl->Metadatas.resize(NewIdx + 1);
1691 } else {
1692 Ctx.pImpl->MetadataRecycleHead = Ctx.pImpl->Metadatas[NewIdx].Next;
1693#ifndef NDEBUG
1694 Ctx.pImpl->MetadataRecycleSize -= 1;
1695#endif
1696 }
1697 Ctx.pImpl->Metadatas[NewIdx] =
1698 MDAttachment{Idx, KindID, TrackingMDNodeRef(&MD)};
1699 Idx = NewIdx;
1700}
1701
1703 addMetadata(getContext().getMDKindID(Kind), MD);
1704}
1705
1706bool Value::eraseMetadata(unsigned KindID) {
1707 bool Changed = false;
1708 eraseMetadataIf([&Changed, KindID](unsigned MDKind, MDNode *) {
1709 Changed |= MDKind == KindID;
1710 return MDKind == KindID;
1711 });
1712 return Changed;
1713}
1714
1715void Value::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {
1716 unsigned *Idx = &getMetadataIndex();
1717 const LLVMContext &Ctx = getContext();
1718 while (*Idx) {
1719 MDAttachment &A = Ctx.pImpl->Metadatas[*Idx];
1720 if (Pred(A.MDKind, A.Node)) {
1721 A.Node.reset();
1722 unsigned FreeIdx = *Idx;
1723 *Idx = A.Next;
1724 A.Next = Ctx.pImpl->MetadataRecycleHead;
1725 Ctx.pImpl->MetadataRecycleHead = FreeIdx;
1726#ifndef NDEBUG
1727 Ctx.pImpl->MetadataRecycleSize += 1;
1728#endif
1729 } else {
1730 Idx = &A.Next;
1731 }
1732 }
1733}
1734
1736 eraseMetadataIf([](unsigned, MDNode *) { return true; });
1737}
1738
1740 if (!Node && MetadataIndex == 0)
1741 return;
1742 setMetadata(getContext().getMDKindID(Kind), Node);
1743}
1744
1745MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1746 const LLVMContext &Ctx = getContext();
1747 unsigned KindID = Ctx.getMDKindID(Kind);
1748 if (KindID == LLVMContext::MD_dbg)
1749 return DbgLoc.getAsMDNode();
1750 return Value::getMetadataImpl(KindID);
1751}
1752
1753void Instruction::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {
1754 if (DbgLoc && Pred(LLVMContext::MD_dbg, DbgLoc.getAsMDNode()))
1755 DbgLoc = {};
1756
1758}
1759
1762 return; // Nothing to remove!
1763
1764 SmallSet<unsigned, 32> KnownSet(llvm::from_range, KnownIDs);
1765
1766 // A DIAssignID attachment is debug metadata, don't drop it.
1767 KnownSet.insert(LLVMContext::MD_DIAssignID);
1768
1769 Value::eraseMetadataIf([&KnownSet](unsigned MDKind, MDNode *Node) {
1770 return !KnownSet.count(MDKind);
1771 });
1772}
1773
1774void Instruction::updateDIAssignIDMapping(DIAssignID *ID) {
1775 auto &IDToInstrs = getContext().pImpl->AssignmentIDToInstrs;
1776 if (const DIAssignID *CurrentID =
1777 cast_or_null<DIAssignID>(getMetadata(LLVMContext::MD_DIAssignID))) {
1778 // Nothing to do if the ID isn't changing.
1779 if (ID == CurrentID)
1780 return;
1781
1782 // Unmap this instruction from its current ID.
1783 auto InstrsIt = IDToInstrs.find(CurrentID);
1784 assert(InstrsIt != IDToInstrs.end() &&
1785 "Expect existing attachment to be mapped");
1786
1787 auto &InstVec = InstrsIt->second;
1788 auto *InstIt = llvm::find(InstVec, this);
1789 assert(InstIt != InstVec.end() &&
1790 "Expect instruction to be mapped to attachment");
1791 // The vector contains a ptr to this. If this is the only element in the
1792 // vector, remove the ID:vector entry, otherwise just remove the
1793 // instruction from the vector.
1794 if (InstVec.size() == 1)
1795 IDToInstrs.erase(InstrsIt);
1796 else
1797 InstVec.erase(InstIt);
1798 }
1799
1800 // Map this instruction to the new ID.
1801 if (ID)
1802 IDToInstrs[ID].push_back(this);
1803}
1804
1805void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1806 if (!Node && !hasMetadata())
1807 return;
1808
1809 // Handle 'dbg' as a special case since it is not stored in the hash table.
1810 if (KindID == LLVMContext::MD_dbg) {
1812 return;
1813 }
1814
1815 // Update DIAssignID to Instruction(s) mapping.
1816 if (KindID == LLVMContext::MD_DIAssignID) {
1817 // The DIAssignID tracking infrastructure doesn't support RAUWing temporary
1818 // nodes with DIAssignIDs. The cast_or_null below would also catch this, but
1819 // having a dedicated assert helps make this obvious.
1820 assert((!Node || !Node->isTemporary()) &&
1821 "Temporary DIAssignIDs are invalid");
1822 updateDIAssignIDMapping(cast_or_null<DIAssignID>(Node));
1823 }
1824
1825 Value::setMetadata(KindID, Node);
1826}
1827
1830 if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {
1831 SmallSetVector<StringRef, 2> AnnotationsSet(Annotations.begin(),
1832 Annotations.end());
1833 auto *Tuple = cast<MDTuple>(Existing);
1834 for (auto &N : Tuple->operands()) {
1835 if (isa<MDString>(N.get())) {
1836 Names.push_back(N);
1837 continue;
1838 }
1839 auto *MDAnnotationTuple = cast<MDTuple>(N);
1840 if (any_of(MDAnnotationTuple->operands(), [&AnnotationsSet](auto &Op) {
1841 return AnnotationsSet.contains(cast<MDString>(Op)->getString());
1842 }))
1843 return;
1844 Names.push_back(N);
1845 }
1846 }
1847
1848 MDBuilder MDB(getContext());
1849 SmallVector<Metadata *> MDAnnotationStrings;
1850 for (StringRef Annotation : Annotations)
1851 MDAnnotationStrings.push_back(MDB.createString(Annotation));
1852 MDNode *InfoTuple = MDTuple::get(getContext(), MDAnnotationStrings);
1853 Names.push_back(InfoTuple);
1854 MDNode *MD = MDTuple::get(getContext(), Names);
1855 setMetadata(LLVMContext::MD_annotation, MD);
1856}
1857
1860 if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {
1861 auto *Tuple = cast<MDTuple>(Existing);
1862 for (auto &N : Tuple->operands()) {
1863 if (isa<MDString>(N.get()) &&
1864 cast<MDString>(N.get())->getString() == Name)
1865 return;
1866 Names.push_back(N.get());
1867 }
1868 }
1869
1870 MDBuilder MDB(getContext());
1871 Names.push_back(MDB.createString(Name));
1872 MDNode *MD = MDTuple::get(getContext(), Names);
1873 setMetadata(LLVMContext::MD_annotation, MD);
1874}
1875
1877 AAMDNodes Result;
1879 unsigned Idx = MetadataIndex;
1880 const auto &Metadatas = getContext().pImpl->Metadatas;
1881 while (Idx) {
1882 const MDAttachment &A = Metadatas[Idx];
1883 switch (A.MDKind) {
1884 case LLVMContext::MD_tbaa:
1885 Result.TBAA = A.Node;
1886 break;
1887 case LLVMContext::MD_tbaa_struct:
1888 Result.TBAAStruct = A.Node;
1889 break;
1890 case LLVMContext::MD_alias_scope:
1891 Result.Scope = A.Node;
1892 break;
1893 case LLVMContext::MD_noalias:
1894 Result.NoAlias = A.Node;
1895 break;
1896 case LLVMContext::MD_noalias_addrspace:
1897 Result.NoAliasAddrSpace = A.Node;
1898 break;
1899 }
1900 Idx = A.Next;
1901 }
1902 }
1903 return Result;
1904}
1905
1907 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1908 setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
1909 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1910 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1911 setMetadata(LLVMContext::MD_noalias_addrspace, N.NoAliasAddrSpace);
1912}
1913
1915 setMetadata(llvm::LLVMContext::MD_nosanitize,
1917}
1918
1919void Instruction::getAllMetadataImpl(
1920 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1921 Result.clear();
1922
1923 // Handle 'dbg' as a special case since it is not stored in the hash table.
1924 if (DbgLoc) {
1925 Result.push_back(
1926 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1927 }
1928 Value::getAllMetadata(Result);
1929}
1930
1931bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
1932 assert((getOpcode() == Instruction::CondBr ||
1933 getOpcode() == Instruction::Select ||
1934 getOpcode() == Instruction::Call ||
1935 getOpcode() == Instruction::Invoke ||
1936 getOpcode() == Instruction::IndirectBr ||
1937 getOpcode() == Instruction::Switch) &&
1938 "Looking for branch weights on something besides branch");
1939
1940 return ::extractProfTotalWeight(*this, TotalVal);
1941}
1942
1945 Other->getAllMetadata(MDs);
1946 for (auto &MD : MDs) {
1947 // We need to adjust the type metadata offset.
1948 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1949 auto *OffsetConst = cast<ConstantInt>(
1950 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1951 Metadata *TypeId = MD.second->getOperand(1);
1952 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1953 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1954 addMetadata(LLVMContext::MD_type,
1955 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1956 continue;
1957 }
1958 // If an offset adjustment was specified we need to modify the DIExpression
1959 // to prepend the adjustment:
1960 // !DIExpression(DW_OP_plus, Offset, [original expr])
1961 auto *Attachment = MD.second;
1962 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1964 DIExpression *E = nullptr;
1965 if (!GV) {
1966 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1967 GV = GVE->getVariable();
1968 E = GVE->getExpression();
1969 }
1970 ArrayRef<uint64_t> OrigElements;
1971 if (E)
1972 OrigElements = E->getElements();
1973 std::vector<uint64_t> Elements(OrigElements.size() + 2);
1974 Elements[0] = dwarf::DW_OP_plus_uconst;
1975 Elements[1] = Offset;
1976 llvm::copy(OrigElements, Elements.begin() + 2);
1977 E = DIExpression::get(getContext(), Elements);
1978 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1979 }
1980 addMetadata(MD.first, *Attachment);
1981 }
1982}
1983
1986 LLVMContext::MD_type,
1988 {ConstantAsMetadata::get(ConstantInt::get(
1990 TypeID}));
1991}
1992
1994 // Remove any existing vcall visibility metadata first in case we are
1995 // updating.
1996 eraseMetadata(LLVMContext::MD_vcall_visibility);
1997 addMetadata(LLVMContext::MD_vcall_visibility,
1999 {ConstantAsMetadata::get(ConstantInt::get(
2001}
2002
2004 if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
2005 uint64_t Val = cast<ConstantInt>(
2006 cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
2007 ->getZExtValue();
2008 assert(Val <= 2 && "unknown vcall visibility!");
2009 return (VCallVisibility)Val;
2010 }
2012}
2013
2015 setMetadata(LLVMContext::MD_dbg, SP);
2016}
2017
2019 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
2020}
2021
2023 if (DISubprogram *SP = getSubprogram()) {
2024 if (DICompileUnit *CU = SP->getUnit()) {
2025 return CU->getDebugInfoForProfiling();
2026 }
2027 }
2028 return false;
2029}
2030
2032 addMetadata(LLVMContext::MD_dbg, *GV);
2033}
2034
2038 getMetadata(LLVMContext::MD_dbg, MDs);
2039 for (MDNode *MD : MDs)
2041}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Domain getDomain(const ConstantRange &CR)
dxil translate DXIL Translate Metadata
static ManagedStatic< DebugCounterOwner > Owner
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
static DISubprogram * getLocalFunctionMetadata(Value *V)
Definition Metadata.cpp:489
static Metadata * canonicalizeMetadataForValue(LLVMContext &Context, Metadata *MD)
Canonicalize metadata arguments to intrinsics.
Definition Metadata.cpp:85
static bool isOperandUnresolved(Metadata *Op)
Definition Metadata.cpp:769
static bool hasSelfReference(MDNode *N)
Definition Metadata.cpp:881
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
static SmallVector< TrackingMDRef, 4 > & getNMDOps(void *Operands)
static bool canBeMerged(const ConstantRange &A, const ConstantRange &B)
static T * uniquifyImpl(T *N, DenseSet< T *, InfoT > &Store)
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
static MDNode * getOrSelfReference(LLVMContext &Context, ArrayRef< Metadata * > Ops)
Get a node or a self-reference that looks like it.
static bool tryMergeRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
This file contains the declarations for profiling metadata utility functions.
Remove Loads Into Fake Uses
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition APInt.h:78
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition Metadata.h:1591
Annotations lets you mark points and ranges inside source code, for tests:
Definition Annotations.h:67
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
This class represents a function call, abstracting a target machine's calling convention.
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
This is the shared class of boolean and integer constants.
Definition Constants.h:87
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:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a list of constant ranges.
LLVM_ABI ConstantRangeList intersectWith(const ConstantRangeList &CRL) const
Return the range list that results from the intersection of this ConstantRangeList with another Const...
This class represents a range of values.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
This is an important base class in LLVM.
Definition Constant.h:43
DWARF expression.
A pair of DIGlobalVariable and DIExpression.
Subprogram description. Uses SubclassData1.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition DebugLoc.cpp:76
Base class for tracking ValueAsMetadata/DIArgLists with user lookups and Owner callbacks outside of V...
Definition Metadata.h:221
LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue)
To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where Old is a pointer to one of the poi...
Definition Metadata.cpp:162
std::array< Metadata *, 3 > DebugValues
Definition Metadata.h:227
void resetDebugValue(size_t Idx, Metadata *DebugValue)
Definition Metadata.h:282
LLVM_ABI DbgVariableRecord * getUser()
Definition Metadata.cpp:155
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool shouldEmitDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
LLVM_ABI void addTypeMetadata(unsigned Offset, Metadata *TypeID)
unsigned MetadataIndex
Index of first metadata attachment in context, or zero.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
GlobalObject(Type *Ty, ValueTy VTy, AllocInfo AllocInfo, LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace=0)
LLVM_ABI void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
LLVM_ABI VCallVisibility getVCallVisibility() const
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
LLVM_ABI void setVCallVisibilityMetadata(VCallVisibility Visibility)
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
bool hasMetadataOtherThanDebugLoc() const
Return true if this instruction has metadata attached to it other than a debug location.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void addAnnotationMetadata(StringRef Annotation)
Adds an !annotation metadata node with Annotation to this instruction.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void setNoSanitizeMetadata()
Sets the nosanitize metadata on this instruction.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void eraseMetadataIf(function_ref< bool(unsigned, MDNode *)> Pred)
Erase all metadata that matches the predicate.
DenseMap< Metadata *, MetadataAsValue * > MetadataAsValues
SmallVector< MDAttachment, 0 > Metadatas
Collection of metadata attachments in this context.
DenseMap< DIAssignID *, SmallVector< Instruction *, 1 > > AssignmentIDToInstrs
Map DIAssignID -> Instructions with that attachment.
std::vector< MDNode * > DistinctMDNodes
DenseSet< MDNode * > TemporaryMDNodes
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
LLVMContextImpl *const pImpl
Definition LLVMContext.h:70
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition MDBuilder.cpp:21
Metadata node.
Definition Metadata.h:1069
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
LLVM_ABI void resolveCycles()
Resolve cycles.
Definition Metadata.cpp:861
static LLVM_ABI CaptureComponents toCaptureComponents(const MDNode *MD)
Convert !captures metadata to CaptureComponents. MD may be nullptr.
mutable_op_range mutable_operands()
Definition Metadata.h:1207
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition Metadata.h:1266
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
static LLVM_ABI void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
LLVM_ABI void resolve()
Resolve a unique, unresolved node.
Definition Metadata.cpp:815
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
LLVM_ABI void storeDistinctInContext()
bool isTemporary() const
Definition Metadata.h:1253
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1424
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
bool isUniqued() const
Definition Metadata.h:1251
static LLVM_ABI MDNode * getMergedAllocTokenMetadata(const MDNode *A, const MDNode *B)
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
void setNumUnresolved(unsigned N)
Definition Metadata.h:1353
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
MDOperand * mutable_begin()
Definition Metadata.h:1202
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:665
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition Metadata.cpp:684
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
bool isDistinct() const
Definition Metadata.h:1252
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1249
op_iterator op_begin() const
Definition Metadata.h:1416
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericNoFPClass(MDNode *A, MDNode *B)
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
LLVMContext & getContext() const
Definition Metadata.h:1233
static LLVM_ABI MDNode * fromCaptureComponents(LLVMContext &Ctx, CaptureComponents CC)
Convert CaptureComponents to !captures metadata.
LLVM_ABI void dropAllReferences()
Definition Metadata.cpp:927
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
unsigned getNumUnresolved() const
Definition Metadata.h:1351
Tracking metadata reference owned by Metadata.
Definition Metadata.h:891
A single uniqued string.
Definition Metadata.h:722
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:629
static LLVM_ABI MDString * getIfExists(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:621
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:611
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1513
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:107
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:115
LLVM_ABI ~MetadataAsValue()
Definition Metadata.cpp:69
static LLVM_ABI bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition Metadata.cpp:250
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition Metadata.h:358
PointerUnion< MetadataAsValue *, Metadata *, DebugValueUser * > OwnerTy
Definition Metadata.h:377
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition Metadata.h:369
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition Metadata.h:324
Root of the metadata hierarchy.
Definition Metadata.h:64
StorageType
Active type of storage.
Definition Metadata.h:72
unsigned char Storage
Storage flag for non-uniqued, otherwise unowned, metadata.
Definition Metadata.h:75
unsigned getMetadataID() const
Definition Metadata.h:104
Metadata(unsigned ID, StorageType Storage)
Definition Metadata.h:88
void eraseNamedMetadata(NamedMDNode *NMD)
Remove the given NamedMDNode from this module and delete it.
Definition Module.cpp:322
iterator end() const
Definition ArrayRef.h:339
LLVM_ABI void setOperand(unsigned I, MDNode *New)
LLVM_ABI ~NamedMDNode()
LLVM_ABI StringRef getName() const
void dropAllReferences()
Remove all uses and clear node vector.
Definition Metadata.h:1820
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI unsigned getNumOperands() const
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
Module * getParent()
Get the module that holds this named metadata collection.
Definition Metadata.h:1825
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Shared implementation of use-lists for replaceable metadata.
Definition Metadata.h:391
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:335
LLVM_ABI void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition Metadata.cpp:372
LLVM_ABI SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Returns the list of all DbgVariableRecord users of this.
Definition Metadata.cpp:276
LLVM_ABI void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition Metadata.cpp:425
LLVM_ABI SmallVector< Metadata * > getAllArgListUsers()
Returns the list of all DIArgList users of this.
Definition Metadata.cpp:254
MetadataTracking::OwnerTy OwnerTy
Definition Metadata.h:395
ArrayRef< value_type > getArrayRef() const
Definition SetVector.h:91
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
Definition SetVector.h:236
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
Definition Type.cpp:278
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
Use & Op()
Definition User.h:171
Value wrapper in the Metadata hierarchy.
Definition Metadata.h:459
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition Metadata.h:519
static LLVM_ABI void handleDeletion(Value *V)
Definition Metadata.cpp:530
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:506
static LLVM_ABI ValueAsMetadata * getIfExists(Value *V)
Definition Metadata.cpp:525
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition Metadata.cpp:549
ValueAsMetadata(unsigned ID, Value *V)
Definition Metadata.h:471
Value * getValue() const
Definition Metadata.h:499
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
unsigned IsUsedByMD
Definition Value.h:112
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
LLVM_ABI MDNode * getMetadataImpl(unsigned KindID) const LLVM_READONLY
Get metadata for the given kind, if any.
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI MDNode * getMetadata(StringRef Kind) const LLVM_READONLY
Get the current metadata attachments for the given kind, if any.
LLVM_ABI void eraseMetadataIf(function_ref< bool(unsigned, MDNode *)> Pred)
Erase all metadata attachments matching the given predicate.
LLVM_ABI void clearMetadata()
Erase all metadata attached to this Value.
An efficient, type-erasing, non-owning reference to a callable.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:709
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
iterator end() const
Definition BasicBlock.h:89
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
bool capturesReadProvenanceOnly(CaptureComponents CC)
Definition ModRef.h:391
void stable_sort(R &&Range)
Definition STLExtras.h:2116
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
bool capturesAddressIsNullOnly(CaptureComponents CC)
Definition ModRef.h:383
TypedTrackingMDRef< MDNode > TrackingMDNodeRef
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
static T * getUniqued(DenseSet< T *, InfoT > &Store, const typename InfoT::KeyTy &Key)
bool capturesAddress(CaptureComponents CC)
Definition ModRef.h:387
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
bool capturesFullProvenance(CaptureComponents CC)
Definition ModRef.h:396
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool capturesAll(CaptureComponents CC)
Definition ModRef.h:404
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:604
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
#define N
static constexpr bool value
static std::false_type check(...)
static std::true_type check(SameType< void(U::*)(unsigned), &U::setHash > *)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
Single metadata attachment, forms linked list ended by index 0.
static LLVM_ABI const char * BranchWeights
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1439