Path: blob/main/contrib/llvm-project/llvm/lib/IR/Metadata.cpp
35233 views
//===- Metadata.cpp - Implement Metadata classes --------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Metadata classes.9//10//===----------------------------------------------------------------------===//1112#include "llvm/IR/Metadata.h"13#include "LLVMContextImpl.h"14#include "MetadataImpl.h"15#include "llvm/ADT/APFloat.h"16#include "llvm/ADT/APInt.h"17#include "llvm/ADT/ArrayRef.h"18#include "llvm/ADT/DenseSet.h"19#include "llvm/ADT/STLExtras.h"20#include "llvm/ADT/SetVector.h"21#include "llvm/ADT/SmallPtrSet.h"22#include "llvm/ADT/SmallSet.h"23#include "llvm/ADT/SmallVector.h"24#include "llvm/ADT/StringMap.h"25#include "llvm/ADT/StringRef.h"26#include "llvm/ADT/Twine.h"27#include "llvm/IR/Argument.h"28#include "llvm/IR/BasicBlock.h"29#include "llvm/IR/Constant.h"30#include "llvm/IR/ConstantRange.h"31#include "llvm/IR/Constants.h"32#include "llvm/IR/DebugInfoMetadata.h"33#include "llvm/IR/DebugLoc.h"34#include "llvm/IR/DebugProgramInstruction.h"35#include "llvm/IR/Function.h"36#include "llvm/IR/GlobalObject.h"37#include "llvm/IR/GlobalVariable.h"38#include "llvm/IR/Instruction.h"39#include "llvm/IR/LLVMContext.h"40#include "llvm/IR/MDBuilder.h"41#include "llvm/IR/Module.h"42#include "llvm/IR/ProfDataUtils.h"43#include "llvm/IR/TrackingMDRef.h"44#include "llvm/IR/Type.h"45#include "llvm/IR/Value.h"46#include "llvm/Support/Casting.h"47#include "llvm/Support/ErrorHandling.h"48#include "llvm/Support/MathExtras.h"49#include <algorithm>50#include <cassert>51#include <cstddef>52#include <cstdint>53#include <type_traits>54#include <utility>55#include <vector>5657using namespace llvm;5859MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)60: Value(Ty, MetadataAsValueVal), MD(MD) {61track();62}6364MetadataAsValue::~MetadataAsValue() {65getType()->getContext().pImpl->MetadataAsValues.erase(MD);66untrack();67}6869/// Canonicalize metadata arguments to intrinsics.70///71/// To support bitcode upgrades (and assembly semantic sugar) for \a72/// MetadataAsValue, we need to canonicalize certain metadata.73///74/// - nullptr is replaced by an empty MDNode.75/// - An MDNode with a single null operand is replaced by an empty MDNode.76/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.77///78/// This maintains readability of bitcode from when metadata was a type of79/// value, and these bridges were unnecessary.80static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,81Metadata *MD) {82if (!MD)83// !{}84return MDNode::get(Context, std::nullopt);8586// Return early if this isn't a single-operand MDNode.87auto *N = dyn_cast<MDNode>(MD);88if (!N || N->getNumOperands() != 1)89return MD;9091if (!N->getOperand(0))92// !{}93return MDNode::get(Context, std::nullopt);9495if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))96// Look through the MDNode.97return C;9899return MD;100}101102MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {103MD = canonicalizeMetadataForValue(Context, MD);104auto *&Entry = Context.pImpl->MetadataAsValues[MD];105if (!Entry)106Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);107return Entry;108}109110MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,111Metadata *MD) {112MD = canonicalizeMetadataForValue(Context, MD);113auto &Store = Context.pImpl->MetadataAsValues;114return Store.lookup(MD);115}116117void MetadataAsValue::handleChangedMetadata(Metadata *MD) {118LLVMContext &Context = getContext();119MD = canonicalizeMetadataForValue(Context, MD);120auto &Store = Context.pImpl->MetadataAsValues;121122// Stop tracking the old metadata.123Store.erase(this->MD);124untrack();125this->MD = nullptr;126127// Start tracking MD, or RAUW if necessary.128auto *&Entry = Store[MD];129if (Entry) {130replaceAllUsesWith(Entry);131delete this;132return;133}134135this->MD = MD;136track();137Entry = this;138}139140void MetadataAsValue::track() {141if (MD)142MetadataTracking::track(&MD, *MD, *this);143}144145void MetadataAsValue::untrack() {146if (MD)147MetadataTracking::untrack(MD);148}149150DbgVariableRecord *DebugValueUser::getUser() {151return static_cast<DbgVariableRecord *>(this);152}153const DbgVariableRecord *DebugValueUser::getUser() const {154return static_cast<const DbgVariableRecord *>(this);155}156157void DebugValueUser::handleChangedValue(void *Old, Metadata *New) {158// NOTE: We could inform the "owner" that a value has changed through159// getOwner, if needed.160auto OldMD = static_cast<Metadata **>(Old);161ptrdiff_t Idx = std::distance(&*DebugValues.begin(), OldMD);162// If replacing a ValueAsMetadata with a nullptr, replace it with a163// PoisonValue instead.164if (OldMD && isa<ValueAsMetadata>(*OldMD) && !New) {165auto *OldVAM = cast<ValueAsMetadata>(*OldMD);166New = ValueAsMetadata::get(PoisonValue::get(OldVAM->getValue()->getType()));167}168resetDebugValue(Idx, New);169}170171void DebugValueUser::trackDebugValue(size_t Idx) {172assert(Idx < 3 && "Invalid debug value index.");173Metadata *&MD = DebugValues[Idx];174if (MD)175MetadataTracking::track(&MD, *MD, *this);176}177178void DebugValueUser::trackDebugValues() {179for (Metadata *&MD : DebugValues)180if (MD)181MetadataTracking::track(&MD, *MD, *this);182}183184void DebugValueUser::untrackDebugValue(size_t Idx) {185assert(Idx < 3 && "Invalid debug value index.");186Metadata *&MD = DebugValues[Idx];187if (MD)188MetadataTracking::untrack(MD);189}190191void DebugValueUser::untrackDebugValues() {192for (Metadata *&MD : DebugValues)193if (MD)194MetadataTracking::untrack(MD);195}196197void DebugValueUser::retrackDebugValues(DebugValueUser &X) {198assert(DebugValueUser::operator==(X) && "Expected values to match");199for (const auto &[MD, XMD] : zip(DebugValues, X.DebugValues))200if (XMD)201MetadataTracking::retrack(XMD, MD);202X.DebugValues.fill(nullptr);203}204205bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {206assert(Ref && "Expected live reference");207assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&208"Reference without owner must be direct");209if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {210R->addRef(Ref, Owner);211return true;212}213if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {214assert(!PH->Use && "Placeholders can only be used once");215assert(!Owner && "Unexpected callback to owner");216PH->Use = static_cast<Metadata **>(Ref);217return true;218}219return false;220}221222void MetadataTracking::untrack(void *Ref, Metadata &MD) {223assert(Ref && "Expected live reference");224if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))225R->dropRef(Ref);226else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))227PH->Use = nullptr;228}229230bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {231assert(Ref && "Expected live reference");232assert(New && "Expected live reference");233assert(Ref != New && "Expected change");234if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {235R->moveRef(Ref, New, MD);236return true;237}238assert(!isa<DistinctMDOperandPlaceholder>(MD) &&239"Unexpected move of an MDOperand");240assert(!isReplaceable(MD) &&241"Expected un-replaceable metadata, since we didn't move a reference");242return false;243}244245bool MetadataTracking::isReplaceable(const Metadata &MD) {246return ReplaceableMetadataImpl::isReplaceable(MD);247}248249SmallVector<Metadata *> ReplaceableMetadataImpl::getAllArgListUsers() {250SmallVector<std::pair<OwnerTy, uint64_t> *> MDUsersWithID;251for (auto Pair : UseMap) {252OwnerTy Owner = Pair.second.first;253if (Owner.isNull())254continue;255if (!isa<Metadata *>(Owner))256continue;257Metadata *OwnerMD = cast<Metadata *>(Owner);258if (OwnerMD->getMetadataID() == Metadata::DIArgListKind)259MDUsersWithID.push_back(&UseMap[Pair.first]);260}261llvm::sort(MDUsersWithID, [](auto UserA, auto UserB) {262return UserA->second < UserB->second;263});264SmallVector<Metadata *> MDUsers;265for (auto *UserWithID : MDUsersWithID)266MDUsers.push_back(cast<Metadata *>(UserWithID->first));267return MDUsers;268}269270SmallVector<DbgVariableRecord *>271ReplaceableMetadataImpl::getAllDbgVariableRecordUsers() {272SmallVector<std::pair<OwnerTy, uint64_t> *> DVRUsersWithID;273for (auto Pair : UseMap) {274OwnerTy Owner = Pair.second.first;275if (Owner.isNull())276continue;277if (!Owner.is<DebugValueUser *>())278continue;279DVRUsersWithID.push_back(&UseMap[Pair.first]);280}281// Order DbgVariableRecord users in reverse-creation order. Normal dbg.value282// users of MetadataAsValues are ordered by their UseList, i.e. reverse order283// of when they were added: we need to replicate that here. The structure of284// debug-info output depends on the ordering of intrinsics, thus we need285// to keep them consistent for comparisons sake.286llvm::sort(DVRUsersWithID, [](auto UserA, auto UserB) {287return UserA->second > UserB->second;288});289SmallVector<DbgVariableRecord *> DVRUsers;290for (auto UserWithID : DVRUsersWithID)291DVRUsers.push_back(UserWithID->first.get<DebugValueUser *>()->getUser());292return DVRUsers;293}294295void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {296bool WasInserted =297UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))298.second;299(void)WasInserted;300assert(WasInserted && "Expected to add a reference");301302++NextIndex;303assert(NextIndex != 0 && "Unexpected overflow");304}305306void ReplaceableMetadataImpl::dropRef(void *Ref) {307bool WasErased = UseMap.erase(Ref);308(void)WasErased;309assert(WasErased && "Expected to drop a reference");310}311312void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,313const Metadata &MD) {314auto I = UseMap.find(Ref);315assert(I != UseMap.end() && "Expected to move a reference");316auto OwnerAndIndex = I->second;317UseMap.erase(I);318bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;319(void)WasInserted;320assert(WasInserted && "Expected to add a reference");321322// Check that the references are direct if there's no owner.323(void)MD;324assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&325"Reference without owner must be direct");326assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&327"Reference without owner must be direct");328}329330void ReplaceableMetadataImpl::SalvageDebugInfo(const Constant &C) {331if (!C.isUsedByMetadata()) {332return;333}334335LLVMContext &Context = C.getType()->getContext();336auto &Store = Context.pImpl->ValuesAsMetadata;337auto I = Store.find(&C);338ValueAsMetadata *MD = I->second;339using UseTy =340std::pair<void *, std::pair<MetadataTracking::OwnerTy, uint64_t>>;341// Copy out uses and update value of Constant used by debug info metadata with undef below342SmallVector<UseTy, 8> Uses(MD->UseMap.begin(), MD->UseMap.end());343344for (const auto &Pair : Uses) {345MetadataTracking::OwnerTy Owner = Pair.second.first;346if (!Owner)347continue;348if (!isa<Metadata *>(Owner))349continue;350auto *OwnerMD = dyn_cast_if_present<MDNode>(cast<Metadata *>(Owner));351if (!OwnerMD)352continue;353if (isa<DINode>(OwnerMD)) {354OwnerMD->handleChangedOperand(355Pair.first, ValueAsMetadata::get(UndefValue::get(C.getType())));356}357}358}359360void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {361if (UseMap.empty())362return;363364// Copy out uses since UseMap will get touched below.365using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;366SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());367llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {368return L.second.second < R.second.second;369});370for (const auto &Pair : Uses) {371// Check that this Ref hasn't disappeared after RAUW (when updating a372// previous Ref).373if (!UseMap.count(Pair.first))374continue;375376OwnerTy Owner = Pair.second.first;377if (!Owner) {378// Update unowned tracking references directly.379Metadata *&Ref = *static_cast<Metadata **>(Pair.first);380Ref = MD;381if (MD)382MetadataTracking::track(Ref);383UseMap.erase(Pair.first);384continue;385}386387// Check for MetadataAsValue.388if (isa<MetadataAsValue *>(Owner)) {389cast<MetadataAsValue *>(Owner)->handleChangedMetadata(MD);390continue;391}392393if (Owner.is<DebugValueUser *>()) {394Owner.get<DebugValueUser *>()->handleChangedValue(Pair.first, MD);395continue;396}397398// There's a Metadata owner -- dispatch.399Metadata *OwnerMD = cast<Metadata *>(Owner);400switch (OwnerMD->getMetadataID()) {401#define HANDLE_METADATA_LEAF(CLASS) \402case Metadata::CLASS##Kind: \403cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \404continue;405#include "llvm/IR/Metadata.def"406default:407llvm_unreachable("Invalid metadata subclass");408}409}410assert(UseMap.empty() && "Expected all uses to be replaced");411}412413void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {414if (UseMap.empty())415return;416417if (!ResolveUsers) {418UseMap.clear();419return;420}421422// Copy out uses since UseMap could get touched below.423using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;424SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());425llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {426return L.second.second < R.second.second;427});428UseMap.clear();429for (const auto &Pair : Uses) {430auto Owner = Pair.second.first;431if (!Owner)432continue;433if (!Owner.is<Metadata *>())434continue;435436// Resolve MDNodes that point at this.437auto *OwnerMD = dyn_cast_if_present<MDNode>(cast<Metadata *>(Owner));438if (!OwnerMD)439continue;440if (OwnerMD->isResolved())441continue;442OwnerMD->decrementUnresolvedOperandCount();443}444}445446// Special handing of DIArgList is required in the RemoveDIs project, see447// commentry in DIArgList::handleChangedOperand for details. Hidden behind448// conditional compilation to avoid a compile time regression.449ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {450if (auto *N = dyn_cast<MDNode>(&MD)) {451return !N->isResolved() || N->isAlwaysReplaceable()452? N->Context.getOrCreateReplaceableUses()453: nullptr;454}455if (auto ArgList = dyn_cast<DIArgList>(&MD))456return ArgList;457return dyn_cast<ValueAsMetadata>(&MD);458}459460ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {461if (auto *N = dyn_cast<MDNode>(&MD)) {462return !N->isResolved() || N->isAlwaysReplaceable()463? N->Context.getReplaceableUses()464: nullptr;465}466if (auto ArgList = dyn_cast<DIArgList>(&MD))467return ArgList;468return dyn_cast<ValueAsMetadata>(&MD);469}470471bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {472if (auto *N = dyn_cast<MDNode>(&MD))473return !N->isResolved() || N->isAlwaysReplaceable();474return isa<ValueAsMetadata>(&MD) || isa<DIArgList>(&MD);475}476477static DISubprogram *getLocalFunctionMetadata(Value *V) {478assert(V && "Expected value");479if (auto *A = dyn_cast<Argument>(V)) {480if (auto *Fn = A->getParent())481return Fn->getSubprogram();482return nullptr;483}484485if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {486if (auto *Fn = BB->getParent())487return Fn->getSubprogram();488return nullptr;489}490491return nullptr;492}493494ValueAsMetadata *ValueAsMetadata::get(Value *V) {495assert(V && "Unexpected null Value");496497auto &Context = V->getContext();498auto *&Entry = Context.pImpl->ValuesAsMetadata[V];499if (!Entry) {500assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&501"Expected constant or function-local value");502assert(!V->IsUsedByMD && "Expected this to be the only metadata use");503V->IsUsedByMD = true;504if (auto *C = dyn_cast<Constant>(V))505Entry = new ConstantAsMetadata(C);506else507Entry = new LocalAsMetadata(V);508}509510return Entry;511}512513ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {514assert(V && "Unexpected null Value");515return V->getContext().pImpl->ValuesAsMetadata.lookup(V);516}517518void ValueAsMetadata::handleDeletion(Value *V) {519assert(V && "Expected valid value");520521auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;522auto I = Store.find(V);523if (I == Store.end())524return;525526// Remove old entry from the map.527ValueAsMetadata *MD = I->second;528assert(MD && "Expected valid metadata");529assert(MD->getValue() == V && "Expected valid mapping");530Store.erase(I);531532// Delete the metadata.533MD->replaceAllUsesWith(nullptr);534delete MD;535}536537void ValueAsMetadata::handleRAUW(Value *From, Value *To) {538assert(From && "Expected valid value");539assert(To && "Expected valid value");540assert(From != To && "Expected changed value");541assert(&From->getContext() == &To->getContext() && "Expected same context");542543LLVMContext &Context = From->getType()->getContext();544auto &Store = Context.pImpl->ValuesAsMetadata;545auto I = Store.find(From);546if (I == Store.end()) {547assert(!From->IsUsedByMD && "Expected From not to be used by metadata");548return;549}550551// Remove old entry from the map.552assert(From->IsUsedByMD && "Expected From to be used by metadata");553From->IsUsedByMD = false;554ValueAsMetadata *MD = I->second;555assert(MD && "Expected valid metadata");556assert(MD->getValue() == From && "Expected valid mapping");557Store.erase(I);558559if (isa<LocalAsMetadata>(MD)) {560if (auto *C = dyn_cast<Constant>(To)) {561// Local became a constant.562MD->replaceAllUsesWith(ConstantAsMetadata::get(C));563delete MD;564return;565}566if (getLocalFunctionMetadata(From) && getLocalFunctionMetadata(To) &&567getLocalFunctionMetadata(From) != getLocalFunctionMetadata(To)) {568// DISubprogram changed.569MD->replaceAllUsesWith(nullptr);570delete MD;571return;572}573} else if (!isa<Constant>(To)) {574// Changed to function-local value.575MD->replaceAllUsesWith(nullptr);576delete MD;577return;578}579580auto *&Entry = Store[To];581if (Entry) {582// The target already exists.583MD->replaceAllUsesWith(Entry);584delete MD;585return;586}587588// Update MD in place (and update the map entry).589assert(!To->IsUsedByMD && "Expected this to be the only metadata use");590To->IsUsedByMD = true;591MD->V = To;592Entry = MD;593}594595//===----------------------------------------------------------------------===//596// MDString implementation.597//598599MDString *MDString::get(LLVMContext &Context, StringRef Str) {600auto &Store = Context.pImpl->MDStringCache;601auto I = Store.try_emplace(Str);602auto &MapEntry = I.first->getValue();603if (!I.second)604return &MapEntry;605MapEntry.Entry = &*I.first;606return &MapEntry;607}608609StringRef MDString::getString() const {610assert(Entry && "Expected to find string map entry");611return Entry->first();612}613614//===----------------------------------------------------------------------===//615// MDNode implementation.616//617618// Assert that the MDNode types will not be unaligned by the objects619// prepended to them.620#define HANDLE_MDNODE_LEAF(CLASS) \621static_assert( \622alignof(uint64_t) >= alignof(CLASS), \623"Alignment is insufficient after objects prepended to " #CLASS);624#include "llvm/IR/Metadata.def"625626void *MDNode::operator new(size_t Size, size_t NumOps, StorageType Storage) {627// uint64_t is the most aligned type we need support (ensured by static_assert628// above)629size_t AllocSize =630alignTo(Header::getAllocSize(Storage, NumOps), alignof(uint64_t));631char *Mem = reinterpret_cast<char *>(::operator new(AllocSize + Size));632Header *H = new (Mem + AllocSize - sizeof(Header)) Header(NumOps, Storage);633return reinterpret_cast<void *>(H + 1);634}635636void MDNode::operator delete(void *N) {637Header *H = reinterpret_cast<Header *>(N) - 1;638void *Mem = H->getAllocation();639H->~Header();640::operator delete(Mem);641}642643MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,644ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)645: Metadata(ID, Storage), Context(Context) {646unsigned Op = 0;647for (Metadata *MD : Ops1)648setOperand(Op++, MD);649for (Metadata *MD : Ops2)650setOperand(Op++, MD);651652if (!isUniqued())653return;654655// Count the unresolved operands. If there are any, RAUW support will be656// added lazily on first reference.657countUnresolvedOperands();658}659660TempMDNode MDNode::clone() const {661switch (getMetadataID()) {662default:663llvm_unreachable("Invalid MDNode subclass");664#define HANDLE_MDNODE_LEAF(CLASS) \665case CLASS##Kind: \666return cast<CLASS>(this)->cloneImpl();667#include "llvm/IR/Metadata.def"668}669}670671MDNode::Header::Header(size_t NumOps, StorageType Storage) {672IsLarge = isLarge(NumOps);673IsResizable = isResizable(Storage);674SmallSize = getSmallSize(NumOps, IsResizable, IsLarge);675if (IsLarge) {676SmallNumOps = 0;677new (getLargePtr()) LargeStorageVector();678getLarge().resize(NumOps);679return;680}681SmallNumOps = NumOps;682MDOperand *O = reinterpret_cast<MDOperand *>(this) - SmallSize;683for (MDOperand *E = O + SmallSize; O != E;)684(void)new (O++) MDOperand();685}686687MDNode::Header::~Header() {688if (IsLarge) {689getLarge().~LargeStorageVector();690return;691}692MDOperand *O = reinterpret_cast<MDOperand *>(this);693for (MDOperand *E = O - SmallSize; O != E; --O)694(void)(O - 1)->~MDOperand();695}696697void *MDNode::Header::getSmallPtr() {698static_assert(alignof(MDOperand) <= alignof(Header),699"MDOperand too strongly aligned");700return reinterpret_cast<char *>(const_cast<Header *>(this)) -701sizeof(MDOperand) * SmallSize;702}703704void MDNode::Header::resize(size_t NumOps) {705assert(IsResizable && "Node is not resizable");706if (operands().size() == NumOps)707return;708709if (IsLarge)710getLarge().resize(NumOps);711else if (NumOps <= SmallSize)712resizeSmall(NumOps);713else714resizeSmallToLarge(NumOps);715}716717void MDNode::Header::resizeSmall(size_t NumOps) {718assert(!IsLarge && "Expected a small MDNode");719assert(NumOps <= SmallSize && "NumOps too large for small resize");720721MutableArrayRef<MDOperand> ExistingOps = operands();722assert(NumOps != ExistingOps.size() && "Expected a different size");723724int NumNew = (int)NumOps - (int)ExistingOps.size();725MDOperand *O = ExistingOps.end();726for (int I = 0, E = NumNew; I < E; ++I)727(O++)->reset();728for (int I = 0, E = NumNew; I > E; --I)729(--O)->reset();730SmallNumOps = NumOps;731assert(O == operands().end() && "Operands not (un)initialized until the end");732}733734void MDNode::Header::resizeSmallToLarge(size_t NumOps) {735assert(!IsLarge && "Expected a small MDNode");736assert(NumOps > SmallSize && "Expected NumOps to be larger than allocation");737LargeStorageVector NewOps;738NewOps.resize(NumOps);739llvm::move(operands(), NewOps.begin());740resizeSmall(0);741new (getLargePtr()) LargeStorageVector(std::move(NewOps));742IsLarge = true;743}744745static bool isOperandUnresolved(Metadata *Op) {746if (auto *N = dyn_cast_or_null<MDNode>(Op))747return !N->isResolved();748return false;749}750751void MDNode::countUnresolvedOperands() {752assert(getNumUnresolved() == 0 && "Expected unresolved ops to be uncounted");753assert(isUniqued() && "Expected this to be uniqued");754setNumUnresolved(count_if(operands(), isOperandUnresolved));755}756757void MDNode::makeUniqued() {758assert(isTemporary() && "Expected this to be temporary");759assert(!isResolved() && "Expected this to be unresolved");760761// Enable uniquing callbacks.762for (auto &Op : mutable_operands())763Op.reset(Op.get(), this);764765// Make this 'uniqued'.766Storage = Uniqued;767countUnresolvedOperands();768if (!getNumUnresolved()) {769dropReplaceableUses();770assert(isResolved() && "Expected this to be resolved");771}772773assert(isUniqued() && "Expected this to be uniqued");774}775776void MDNode::makeDistinct() {777assert(isTemporary() && "Expected this to be temporary");778assert(!isResolved() && "Expected this to be unresolved");779780// Drop RAUW support and store as a distinct node.781dropReplaceableUses();782storeDistinctInContext();783784assert(isDistinct() && "Expected this to be distinct");785assert(isResolved() && "Expected this to be resolved");786}787788void MDNode::resolve() {789assert(isUniqued() && "Expected this to be uniqued");790assert(!isResolved() && "Expected this to be unresolved");791792setNumUnresolved(0);793dropReplaceableUses();794795assert(isResolved() && "Expected this to be resolved");796}797798void MDNode::dropReplaceableUses() {799assert(!getNumUnresolved() && "Unexpected unresolved operand");800801// Drop any RAUW support.802if (Context.hasReplaceableUses())803Context.takeReplaceableUses()->resolveAllUses();804}805806void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {807assert(isUniqued() && "Expected this to be uniqued");808assert(getNumUnresolved() != 0 && "Expected unresolved operands");809810// Check if an operand was resolved.811if (!isOperandUnresolved(Old)) {812if (isOperandUnresolved(New))813// An operand was un-resolved!814setNumUnresolved(getNumUnresolved() + 1);815} else if (!isOperandUnresolved(New))816decrementUnresolvedOperandCount();817}818819void MDNode::decrementUnresolvedOperandCount() {820assert(!isResolved() && "Expected this to be unresolved");821if (isTemporary())822return;823824assert(isUniqued() && "Expected this to be uniqued");825setNumUnresolved(getNumUnresolved() - 1);826if (getNumUnresolved())827return;828829// Last unresolved operand has just been resolved.830dropReplaceableUses();831assert(isResolved() && "Expected this to become resolved");832}833834void MDNode::resolveCycles() {835if (isResolved())836return;837838// Resolve this node immediately.839resolve();840841// Resolve all operands.842for (const auto &Op : operands()) {843auto *N = dyn_cast_or_null<MDNode>(Op);844if (!N)845continue;846847assert(!N->isTemporary() &&848"Expected all forward declarations to be resolved");849if (!N->isResolved())850N->resolveCycles();851}852}853854static bool hasSelfReference(MDNode *N) {855return llvm::is_contained(N->operands(), N);856}857858MDNode *MDNode::replaceWithPermanentImpl() {859switch (getMetadataID()) {860default:861// If this type isn't uniquable, replace with a distinct node.862return replaceWithDistinctImpl();863864#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \865case CLASS##Kind: \866break;867#include "llvm/IR/Metadata.def"868}869870// Even if this type is uniquable, self-references have to be distinct.871if (hasSelfReference(this))872return replaceWithDistinctImpl();873return replaceWithUniquedImpl();874}875876MDNode *MDNode::replaceWithUniquedImpl() {877// Try to uniquify in place.878MDNode *UniquedNode = uniquify();879880if (UniquedNode == this) {881makeUniqued();882return this;883}884885// Collision, so RAUW instead.886replaceAllUsesWith(UniquedNode);887deleteAsSubclass();888return UniquedNode;889}890891MDNode *MDNode::replaceWithDistinctImpl() {892makeDistinct();893return this;894}895896void MDTuple::recalculateHash() {897setHash(MDTupleInfo::KeyTy::calculateHash(this));898}899900void MDNode::dropAllReferences() {901for (unsigned I = 0, E = getNumOperands(); I != E; ++I)902setOperand(I, nullptr);903if (Context.hasReplaceableUses()) {904Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);905(void)Context.takeReplaceableUses();906}907}908909void MDNode::handleChangedOperand(void *Ref, Metadata *New) {910unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();911assert(Op < getNumOperands() && "Expected valid operand");912913if (!isUniqued()) {914// This node is not uniqued. Just set the operand and be done with it.915setOperand(Op, New);916return;917}918919// This node is uniqued.920eraseFromStore();921922Metadata *Old = getOperand(Op);923setOperand(Op, New);924925// Drop uniquing for self-reference cycles and deleted constants.926if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {927if (!isResolved())928resolve();929storeDistinctInContext();930return;931}932933// Re-unique the node.934auto *Uniqued = uniquify();935if (Uniqued == this) {936if (!isResolved())937resolveAfterOperandChange(Old, New);938return;939}940941// Collision.942if (!isResolved()) {943// Still unresolved, so RAUW.944//945// First, clear out all operands to prevent any recursion (similar to946// dropAllReferences(), but we still need the use-list).947for (unsigned O = 0, E = getNumOperands(); O != E; ++O)948setOperand(O, nullptr);949if (Context.hasReplaceableUses())950Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);951deleteAsSubclass();952return;953}954955// Store in non-uniqued form if RAUW isn't possible.956storeDistinctInContext();957}958959void MDNode::deleteAsSubclass() {960switch (getMetadataID()) {961default:962llvm_unreachable("Invalid subclass of MDNode");963#define HANDLE_MDNODE_LEAF(CLASS) \964case CLASS##Kind: \965delete cast<CLASS>(this); \966break;967#include "llvm/IR/Metadata.def"968}969}970971template <class T, class InfoT>972static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {973if (T *U = getUniqued(Store, N))974return U;975976Store.insert(N);977return N;978}979980template <class NodeTy> struct MDNode::HasCachedHash {981using Yes = char[1];982using No = char[2];983template <class U, U Val> struct SFINAE {};984985template <class U>986static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);987template <class U> static No &check(...);988989static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);990};991992MDNode *MDNode::uniquify() {993assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");994995// Try to insert into uniquing store.996switch (getMetadataID()) {997default:998llvm_unreachable("Invalid or non-uniquable subclass of MDNode");999#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \1000case CLASS##Kind: { \1001CLASS *SubclassThis = cast<CLASS>(this); \1002std::integral_constant<bool, HasCachedHash<CLASS>::value> \1003ShouldRecalculateHash; \1004dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \1005return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \1006}1007#include "llvm/IR/Metadata.def"1008}1009}10101011void MDNode::eraseFromStore() {1012switch (getMetadataID()) {1013default:1014llvm_unreachable("Invalid or non-uniquable subclass of MDNode");1015#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \1016case CLASS##Kind: \1017getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \1018break;1019#include "llvm/IR/Metadata.def"1020}1021}10221023MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,1024StorageType Storage, bool ShouldCreate) {1025unsigned Hash = 0;1026if (Storage == Uniqued) {1027MDTupleInfo::KeyTy Key(MDs);1028if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))1029return N;1030if (!ShouldCreate)1031return nullptr;1032Hash = Key.getHash();1033} else {1034assert(ShouldCreate && "Expected non-uniqued nodes to always be created");1035}10361037return storeImpl(new (MDs.size(), Storage)1038MDTuple(Context, Storage, Hash, MDs),1039Storage, Context.pImpl->MDTuples);1040}10411042void MDNode::deleteTemporary(MDNode *N) {1043assert(N->isTemporary() && "Expected temporary node");1044N->replaceAllUsesWith(nullptr);1045N->deleteAsSubclass();1046}10471048void MDNode::storeDistinctInContext() {1049assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");1050assert(!getNumUnresolved() && "Unexpected unresolved nodes");1051Storage = Distinct;1052assert(isResolved() && "Expected this to be resolved");10531054// Reset the hash.1055switch (getMetadataID()) {1056default:1057llvm_unreachable("Invalid subclass of MDNode");1058#define HANDLE_MDNODE_LEAF(CLASS) \1059case CLASS##Kind: { \1060std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \1061dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \1062break; \1063}1064#include "llvm/IR/Metadata.def"1065}10661067getContext().pImpl->DistinctMDNodes.push_back(this);1068}10691070void MDNode::replaceOperandWith(unsigned I, Metadata *New) {1071if (getOperand(I) == New)1072return;10731074if (!isUniqued()) {1075setOperand(I, New);1076return;1077}10781079handleChangedOperand(mutable_begin() + I, New);1080}10811082void MDNode::setOperand(unsigned I, Metadata *New) {1083assert(I < getNumOperands());1084mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);1085}10861087/// Get a node or a self-reference that looks like it.1088///1089/// Special handling for finding self-references, for use by \a1090/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from1091/// when self-referencing nodes were still uniqued. If the first operand has1092/// the same operands as \c Ops, return the first operand instead.1093static MDNode *getOrSelfReference(LLVMContext &Context,1094ArrayRef<Metadata *> Ops) {1095if (!Ops.empty())1096if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))1097if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {1098for (unsigned I = 1, E = Ops.size(); I != E; ++I)1099if (Ops[I] != N->getOperand(I))1100return MDNode::get(Context, Ops);1101return N;1102}11031104return MDNode::get(Context, Ops);1105}11061107MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {1108if (!A)1109return B;1110if (!B)1111return A;11121113SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());1114MDs.insert(B->op_begin(), B->op_end());11151116// FIXME: This preserves long-standing behaviour, but is it really the right1117// behaviour? Or was that an unintended side-effect of node uniquing?1118return getOrSelfReference(A->getContext(), MDs.getArrayRef());1119}11201121MDNode *MDNode::intersect(MDNode *A, MDNode *B) {1122if (!A || !B)1123return nullptr;11241125SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());1126SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());1127MDs.remove_if([&](Metadata *MD) { return !BSet.count(MD); });11281129// FIXME: This preserves long-standing behaviour, but is it really the right1130// behaviour? Or was that an unintended side-effect of node uniquing?1131return getOrSelfReference(A->getContext(), MDs.getArrayRef());1132}11331134MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {1135if (!A || !B)1136return nullptr;11371138// Take the intersection of domains then union the scopes1139// within those domains1140SmallPtrSet<const MDNode *, 16> ADomains;1141SmallPtrSet<const MDNode *, 16> IntersectDomains;1142SmallSetVector<Metadata *, 4> MDs;1143for (const MDOperand &MDOp : A->operands())1144if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))1145if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())1146ADomains.insert(Domain);11471148for (const MDOperand &MDOp : B->operands())1149if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))1150if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())1151if (ADomains.contains(Domain)) {1152IntersectDomains.insert(Domain);1153MDs.insert(MDOp);1154}11551156for (const MDOperand &MDOp : A->operands())1157if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))1158if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())1159if (IntersectDomains.contains(Domain))1160MDs.insert(MDOp);11611162return MDs.empty() ? nullptr1163: getOrSelfReference(A->getContext(), MDs.getArrayRef());1164}11651166MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {1167if (!A || !B)1168return nullptr;11691170APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();1171APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();1172if (AVal < BVal)1173return A;1174return B;1175}11761177// Call instructions with branch weights are only used in SamplePGO as1178// documented in1179/// https://llvm.org/docs/BranchWeightMetadata.html#callinst).1180MDNode *MDNode::mergeDirectCallProfMetadata(MDNode *A, MDNode *B,1181const Instruction *AInstr,1182const Instruction *BInstr) {1183assert(A && B && AInstr && BInstr && "Caller should guarantee");1184auto &Ctx = AInstr->getContext();1185MDBuilder MDHelper(Ctx);11861187// LLVM IR verifier verifies !prof metadata has at least 2 operands.1188assert(A->getNumOperands() >= 2 && B->getNumOperands() >= 2 &&1189"!prof annotations should have no less than 2 operands");1190MDString *AMDS = dyn_cast<MDString>(A->getOperand(0));1191MDString *BMDS = dyn_cast<MDString>(B->getOperand(0));1192// LLVM IR verfier verifies first operand is MDString.1193assert(AMDS != nullptr && BMDS != nullptr &&1194"first operand should be a non-null MDString");1195StringRef AProfName = AMDS->getString();1196StringRef BProfName = BMDS->getString();1197if (AProfName == "branch_weights" && BProfName == "branch_weights") {1198ConstantInt *AInstrWeight = mdconst::dyn_extract<ConstantInt>(1199A->getOperand(getBranchWeightOffset(A)));1200ConstantInt *BInstrWeight = mdconst::dyn_extract<ConstantInt>(1201B->getOperand(getBranchWeightOffset(B)));1202assert(AInstrWeight && BInstrWeight && "verified by LLVM verifier");1203return MDNode::get(Ctx,1204{MDHelper.createString("branch_weights"),1205MDHelper.createConstant(ConstantInt::get(1206Type::getInt64Ty(Ctx),1207SaturatingAdd(AInstrWeight->getZExtValue(),1208BInstrWeight->getZExtValue())))});1209}1210return nullptr;1211}12121213// Pass in both instructions and nodes. Instruction information (e.g.,1214// instruction type) helps interpret profiles and make implementation clearer.1215MDNode *MDNode::getMergedProfMetadata(MDNode *A, MDNode *B,1216const Instruction *AInstr,1217const Instruction *BInstr) {1218if (!(A && B)) {1219return A ? A : B;1220}12211222assert(AInstr->getMetadata(LLVMContext::MD_prof) == A &&1223"Caller should guarantee");1224assert(BInstr->getMetadata(LLVMContext::MD_prof) == B &&1225"Caller should guarantee");12261227const CallInst *ACall = dyn_cast<CallInst>(AInstr);1228const CallInst *BCall = dyn_cast<CallInst>(BInstr);12291230// Both ACall and BCall are direct callsites.1231if (ACall && BCall && ACall->getCalledFunction() &&1232BCall->getCalledFunction())1233return mergeDirectCallProfMetadata(A, B, AInstr, BInstr);12341235// The rest of the cases are not implemented but could be added1236// when there are use cases.1237return nullptr;1238}12391240static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {1241return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();1242}12431244static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {1245return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);1246}12471248static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,1249ConstantInt *Low, ConstantInt *High) {1250ConstantRange NewRange(Low->getValue(), High->getValue());1251unsigned Size = EndPoints.size();1252APInt LB = EndPoints[Size - 2]->getValue();1253APInt LE = EndPoints[Size - 1]->getValue();1254ConstantRange LastRange(LB, LE);1255if (canBeMerged(NewRange, LastRange)) {1256ConstantRange Union = LastRange.unionWith(NewRange);1257Type *Ty = High->getType();1258EndPoints[Size - 2] =1259cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));1260EndPoints[Size - 1] =1261cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));1262return true;1263}1264return false;1265}12661267static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,1268ConstantInt *Low, ConstantInt *High) {1269if (!EndPoints.empty())1270if (tryMergeRange(EndPoints, Low, High))1271return;12721273EndPoints.push_back(Low);1274EndPoints.push_back(High);1275}12761277MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {1278// Given two ranges, we want to compute the union of the ranges. This1279// is slightly complicated by having to combine the intervals and merge1280// the ones that overlap.12811282if (!A || !B)1283return nullptr;12841285if (A == B)1286return A;12871288// First, walk both lists in order of the lower boundary of each interval.1289// At each step, try to merge the new interval to the last one we added.1290SmallVector<ConstantInt *, 4> EndPoints;1291unsigned AI = 0;1292unsigned BI = 0;1293unsigned AN = A->getNumOperands() / 2;1294unsigned BN = B->getNumOperands() / 2;1295while (AI < AN && BI < BN) {1296ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));1297ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));12981299if (ALow->getValue().slt(BLow->getValue())) {1300addRange(EndPoints, ALow,1301mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));1302++AI;1303} else {1304addRange(EndPoints, BLow,1305mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));1306++BI;1307}1308}1309while (AI < AN) {1310addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),1311mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));1312++AI;1313}1314while (BI < BN) {1315addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),1316mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));1317++BI;1318}13191320// We haven't handled wrap in the previous merge,1321// if we have at least 2 ranges (4 endpoints) we have to try to merge1322// the last and first ones.1323unsigned Size = EndPoints.size();1324if (Size > 2) {1325ConstantInt *FB = EndPoints[0];1326ConstantInt *FE = EndPoints[1];1327if (tryMergeRange(EndPoints, FB, FE)) {1328for (unsigned i = 0; i < Size - 2; ++i) {1329EndPoints[i] = EndPoints[i + 2];1330}1331EndPoints.resize(Size - 2);1332}1333}13341335// If in the end we have a single range, it is possible that it is now the1336// full range. Just drop the metadata in that case.1337if (EndPoints.size() == 2) {1338ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());1339if (Range.isFullSet())1340return nullptr;1341}13421343SmallVector<Metadata *, 4> MDs;1344MDs.reserve(EndPoints.size());1345for (auto *I : EndPoints)1346MDs.push_back(ConstantAsMetadata::get(I));1347return MDNode::get(A->getContext(), MDs);1348}13491350MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {1351if (!A || !B)1352return nullptr;13531354ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));1355ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));1356if (AVal->getZExtValue() < BVal->getZExtValue())1357return A;1358return B;1359}13601361//===----------------------------------------------------------------------===//1362// NamedMDNode implementation.1363//13641365static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {1366return *(SmallVector<TrackingMDRef, 4> *)Operands;1367}13681369NamedMDNode::NamedMDNode(const Twine &N)1370: Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}13711372NamedMDNode::~NamedMDNode() {1373dropAllReferences();1374delete &getNMDOps(Operands);1375}13761377unsigned NamedMDNode::getNumOperands() const {1378return (unsigned)getNMDOps(Operands).size();1379}13801381MDNode *NamedMDNode::getOperand(unsigned i) const {1382assert(i < getNumOperands() && "Invalid Operand number!");1383auto *N = getNMDOps(Operands)[i].get();1384return cast_or_null<MDNode>(N);1385}13861387void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }13881389void NamedMDNode::setOperand(unsigned I, MDNode *New) {1390assert(I < getNumOperands() && "Invalid operand number");1391getNMDOps(Operands)[I].reset(New);1392}13931394void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }13951396void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }13971398StringRef NamedMDNode::getName() const { return StringRef(Name); }13991400//===----------------------------------------------------------------------===//1401// Instruction Metadata method implementations.1402//14031404MDNode *MDAttachments::lookup(unsigned ID) const {1405for (const auto &A : Attachments)1406if (A.MDKind == ID)1407return A.Node;1408return nullptr;1409}14101411void MDAttachments::get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const {1412for (const auto &A : Attachments)1413if (A.MDKind == ID)1414Result.push_back(A.Node);1415}14161417void MDAttachments::getAll(1418SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {1419for (const auto &A : Attachments)1420Result.emplace_back(A.MDKind, A.Node);14211422// Sort the resulting array so it is stable with respect to metadata IDs. We1423// need to preserve the original insertion order though.1424if (Result.size() > 1)1425llvm::stable_sort(Result, less_first());1426}14271428void MDAttachments::set(unsigned ID, MDNode *MD) {1429erase(ID);1430if (MD)1431insert(ID, *MD);1432}14331434void MDAttachments::insert(unsigned ID, MDNode &MD) {1435Attachments.push_back({ID, TrackingMDNodeRef(&MD)});1436}14371438bool MDAttachments::erase(unsigned ID) {1439if (empty())1440return false;14411442// Common case is one value.1443if (Attachments.size() == 1 && Attachments.back().MDKind == ID) {1444Attachments.pop_back();1445return true;1446}14471448auto OldSize = Attachments.size();1449llvm::erase_if(Attachments,1450[ID](const Attachment &A) { return A.MDKind == ID; });1451return OldSize != Attachments.size();1452}14531454MDNode *Value::getMetadata(StringRef Kind) const {1455if (!hasMetadata())1456return nullptr;1457unsigned KindID = getContext().getMDKindID(Kind);1458return getMetadataImpl(KindID);1459}14601461MDNode *Value::getMetadataImpl(unsigned KindID) const {1462const LLVMContext &Ctx = getContext();1463const MDAttachments &Attachements = Ctx.pImpl->ValueMetadata.at(this);1464return Attachements.lookup(KindID);1465}14661467void Value::getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const {1468if (hasMetadata())1469getContext().pImpl->ValueMetadata.at(this).get(KindID, MDs);1470}14711472void Value::getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const {1473if (hasMetadata())1474getMetadata(getContext().getMDKindID(Kind), MDs);1475}14761477void Value::getAllMetadata(1478SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {1479if (hasMetadata()) {1480assert(getContext().pImpl->ValueMetadata.count(this) &&1481"bit out of sync with hash table");1482const MDAttachments &Info = getContext().pImpl->ValueMetadata.at(this);1483Info.getAll(MDs);1484}1485}14861487void Value::setMetadata(unsigned KindID, MDNode *Node) {1488assert(isa<Instruction>(this) || isa<GlobalObject>(this));14891490// Handle the case when we're adding/updating metadata on a value.1491if (Node) {1492MDAttachments &Info = getContext().pImpl->ValueMetadata[this];1493assert(!Info.empty() == HasMetadata && "bit out of sync with hash table");1494if (Info.empty())1495HasMetadata = true;1496Info.set(KindID, Node);1497return;1498}14991500// Otherwise, we're removing metadata from an instruction.1501assert((HasMetadata == (getContext().pImpl->ValueMetadata.count(this) > 0)) &&1502"bit out of sync with hash table");1503if (!HasMetadata)1504return; // Nothing to remove!1505MDAttachments &Info = getContext().pImpl->ValueMetadata.find(this)->second;15061507// Handle removal of an existing value.1508Info.erase(KindID);1509if (!Info.empty())1510return;1511getContext().pImpl->ValueMetadata.erase(this);1512HasMetadata = false;1513}15141515void Value::setMetadata(StringRef Kind, MDNode *Node) {1516if (!Node && !HasMetadata)1517return;1518setMetadata(getContext().getMDKindID(Kind), Node);1519}15201521void Value::addMetadata(unsigned KindID, MDNode &MD) {1522assert(isa<Instruction>(this) || isa<GlobalObject>(this));1523if (!HasMetadata)1524HasMetadata = true;1525getContext().pImpl->ValueMetadata[this].insert(KindID, MD);1526}15271528void Value::addMetadata(StringRef Kind, MDNode &MD) {1529addMetadata(getContext().getMDKindID(Kind), MD);1530}15311532bool Value::eraseMetadata(unsigned KindID) {1533// Nothing to unset.1534if (!HasMetadata)1535return false;15361537MDAttachments &Store = getContext().pImpl->ValueMetadata.find(this)->second;1538bool Changed = Store.erase(KindID);1539if (Store.empty())1540clearMetadata();1541return Changed;1542}15431544void Value::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {1545if (!HasMetadata)1546return;15471548auto &MetadataStore = getContext().pImpl->ValueMetadata;1549MDAttachments &Info = MetadataStore.find(this)->second;1550assert(!Info.empty() && "bit out of sync with hash table");1551Info.remove_if([Pred](const MDAttachments::Attachment &I) {1552return Pred(I.MDKind, I.Node);1553});15541555if (Info.empty())1556clearMetadata();1557}15581559void Value::clearMetadata() {1560if (!HasMetadata)1561return;1562assert(getContext().pImpl->ValueMetadata.count(this) &&1563"bit out of sync with hash table");1564getContext().pImpl->ValueMetadata.erase(this);1565HasMetadata = false;1566}15671568void Instruction::setMetadata(StringRef Kind, MDNode *Node) {1569if (!Node && !hasMetadata())1570return;1571setMetadata(getContext().getMDKindID(Kind), Node);1572}15731574MDNode *Instruction::getMetadataImpl(StringRef Kind) const {1575const LLVMContext &Ctx = getContext();1576unsigned KindID = Ctx.getMDKindID(Kind);1577if (KindID == LLVMContext::MD_dbg)1578return DbgLoc.getAsMDNode();1579return Value::getMetadata(KindID);1580}15811582void Instruction::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {1583if (DbgLoc && Pred(LLVMContext::MD_dbg, DbgLoc.getAsMDNode()))1584DbgLoc = {};15851586Value::eraseMetadataIf(Pred);1587}15881589void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {1590if (!Value::hasMetadata())1591return; // Nothing to remove!15921593SmallSet<unsigned, 32> KnownSet;1594KnownSet.insert(KnownIDs.begin(), KnownIDs.end());15951596// A DIAssignID attachment is debug metadata, don't drop it.1597KnownSet.insert(LLVMContext::MD_DIAssignID);15981599Value::eraseMetadataIf([&KnownSet](unsigned MDKind, MDNode *Node) {1600return !KnownSet.count(MDKind);1601});1602}16031604void Instruction::updateDIAssignIDMapping(DIAssignID *ID) {1605auto &IDToInstrs = getContext().pImpl->AssignmentIDToInstrs;1606if (const DIAssignID *CurrentID =1607cast_or_null<DIAssignID>(getMetadata(LLVMContext::MD_DIAssignID))) {1608// Nothing to do if the ID isn't changing.1609if (ID == CurrentID)1610return;16111612// Unmap this instruction from its current ID.1613auto InstrsIt = IDToInstrs.find(CurrentID);1614assert(InstrsIt != IDToInstrs.end() &&1615"Expect existing attachment to be mapped");16161617auto &InstVec = InstrsIt->second;1618auto *InstIt = llvm::find(InstVec, this);1619assert(InstIt != InstVec.end() &&1620"Expect instruction to be mapped to attachment");1621// The vector contains a ptr to this. If this is the only element in the1622// vector, remove the ID:vector entry, otherwise just remove the1623// instruction from the vector.1624if (InstVec.size() == 1)1625IDToInstrs.erase(InstrsIt);1626else1627InstVec.erase(InstIt);1628}16291630// Map this instruction to the new ID.1631if (ID)1632IDToInstrs[ID].push_back(this);1633}16341635void Instruction::setMetadata(unsigned KindID, MDNode *Node) {1636if (!Node && !hasMetadata())1637return;16381639// Handle 'dbg' as a special case since it is not stored in the hash table.1640if (KindID == LLVMContext::MD_dbg) {1641DbgLoc = DebugLoc(Node);1642return;1643}16441645// Update DIAssignID to Instruction(s) mapping.1646if (KindID == LLVMContext::MD_DIAssignID) {1647// The DIAssignID tracking infrastructure doesn't support RAUWing temporary1648// nodes with DIAssignIDs. The cast_or_null below would also catch this, but1649// having a dedicated assert helps make this obvious.1650assert((!Node || !Node->isTemporary()) &&1651"Temporary DIAssignIDs are invalid");1652updateDIAssignIDMapping(cast_or_null<DIAssignID>(Node));1653}16541655Value::setMetadata(KindID, Node);1656}16571658void Instruction::addAnnotationMetadata(SmallVector<StringRef> Annotations) {1659SmallVector<Metadata *, 4> Names;1660if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {1661SmallSetVector<StringRef, 2> AnnotationsSet(Annotations.begin(),1662Annotations.end());1663auto *Tuple = cast<MDTuple>(Existing);1664for (auto &N : Tuple->operands()) {1665if (isa<MDString>(N.get())) {1666Names.push_back(N);1667continue;1668}1669auto *MDAnnotationTuple = cast<MDTuple>(N);1670if (any_of(MDAnnotationTuple->operands(), [&AnnotationsSet](auto &Op) {1671return AnnotationsSet.contains(cast<MDString>(Op)->getString());1672}))1673return;1674Names.push_back(N);1675}1676}16771678MDBuilder MDB(getContext());1679SmallVector<Metadata *> MDAnnotationStrings;1680for (StringRef Annotation : Annotations)1681MDAnnotationStrings.push_back(MDB.createString(Annotation));1682MDNode *InfoTuple = MDTuple::get(getContext(), MDAnnotationStrings);1683Names.push_back(InfoTuple);1684MDNode *MD = MDTuple::get(getContext(), Names);1685setMetadata(LLVMContext::MD_annotation, MD);1686}16871688void Instruction::addAnnotationMetadata(StringRef Name) {1689SmallVector<Metadata *, 4> Names;1690if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {1691auto *Tuple = cast<MDTuple>(Existing);1692for (auto &N : Tuple->operands()) {1693if (isa<MDString>(N.get()) &&1694cast<MDString>(N.get())->getString() == Name)1695return;1696Names.push_back(N.get());1697}1698}16991700MDBuilder MDB(getContext());1701Names.push_back(MDB.createString(Name));1702MDNode *MD = MDTuple::get(getContext(), Names);1703setMetadata(LLVMContext::MD_annotation, MD);1704}17051706AAMDNodes Instruction::getAAMetadata() const {1707AAMDNodes Result;1708// Not using Instruction::hasMetadata() because we're not interested in1709// DebugInfoMetadata.1710if (Value::hasMetadata()) {1711const MDAttachments &Info = getContext().pImpl->ValueMetadata.at(this);1712Result.TBAA = Info.lookup(LLVMContext::MD_tbaa);1713Result.TBAAStruct = Info.lookup(LLVMContext::MD_tbaa_struct);1714Result.Scope = Info.lookup(LLVMContext::MD_alias_scope);1715Result.NoAlias = Info.lookup(LLVMContext::MD_noalias);1716}1717return Result;1718}17191720void Instruction::setAAMetadata(const AAMDNodes &N) {1721setMetadata(LLVMContext::MD_tbaa, N.TBAA);1722setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);1723setMetadata(LLVMContext::MD_alias_scope, N.Scope);1724setMetadata(LLVMContext::MD_noalias, N.NoAlias);1725}17261727void Instruction::setNoSanitizeMetadata() {1728setMetadata(llvm::LLVMContext::MD_nosanitize,1729llvm::MDNode::get(getContext(), std::nullopt));1730}17311732void Instruction::getAllMetadataImpl(1733SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {1734Result.clear();17351736// Handle 'dbg' as a special case since it is not stored in the hash table.1737if (DbgLoc) {1738Result.push_back(1739std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));1740}1741Value::getAllMetadata(Result);1742}17431744bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {1745assert(1746(getOpcode() == Instruction::Br || getOpcode() == Instruction::Select ||1747getOpcode() == Instruction::Call || getOpcode() == Instruction::Invoke ||1748getOpcode() == Instruction::IndirectBr ||1749getOpcode() == Instruction::Switch) &&1750"Looking for branch weights on something besides branch");17511752return ::extractProfTotalWeight(*this, TotalVal);1753}17541755void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {1756SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;1757Other->getAllMetadata(MDs);1758for (auto &MD : MDs) {1759// We need to adjust the type metadata offset.1760if (Offset != 0 && MD.first == LLVMContext::MD_type) {1761auto *OffsetConst = cast<ConstantInt>(1762cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());1763Metadata *TypeId = MD.second->getOperand(1);1764auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(1765OffsetConst->getType(), OffsetConst->getValue() + Offset));1766addMetadata(LLVMContext::MD_type,1767*MDNode::get(getContext(), {NewOffsetMD, TypeId}));1768continue;1769}1770// If an offset adjustment was specified we need to modify the DIExpression1771// to prepend the adjustment:1772// !DIExpression(DW_OP_plus, Offset, [original expr])1773auto *Attachment = MD.second;1774if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {1775DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);1776DIExpression *E = nullptr;1777if (!GV) {1778auto *GVE = cast<DIGlobalVariableExpression>(Attachment);1779GV = GVE->getVariable();1780E = GVE->getExpression();1781}1782ArrayRef<uint64_t> OrigElements;1783if (E)1784OrigElements = E->getElements();1785std::vector<uint64_t> Elements(OrigElements.size() + 2);1786Elements[0] = dwarf::DW_OP_plus_uconst;1787Elements[1] = Offset;1788llvm::copy(OrigElements, Elements.begin() + 2);1789E = DIExpression::get(getContext(), Elements);1790Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);1791}1792addMetadata(MD.first, *Attachment);1793}1794}17951796void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {1797addMetadata(1798LLVMContext::MD_type,1799*MDTuple::get(getContext(),1800{ConstantAsMetadata::get(ConstantInt::get(1801Type::getInt64Ty(getContext()), Offset)),1802TypeID}));1803}18041805void GlobalObject::setVCallVisibilityMetadata(VCallVisibility Visibility) {1806// Remove any existing vcall visibility metadata first in case we are1807// updating.1808eraseMetadata(LLVMContext::MD_vcall_visibility);1809addMetadata(LLVMContext::MD_vcall_visibility,1810*MDNode::get(getContext(),1811{ConstantAsMetadata::get(ConstantInt::get(1812Type::getInt64Ty(getContext()), Visibility))}));1813}18141815GlobalObject::VCallVisibility GlobalObject::getVCallVisibility() const {1816if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {1817uint64_t Val = cast<ConstantInt>(1818cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())1819->getZExtValue();1820assert(Val <= 2 && "unknown vcall visibility!");1821return (VCallVisibility)Val;1822}1823return VCallVisibility::VCallVisibilityPublic;1824}18251826void Function::setSubprogram(DISubprogram *SP) {1827setMetadata(LLVMContext::MD_dbg, SP);1828}18291830DISubprogram *Function::getSubprogram() const {1831return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));1832}18331834bool Function::shouldEmitDebugInfoForProfiling() const {1835if (DISubprogram *SP = getSubprogram()) {1836if (DICompileUnit *CU = SP->getUnit()) {1837return CU->getDebugInfoForProfiling();1838}1839}1840return false;1841}18421843void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {1844addMetadata(LLVMContext::MD_dbg, *GV);1845}18461847void GlobalVariable::getDebugInfo(1848SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {1849SmallVector<MDNode *, 1> MDs;1850getMetadata(LLVMContext::MD_dbg, MDs);1851for (MDNode *MD : MDs)1852GVs.push_back(cast<DIGlobalVariableExpression>(MD));1853}185418551856