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