10b57cec5SDimitry Andric //===-- Value.cpp - Implement the Value class -----------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements the Value, ValueHandle, and User classes. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "llvm/IR/Value.h" 140b57cec5SDimitry Andric #include "LLVMContextImpl.h" 150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 160b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h" 17480093f4SDimitry Andric #include "llvm/ADT/SmallString.h" 180b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 190b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 200b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 21fe6060f1SDimitry Andric #include "llvm/IR/DebugInfo.h" 220b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 230b57cec5SDimitry Andric #include "llvm/IR/DerivedUser.h" 240b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h" 250b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 260b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 270b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 280b57cec5SDimitry Andric #include "llvm/IR/Module.h" 290b57cec5SDimitry Andric #include "llvm/IR/Operator.h" 300b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h" 310b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h" 32480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 330b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 340b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 350b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h" 360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 370b57cec5SDimitry Andric #include <algorithm> 380b57cec5SDimitry Andric 390b57cec5SDimitry Andric using namespace llvm; 400b57cec5SDimitry Andric 41fe6060f1SDimitry Andric static cl::opt<unsigned> UseDerefAtPointSemantics( 42fe6060f1SDimitry Andric "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false), 43fe6060f1SDimitry Andric cl::desc("Deref attributes and metadata infer facts at definition only")); 440b57cec5SDimitry Andric 450b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 460b57cec5SDimitry Andric // Value Class 470b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 480b57cec5SDimitry Andric static inline Type *checkType(Type *Ty) { 490b57cec5SDimitry Andric assert(Ty && "Value defined with a null type: Error!"); 500b57cec5SDimitry Andric return Ty; 510b57cec5SDimitry Andric } 520b57cec5SDimitry Andric 530b57cec5SDimitry Andric Value::Value(Type *ty, unsigned scid) 54e8d8bef9SDimitry Andric : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0), 55e8d8bef9SDimitry Andric SubclassOptionalData(0), SubclassData(0), NumUserOperands(0), 56e8d8bef9SDimitry Andric IsUsedByMD(false), HasName(false), HasMetadata(false) { 570b57cec5SDimitry Andric static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)"); 580b57cec5SDimitry Andric // FIXME: Why isn't this in the subclass gunk?? 590b57cec5SDimitry Andric // Note, we cannot call isa<CallInst> before the CallInst has been 600b57cec5SDimitry Andric // constructed. 61fe6060f1SDimitry Andric unsigned OpCode = 0; 62fe6060f1SDimitry Andric if (SubclassID >= InstructionVal) 63fe6060f1SDimitry Andric OpCode = SubclassID - InstructionVal; 64fe6060f1SDimitry Andric if (OpCode == Instruction::Call || OpCode == Instruction::Invoke || 65fe6060f1SDimitry Andric OpCode == Instruction::CallBr) 660b57cec5SDimitry Andric assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) && 67fe6060f1SDimitry Andric "invalid CallBase type!"); 680b57cec5SDimitry Andric else if (SubclassID != BasicBlockVal && 690b57cec5SDimitry Andric (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal)) 700b57cec5SDimitry Andric assert((VTy->isFirstClassType() || VTy->isVoidTy()) && 710b57cec5SDimitry Andric "Cannot create non-first-class values except for constants!"); 720b57cec5SDimitry Andric static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned), 730b57cec5SDimitry Andric "Value too big"); 740b57cec5SDimitry Andric } 750b57cec5SDimitry Andric 760b57cec5SDimitry Andric Value::~Value() { 770b57cec5SDimitry Andric // Notify all ValueHandles (if present) that this value is going away. 780b57cec5SDimitry Andric if (HasValueHandle) 790b57cec5SDimitry Andric ValueHandleBase::ValueIsDeleted(this); 800b57cec5SDimitry Andric if (isUsedByMetadata()) 810b57cec5SDimitry Andric ValueAsMetadata::handleDeletion(this); 820b57cec5SDimitry Andric 83e8d8bef9SDimitry Andric // Remove associated metadata from context. 84e8d8bef9SDimitry Andric if (HasMetadata) 85e8d8bef9SDimitry Andric clearMetadata(); 86e8d8bef9SDimitry Andric 870b57cec5SDimitry Andric #ifndef NDEBUG // Only in -g mode... 880b57cec5SDimitry Andric // Check to make sure that there are no uses of this value that are still 890b57cec5SDimitry Andric // around when the value is destroyed. If there are, then we have a dangling 900b57cec5SDimitry Andric // reference and something is wrong. This code is here to print out where 910b57cec5SDimitry Andric // the value is still being referenced. 920b57cec5SDimitry Andric // 935ffd83dbSDimitry Andric // Note that use_empty() cannot be called here, as it eventually downcasts 945ffd83dbSDimitry Andric // 'this' to GlobalValue (derived class of Value), but GlobalValue has already 955ffd83dbSDimitry Andric // been destructed, so accessing it is UB. 965ffd83dbSDimitry Andric // 975ffd83dbSDimitry Andric if (!materialized_use_empty()) { 980b57cec5SDimitry Andric dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n"; 990b57cec5SDimitry Andric for (auto *U : users()) 1000b57cec5SDimitry Andric dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n"; 1010b57cec5SDimitry Andric } 1020b57cec5SDimitry Andric #endif 1035ffd83dbSDimitry Andric assert(materialized_use_empty() && "Uses remain when a value is destroyed!"); 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric // If this value is named, destroy the name. This should not be in a symtab 1060b57cec5SDimitry Andric // at this point. 1070b57cec5SDimitry Andric destroyValueName(); 1080b57cec5SDimitry Andric } 1090b57cec5SDimitry Andric 1100b57cec5SDimitry Andric void Value::deleteValue() { 1110b57cec5SDimitry Andric switch (getValueID()) { 1120b57cec5SDimitry Andric #define HANDLE_VALUE(Name) \ 1130b57cec5SDimitry Andric case Value::Name##Val: \ 1140b57cec5SDimitry Andric delete static_cast<Name *>(this); \ 1150b57cec5SDimitry Andric break; 1160b57cec5SDimitry Andric #define HANDLE_MEMORY_VALUE(Name) \ 1170b57cec5SDimitry Andric case Value::Name##Val: \ 1180b57cec5SDimitry Andric static_cast<DerivedUser *>(this)->DeleteValue( \ 1190b57cec5SDimitry Andric static_cast<DerivedUser *>(this)); \ 1200b57cec5SDimitry Andric break; 1215ffd83dbSDimitry Andric #define HANDLE_CONSTANT(Name) \ 1225ffd83dbSDimitry Andric case Value::Name##Val: \ 1235ffd83dbSDimitry Andric llvm_unreachable("constants should be destroyed with destroyConstant"); \ 1245ffd83dbSDimitry Andric break; 1250b57cec5SDimitry Andric #define HANDLE_INSTRUCTION(Name) /* nothing */ 1260b57cec5SDimitry Andric #include "llvm/IR/Value.def" 1270b57cec5SDimitry Andric 1280b57cec5SDimitry Andric #define HANDLE_INST(N, OPC, CLASS) \ 1290b57cec5SDimitry Andric case Value::InstructionVal + Instruction::OPC: \ 1300b57cec5SDimitry Andric delete static_cast<CLASS *>(this); \ 1310b57cec5SDimitry Andric break; 1320b57cec5SDimitry Andric #define HANDLE_USER_INST(N, OPC, CLASS) 1330b57cec5SDimitry Andric #include "llvm/IR/Instruction.def" 1340b57cec5SDimitry Andric 1350b57cec5SDimitry Andric default: 1360b57cec5SDimitry Andric llvm_unreachable("attempting to delete unknown value kind"); 1370b57cec5SDimitry Andric } 1380b57cec5SDimitry Andric } 1390b57cec5SDimitry Andric 1400b57cec5SDimitry Andric void Value::destroyValueName() { 1410b57cec5SDimitry Andric ValueName *Name = getValueName(); 1425ffd83dbSDimitry Andric if (Name) { 1435ffd83dbSDimitry Andric MallocAllocator Allocator; 1445ffd83dbSDimitry Andric Name->Destroy(Allocator); 1455ffd83dbSDimitry Andric } 1460b57cec5SDimitry Andric setValueName(nullptr); 1470b57cec5SDimitry Andric } 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric bool Value::hasNUses(unsigned N) const { 1500b57cec5SDimitry Andric return hasNItems(use_begin(), use_end(), N); 1510b57cec5SDimitry Andric } 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric bool Value::hasNUsesOrMore(unsigned N) const { 1540b57cec5SDimitry Andric return hasNItemsOrMore(use_begin(), use_end(), N); 1550b57cec5SDimitry Andric } 1560b57cec5SDimitry Andric 157e8d8bef9SDimitry Andric bool Value::hasOneUser() const { 158e8d8bef9SDimitry Andric if (use_empty()) 159e8d8bef9SDimitry Andric return false; 160e8d8bef9SDimitry Andric if (hasOneUse()) 161e8d8bef9SDimitry Andric return true; 162e8d8bef9SDimitry Andric return std::equal(++user_begin(), user_end(), user_begin()); 163e8d8bef9SDimitry Andric } 164e8d8bef9SDimitry Andric 1655ffd83dbSDimitry Andric static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); } 1665ffd83dbSDimitry Andric 1675ffd83dbSDimitry Andric Use *Value::getSingleUndroppableUse() { 1685ffd83dbSDimitry Andric Use *Result = nullptr; 1695ffd83dbSDimitry Andric for (Use &U : uses()) { 1705ffd83dbSDimitry Andric if (!U.getUser()->isDroppable()) { 1715ffd83dbSDimitry Andric if (Result) 1725ffd83dbSDimitry Andric return nullptr; 1735ffd83dbSDimitry Andric Result = &U; 1745ffd83dbSDimitry Andric } 1755ffd83dbSDimitry Andric } 1765ffd83dbSDimitry Andric return Result; 1775ffd83dbSDimitry Andric } 1785ffd83dbSDimitry Andric 179349cc55cSDimitry Andric User *Value::getUniqueUndroppableUser() { 180349cc55cSDimitry Andric User *Result = nullptr; 181349cc55cSDimitry Andric for (auto *U : users()) { 182349cc55cSDimitry Andric if (!U->isDroppable()) { 183349cc55cSDimitry Andric if (Result && Result != U) 184349cc55cSDimitry Andric return nullptr; 185349cc55cSDimitry Andric Result = U; 186349cc55cSDimitry Andric } 187349cc55cSDimitry Andric } 188349cc55cSDimitry Andric return Result; 189349cc55cSDimitry Andric } 190349cc55cSDimitry Andric 1915ffd83dbSDimitry Andric bool Value::hasNUndroppableUses(unsigned int N) const { 1925ffd83dbSDimitry Andric return hasNItems(user_begin(), user_end(), N, isUnDroppableUser); 1935ffd83dbSDimitry Andric } 1945ffd83dbSDimitry Andric 1955ffd83dbSDimitry Andric bool Value::hasNUndroppableUsesOrMore(unsigned int N) const { 1965ffd83dbSDimitry Andric return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser); 1975ffd83dbSDimitry Andric } 1985ffd83dbSDimitry Andric 1995ffd83dbSDimitry Andric void Value::dropDroppableUses( 2005ffd83dbSDimitry Andric llvm::function_ref<bool(const Use *)> ShouldDrop) { 2015ffd83dbSDimitry Andric SmallVector<Use *, 8> ToBeEdited; 2025ffd83dbSDimitry Andric for (Use &U : uses()) 2035ffd83dbSDimitry Andric if (U.getUser()->isDroppable() && ShouldDrop(&U)) 2045ffd83dbSDimitry Andric ToBeEdited.push_back(&U); 205e8d8bef9SDimitry Andric for (Use *U : ToBeEdited) 206e8d8bef9SDimitry Andric dropDroppableUse(*U); 207e8d8bef9SDimitry Andric } 208e8d8bef9SDimitry Andric 209e8d8bef9SDimitry Andric void Value::dropDroppableUsesIn(User &Usr) { 210e8d8bef9SDimitry Andric assert(Usr.isDroppable() && "Expected a droppable user!"); 211e8d8bef9SDimitry Andric for (Use &UsrOp : Usr.operands()) { 212e8d8bef9SDimitry Andric if (UsrOp.get() == this) 213e8d8bef9SDimitry Andric dropDroppableUse(UsrOp); 214e8d8bef9SDimitry Andric } 215e8d8bef9SDimitry Andric } 216e8d8bef9SDimitry Andric 217e8d8bef9SDimitry Andric void Value::dropDroppableUse(Use &U) { 218e8d8bef9SDimitry Andric U.removeFromList(); 219fe6060f1SDimitry Andric if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) { 220e8d8bef9SDimitry Andric unsigned OpNo = U.getOperandNo(); 2215ffd83dbSDimitry Andric if (OpNo == 0) 222e8d8bef9SDimitry Andric U.set(ConstantInt::getTrue(Assume->getContext())); 2235ffd83dbSDimitry Andric else { 224e8d8bef9SDimitry Andric U.set(UndefValue::get(U.get()->getType())); 2255ffd83dbSDimitry Andric CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo); 226e8d8bef9SDimitry Andric BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore"); 2275ffd83dbSDimitry Andric } 228e8d8bef9SDimitry Andric return; 229e8d8bef9SDimitry Andric } 230e8d8bef9SDimitry Andric 2315ffd83dbSDimitry Andric llvm_unreachable("unkown droppable use"); 2325ffd83dbSDimitry Andric } 2335ffd83dbSDimitry Andric 2340b57cec5SDimitry Andric bool Value::isUsedInBasicBlock(const BasicBlock *BB) const { 2350b57cec5SDimitry Andric // This can be computed either by scanning the instructions in BB, or by 2360b57cec5SDimitry Andric // scanning the use list of this Value. Both lists can be very long, but 2370b57cec5SDimitry Andric // usually one is quite short. 2380b57cec5SDimitry Andric // 2390b57cec5SDimitry Andric // Scan both lists simultaneously until one is exhausted. This limits the 2400b57cec5SDimitry Andric // search to the shorter list. 2410b57cec5SDimitry Andric BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); 2420b57cec5SDimitry Andric const_user_iterator UI = user_begin(), UE = user_end(); 2430b57cec5SDimitry Andric for (; BI != BE && UI != UE; ++BI, ++UI) { 2440b57cec5SDimitry Andric // Scan basic block: Check if this Value is used by the instruction at BI. 2450b57cec5SDimitry Andric if (is_contained(BI->operands(), this)) 2460b57cec5SDimitry Andric return true; 2470b57cec5SDimitry Andric // Scan use list: Check if the use at UI is in BB. 2480b57cec5SDimitry Andric const auto *User = dyn_cast<Instruction>(*UI); 2490b57cec5SDimitry Andric if (User && User->getParent() == BB) 2500b57cec5SDimitry Andric return true; 2510b57cec5SDimitry Andric } 2520b57cec5SDimitry Andric return false; 2530b57cec5SDimitry Andric } 2540b57cec5SDimitry Andric 2550b57cec5SDimitry Andric unsigned Value::getNumUses() const { 2560b57cec5SDimitry Andric return (unsigned)std::distance(use_begin(), use_end()); 2570b57cec5SDimitry Andric } 2580b57cec5SDimitry Andric 2590b57cec5SDimitry Andric static bool getSymTab(Value *V, ValueSymbolTable *&ST) { 2600b57cec5SDimitry Andric ST = nullptr; 2610b57cec5SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(V)) { 2620b57cec5SDimitry Andric if (BasicBlock *P = I->getParent()) 2630b57cec5SDimitry Andric if (Function *PP = P->getParent()) 2640b57cec5SDimitry Andric ST = PP->getValueSymbolTable(); 2650b57cec5SDimitry Andric } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 2660b57cec5SDimitry Andric if (Function *P = BB->getParent()) 2670b57cec5SDimitry Andric ST = P->getValueSymbolTable(); 2680b57cec5SDimitry Andric } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2690b57cec5SDimitry Andric if (Module *P = GV->getParent()) 2700b57cec5SDimitry Andric ST = &P->getValueSymbolTable(); 2710b57cec5SDimitry Andric } else if (Argument *A = dyn_cast<Argument>(V)) { 2720b57cec5SDimitry Andric if (Function *P = A->getParent()) 2730b57cec5SDimitry Andric ST = P->getValueSymbolTable(); 2740b57cec5SDimitry Andric } else { 2750b57cec5SDimitry Andric assert(isa<Constant>(V) && "Unknown value type!"); 2760b57cec5SDimitry Andric return true; // no name is setable for this. 2770b57cec5SDimitry Andric } 2780b57cec5SDimitry Andric return false; 2790b57cec5SDimitry Andric } 2800b57cec5SDimitry Andric 2810b57cec5SDimitry Andric ValueName *Value::getValueName() const { 2820b57cec5SDimitry Andric if (!HasName) return nullptr; 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric LLVMContext &Ctx = getContext(); 2850b57cec5SDimitry Andric auto I = Ctx.pImpl->ValueNames.find(this); 2860b57cec5SDimitry Andric assert(I != Ctx.pImpl->ValueNames.end() && 2870b57cec5SDimitry Andric "No name entry found!"); 2880b57cec5SDimitry Andric 2890b57cec5SDimitry Andric return I->second; 2900b57cec5SDimitry Andric } 2910b57cec5SDimitry Andric 2920b57cec5SDimitry Andric void Value::setValueName(ValueName *VN) { 2930b57cec5SDimitry Andric LLVMContext &Ctx = getContext(); 2940b57cec5SDimitry Andric 2950b57cec5SDimitry Andric assert(HasName == Ctx.pImpl->ValueNames.count(this) && 2960b57cec5SDimitry Andric "HasName bit out of sync!"); 2970b57cec5SDimitry Andric 2980b57cec5SDimitry Andric if (!VN) { 2990b57cec5SDimitry Andric if (HasName) 3000b57cec5SDimitry Andric Ctx.pImpl->ValueNames.erase(this); 3010b57cec5SDimitry Andric HasName = false; 3020b57cec5SDimitry Andric return; 3030b57cec5SDimitry Andric } 3040b57cec5SDimitry Andric 3050b57cec5SDimitry Andric HasName = true; 3060b57cec5SDimitry Andric Ctx.pImpl->ValueNames[this] = VN; 3070b57cec5SDimitry Andric } 3080b57cec5SDimitry Andric 3090b57cec5SDimitry Andric StringRef Value::getName() const { 3100b57cec5SDimitry Andric // Make sure the empty string is still a C string. For historical reasons, 3110b57cec5SDimitry Andric // some clients want to call .data() on the result and expect it to be null 3120b57cec5SDimitry Andric // terminated. 3130b57cec5SDimitry Andric if (!hasName()) 3140b57cec5SDimitry Andric return StringRef("", 0); 3150b57cec5SDimitry Andric return getValueName()->getKey(); 3160b57cec5SDimitry Andric } 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric void Value::setNameImpl(const Twine &NewName) { 3190b57cec5SDimitry Andric // Fast-path: LLVMContext can be set to strip out non-GlobalValue names 3200b57cec5SDimitry Andric if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this)) 3210b57cec5SDimitry Andric return; 3220b57cec5SDimitry Andric 3230b57cec5SDimitry Andric // Fast path for common IRBuilder case of setName("") when there is no name. 3240b57cec5SDimitry Andric if (NewName.isTriviallyEmpty() && !hasName()) 3250b57cec5SDimitry Andric return; 3260b57cec5SDimitry Andric 3270b57cec5SDimitry Andric SmallString<256> NameData; 3280b57cec5SDimitry Andric StringRef NameRef = NewName.toStringRef(NameData); 3290b57cec5SDimitry Andric assert(NameRef.find_first_of(0) == StringRef::npos && 3300b57cec5SDimitry Andric "Null bytes are not allowed in names"); 3310b57cec5SDimitry Andric 3320b57cec5SDimitry Andric // Name isn't changing? 3330b57cec5SDimitry Andric if (getName() == NameRef) 3340b57cec5SDimitry Andric return; 3350b57cec5SDimitry Andric 3360b57cec5SDimitry Andric assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); 3370b57cec5SDimitry Andric 3380b57cec5SDimitry Andric // Get the symbol table to update for this object. 3390b57cec5SDimitry Andric ValueSymbolTable *ST; 3400b57cec5SDimitry Andric if (getSymTab(this, ST)) 3410b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant). 3420b57cec5SDimitry Andric 3430b57cec5SDimitry Andric if (!ST) { // No symbol table to update? Just do the change. 3440b57cec5SDimitry Andric if (NameRef.empty()) { 3450b57cec5SDimitry Andric // Free the name for this value. 3460b57cec5SDimitry Andric destroyValueName(); 3470b57cec5SDimitry Andric return; 3480b57cec5SDimitry Andric } 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric // NOTE: Could optimize for the case the name is shrinking to not deallocate 3510b57cec5SDimitry Andric // then reallocated. 3520b57cec5SDimitry Andric destroyValueName(); 3530b57cec5SDimitry Andric 3540b57cec5SDimitry Andric // Create the new name. 3555ffd83dbSDimitry Andric MallocAllocator Allocator; 3565ffd83dbSDimitry Andric setValueName(ValueName::Create(NameRef, Allocator)); 3570b57cec5SDimitry Andric getValueName()->setValue(this); 3580b57cec5SDimitry Andric return; 3590b57cec5SDimitry Andric } 3600b57cec5SDimitry Andric 3610b57cec5SDimitry Andric // NOTE: Could optimize for the case the name is shrinking to not deallocate 3620b57cec5SDimitry Andric // then reallocated. 3630b57cec5SDimitry Andric if (hasName()) { 3640b57cec5SDimitry Andric // Remove old name. 3650b57cec5SDimitry Andric ST->removeValueName(getValueName()); 3660b57cec5SDimitry Andric destroyValueName(); 3670b57cec5SDimitry Andric 3680b57cec5SDimitry Andric if (NameRef.empty()) 3690b57cec5SDimitry Andric return; 3700b57cec5SDimitry Andric } 3710b57cec5SDimitry Andric 3720b57cec5SDimitry Andric // Name is changing to something new. 3730b57cec5SDimitry Andric setValueName(ST->createValueName(NameRef, this)); 3740b57cec5SDimitry Andric } 3750b57cec5SDimitry Andric 3760b57cec5SDimitry Andric void Value::setName(const Twine &NewName) { 3770b57cec5SDimitry Andric setNameImpl(NewName); 3780b57cec5SDimitry Andric if (Function *F = dyn_cast<Function>(this)) 3790b57cec5SDimitry Andric F->recalculateIntrinsicID(); 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric void Value::takeName(Value *V) { 3830b57cec5SDimitry Andric ValueSymbolTable *ST = nullptr; 3840b57cec5SDimitry Andric // If this value has a name, drop it. 3850b57cec5SDimitry Andric if (hasName()) { 3860b57cec5SDimitry Andric // Get the symtab this is in. 3870b57cec5SDimitry Andric if (getSymTab(this, ST)) { 3880b57cec5SDimitry Andric // We can't set a name on this value, but we need to clear V's name if 3890b57cec5SDimitry Andric // it has one. 3900b57cec5SDimitry Andric if (V->hasName()) V->setName(""); 3910b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant). 3920b57cec5SDimitry Andric } 3930b57cec5SDimitry Andric 3940b57cec5SDimitry Andric // Remove old name. 3950b57cec5SDimitry Andric if (ST) 3960b57cec5SDimitry Andric ST->removeValueName(getValueName()); 3970b57cec5SDimitry Andric destroyValueName(); 3980b57cec5SDimitry Andric } 3990b57cec5SDimitry Andric 4000b57cec5SDimitry Andric // Now we know that this has no name. 4010b57cec5SDimitry Andric 4020b57cec5SDimitry Andric // If V has no name either, we're done. 4030b57cec5SDimitry Andric if (!V->hasName()) return; 4040b57cec5SDimitry Andric 4050b57cec5SDimitry Andric // Get this's symtab if we didn't before. 4060b57cec5SDimitry Andric if (!ST) { 4070b57cec5SDimitry Andric if (getSymTab(this, ST)) { 4080b57cec5SDimitry Andric // Clear V's name. 4090b57cec5SDimitry Andric V->setName(""); 4100b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant). 4110b57cec5SDimitry Andric } 4120b57cec5SDimitry Andric } 4130b57cec5SDimitry Andric 4140b57cec5SDimitry Andric // Get V's ST, this should always succed, because V has a name. 4150b57cec5SDimitry Andric ValueSymbolTable *VST; 4160b57cec5SDimitry Andric bool Failure = getSymTab(V, VST); 4170b57cec5SDimitry Andric assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure; 4180b57cec5SDimitry Andric 4190b57cec5SDimitry Andric // If these values are both in the same symtab, we can do this very fast. 4200b57cec5SDimitry Andric // This works even if both values have no symtab yet. 4210b57cec5SDimitry Andric if (ST == VST) { 4220b57cec5SDimitry Andric // Take the name! 4230b57cec5SDimitry Andric setValueName(V->getValueName()); 4240b57cec5SDimitry Andric V->setValueName(nullptr); 4250b57cec5SDimitry Andric getValueName()->setValue(this); 4260b57cec5SDimitry Andric return; 4270b57cec5SDimitry Andric } 4280b57cec5SDimitry Andric 4290b57cec5SDimitry Andric // Otherwise, things are slightly more complex. Remove V's name from VST and 4300b57cec5SDimitry Andric // then reinsert it into ST. 4310b57cec5SDimitry Andric 4320b57cec5SDimitry Andric if (VST) 4330b57cec5SDimitry Andric VST->removeValueName(V->getValueName()); 4340b57cec5SDimitry Andric setValueName(V->getValueName()); 4350b57cec5SDimitry Andric V->setValueName(nullptr); 4360b57cec5SDimitry Andric getValueName()->setValue(this); 4370b57cec5SDimitry Andric 4380b57cec5SDimitry Andric if (ST) 4390b57cec5SDimitry Andric ST->reinsertValue(this); 4400b57cec5SDimitry Andric } 4410b57cec5SDimitry Andric 442e8d8bef9SDimitry Andric #ifndef NDEBUG 443e8d8bef9SDimitry Andric std::string Value::getNameOrAsOperand() const { 444e8d8bef9SDimitry Andric if (!getName().empty()) 445e8d8bef9SDimitry Andric return std::string(getName()); 446e8d8bef9SDimitry Andric 447e8d8bef9SDimitry Andric std::string BBName; 448e8d8bef9SDimitry Andric raw_string_ostream OS(BBName); 449e8d8bef9SDimitry Andric printAsOperand(OS, false); 450e8d8bef9SDimitry Andric return OS.str(); 451e8d8bef9SDimitry Andric } 452e8d8bef9SDimitry Andric #endif 453e8d8bef9SDimitry Andric 4540b57cec5SDimitry Andric void Value::assertModuleIsMaterializedImpl() const { 4550b57cec5SDimitry Andric #ifndef NDEBUG 4560b57cec5SDimitry Andric const GlobalValue *GV = dyn_cast<GlobalValue>(this); 4570b57cec5SDimitry Andric if (!GV) 4580b57cec5SDimitry Andric return; 4590b57cec5SDimitry Andric const Module *M = GV->getParent(); 4600b57cec5SDimitry Andric if (!M) 4610b57cec5SDimitry Andric return; 4620b57cec5SDimitry Andric assert(M->isMaterialized()); 4630b57cec5SDimitry Andric #endif 4640b57cec5SDimitry Andric } 4650b57cec5SDimitry Andric 4660b57cec5SDimitry Andric #ifndef NDEBUG 4670b57cec5SDimitry Andric static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr, 4680b57cec5SDimitry Andric Constant *C) { 4690b57cec5SDimitry Andric if (!Cache.insert(Expr).second) 4700b57cec5SDimitry Andric return false; 4710b57cec5SDimitry Andric 4720b57cec5SDimitry Andric for (auto &O : Expr->operands()) { 4730b57cec5SDimitry Andric if (O == C) 4740b57cec5SDimitry Andric return true; 4750b57cec5SDimitry Andric auto *CE = dyn_cast<ConstantExpr>(O); 4760b57cec5SDimitry Andric if (!CE) 4770b57cec5SDimitry Andric continue; 4780b57cec5SDimitry Andric if (contains(Cache, CE, C)) 4790b57cec5SDimitry Andric return true; 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric return false; 4820b57cec5SDimitry Andric } 4830b57cec5SDimitry Andric 4840b57cec5SDimitry Andric static bool contains(Value *Expr, Value *V) { 4850b57cec5SDimitry Andric if (Expr == V) 4860b57cec5SDimitry Andric return true; 4870b57cec5SDimitry Andric 4880b57cec5SDimitry Andric auto *C = dyn_cast<Constant>(V); 4890b57cec5SDimitry Andric if (!C) 4900b57cec5SDimitry Andric return false; 4910b57cec5SDimitry Andric 4920b57cec5SDimitry Andric auto *CE = dyn_cast<ConstantExpr>(Expr); 4930b57cec5SDimitry Andric if (!CE) 4940b57cec5SDimitry Andric return false; 4950b57cec5SDimitry Andric 4960b57cec5SDimitry Andric SmallPtrSet<ConstantExpr *, 4> Cache; 4970b57cec5SDimitry Andric return contains(Cache, CE, C); 4980b57cec5SDimitry Andric } 4990b57cec5SDimitry Andric #endif // NDEBUG 5000b57cec5SDimitry Andric 5010b57cec5SDimitry Andric void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) { 5020b57cec5SDimitry Andric assert(New && "Value::replaceAllUsesWith(<null>) is invalid!"); 5030b57cec5SDimitry Andric assert(!contains(New, this) && 5040b57cec5SDimitry Andric "this->replaceAllUsesWith(expr(this)) is NOT valid!"); 5050b57cec5SDimitry Andric assert(New->getType() == getType() && 5060b57cec5SDimitry Andric "replaceAllUses of value with new value of different type!"); 5070b57cec5SDimitry Andric 5080b57cec5SDimitry Andric // Notify all ValueHandles (if present) that this value is going away. 5090b57cec5SDimitry Andric if (HasValueHandle) 5100b57cec5SDimitry Andric ValueHandleBase::ValueIsRAUWd(this, New); 5110b57cec5SDimitry Andric if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata()) 5120b57cec5SDimitry Andric ValueAsMetadata::handleRAUW(this, New); 5130b57cec5SDimitry Andric 5140b57cec5SDimitry Andric while (!materialized_use_empty()) { 5150b57cec5SDimitry Andric Use &U = *UseList; 5160b57cec5SDimitry Andric // Must handle Constants specially, we cannot call replaceUsesOfWith on a 5170b57cec5SDimitry Andric // constant because they are uniqued. 5180b57cec5SDimitry Andric if (auto *C = dyn_cast<Constant>(U.getUser())) { 5190b57cec5SDimitry Andric if (!isa<GlobalValue>(C)) { 5200b57cec5SDimitry Andric C->handleOperandChange(this, New); 5210b57cec5SDimitry Andric continue; 5220b57cec5SDimitry Andric } 5230b57cec5SDimitry Andric } 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric U.set(New); 5260b57cec5SDimitry Andric } 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric if (BasicBlock *BB = dyn_cast<BasicBlock>(this)) 5290b57cec5SDimitry Andric BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New)); 5300b57cec5SDimitry Andric } 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric void Value::replaceAllUsesWith(Value *New) { 5330b57cec5SDimitry Andric doRAUW(New, ReplaceMetadataUses::Yes); 5340b57cec5SDimitry Andric } 5350b57cec5SDimitry Andric 5360b57cec5SDimitry Andric void Value::replaceNonMetadataUsesWith(Value *New) { 5370b57cec5SDimitry Andric doRAUW(New, ReplaceMetadataUses::No); 5380b57cec5SDimitry Andric } 5390b57cec5SDimitry Andric 540fe6060f1SDimitry Andric void Value::replaceUsesWithIf(Value *New, 541fe6060f1SDimitry Andric llvm::function_ref<bool(Use &U)> ShouldReplace) { 542fe6060f1SDimitry Andric assert(New && "Value::replaceUsesWithIf(<null>) is invalid!"); 543fe6060f1SDimitry Andric assert(New->getType() == getType() && 544fe6060f1SDimitry Andric "replaceUses of value with new value of different type!"); 545fe6060f1SDimitry Andric 546fe6060f1SDimitry Andric SmallVector<TrackingVH<Constant>, 8> Consts; 547fe6060f1SDimitry Andric SmallPtrSet<Constant *, 8> Visited; 548fe6060f1SDimitry Andric 549349cc55cSDimitry Andric for (Use &U : llvm::make_early_inc_range(uses())) { 550fe6060f1SDimitry Andric if (!ShouldReplace(U)) 551fe6060f1SDimitry Andric continue; 552fe6060f1SDimitry Andric // Must handle Constants specially, we cannot call replaceUsesOfWith on a 553fe6060f1SDimitry Andric // constant because they are uniqued. 554fe6060f1SDimitry Andric if (auto *C = dyn_cast<Constant>(U.getUser())) { 555fe6060f1SDimitry Andric if (!isa<GlobalValue>(C)) { 556fe6060f1SDimitry Andric if (Visited.insert(C).second) 557fe6060f1SDimitry Andric Consts.push_back(TrackingVH<Constant>(C)); 558fe6060f1SDimitry Andric continue; 559fe6060f1SDimitry Andric } 560fe6060f1SDimitry Andric } 561fe6060f1SDimitry Andric U.set(New); 562fe6060f1SDimitry Andric } 563fe6060f1SDimitry Andric 564fe6060f1SDimitry Andric while (!Consts.empty()) { 565fe6060f1SDimitry Andric // FIXME: handleOperandChange() updates all the uses in a given Constant, 566fe6060f1SDimitry Andric // not just the one passed to ShouldReplace 567fe6060f1SDimitry Andric Consts.pop_back_val()->handleOperandChange(this, New); 568fe6060f1SDimitry Andric } 569fe6060f1SDimitry Andric } 570fe6060f1SDimitry Andric 571fe6060f1SDimitry Andric /// Replace llvm.dbg.* uses of MetadataAsValue(ValueAsMetadata(V)) outside BB 572fe6060f1SDimitry Andric /// with New. 573fe6060f1SDimitry Andric static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) { 574fe6060f1SDimitry Andric SmallVector<DbgVariableIntrinsic *> DbgUsers; 575fe6060f1SDimitry Andric findDbgUsers(DbgUsers, V); 576fe6060f1SDimitry Andric for (auto *DVI : DbgUsers) { 577fe6060f1SDimitry Andric if (DVI->getParent() != BB) 578fe6060f1SDimitry Andric DVI->replaceVariableLocationOp(V, New); 579fe6060f1SDimitry Andric } 580fe6060f1SDimitry Andric } 581fe6060f1SDimitry Andric 5820b57cec5SDimitry Andric // Like replaceAllUsesWith except it does not handle constants or basic blocks. 5830b57cec5SDimitry Andric // This routine leaves uses within BB. 5840b57cec5SDimitry Andric void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) { 5850b57cec5SDimitry Andric assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!"); 5860b57cec5SDimitry Andric assert(!contains(New, this) && 5870b57cec5SDimitry Andric "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!"); 5880b57cec5SDimitry Andric assert(New->getType() == getType() && 5890b57cec5SDimitry Andric "replaceUses of value with new value of different type!"); 5900b57cec5SDimitry Andric assert(BB && "Basic block that may contain a use of 'New' must be defined\n"); 5910b57cec5SDimitry Andric 592fe6060f1SDimitry Andric replaceDbgUsesOutsideBlock(this, New, BB); 5938bcb0991SDimitry Andric replaceUsesWithIf(New, [BB](Use &U) { 5948bcb0991SDimitry Andric auto *I = dyn_cast<Instruction>(U.getUser()); 5958bcb0991SDimitry Andric // Don't replace if it's an instruction in the BB basic block. 5968bcb0991SDimitry Andric return !I || I->getParent() != BB; 5978bcb0991SDimitry Andric }); 5980b57cec5SDimitry Andric } 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric namespace { 6010b57cec5SDimitry Andric // Various metrics for how much to strip off of pointers. 6020b57cec5SDimitry Andric enum PointerStripKind { 6030b57cec5SDimitry Andric PSK_ZeroIndices, 6040b57cec5SDimitry Andric PSK_ZeroIndicesAndAliases, 6058bcb0991SDimitry Andric PSK_ZeroIndicesSameRepresentation, 606fe6060f1SDimitry Andric PSK_ForAliasAnalysis, 6070b57cec5SDimitry Andric PSK_InBoundsConstantIndices, 6080b57cec5SDimitry Andric PSK_InBounds 6090b57cec5SDimitry Andric }; 6100b57cec5SDimitry Andric 6115ffd83dbSDimitry Andric template <PointerStripKind StripKind> static void NoopCallback(const Value *) {} 6125ffd83dbSDimitry Andric 6130b57cec5SDimitry Andric template <PointerStripKind StripKind> 6145ffd83dbSDimitry Andric static const Value *stripPointerCastsAndOffsets( 6155ffd83dbSDimitry Andric const Value *V, 6165ffd83dbSDimitry Andric function_ref<void(const Value *)> Func = NoopCallback<StripKind>) { 6170b57cec5SDimitry Andric if (!V->getType()->isPointerTy()) 6180b57cec5SDimitry Andric return V; 6190b57cec5SDimitry Andric 6200b57cec5SDimitry Andric // Even though we don't look through PHI nodes, we could be called on an 6210b57cec5SDimitry Andric // instruction in an unreachable block, which may be on a cycle. 6220b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> Visited; 6230b57cec5SDimitry Andric 6240b57cec5SDimitry Andric Visited.insert(V); 6250b57cec5SDimitry Andric do { 6265ffd83dbSDimitry Andric Func(V); 6270b57cec5SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(V)) { 6280b57cec5SDimitry Andric switch (StripKind) { 6290b57cec5SDimitry Andric case PSK_ZeroIndices: 6308bcb0991SDimitry Andric case PSK_ZeroIndicesAndAliases: 6318bcb0991SDimitry Andric case PSK_ZeroIndicesSameRepresentation: 632fe6060f1SDimitry Andric case PSK_ForAliasAnalysis: 6330b57cec5SDimitry Andric if (!GEP->hasAllZeroIndices()) 6340b57cec5SDimitry Andric return V; 6350b57cec5SDimitry Andric break; 6360b57cec5SDimitry Andric case PSK_InBoundsConstantIndices: 6370b57cec5SDimitry Andric if (!GEP->hasAllConstantIndices()) 6380b57cec5SDimitry Andric return V; 6390b57cec5SDimitry Andric LLVM_FALLTHROUGH; 6400b57cec5SDimitry Andric case PSK_InBounds: 6410b57cec5SDimitry Andric if (!GEP->isInBounds()) 6420b57cec5SDimitry Andric return V; 6430b57cec5SDimitry Andric break; 6440b57cec5SDimitry Andric } 6450b57cec5SDimitry Andric V = GEP->getPointerOperand(); 6460b57cec5SDimitry Andric } else if (Operator::getOpcode(V) == Instruction::BitCast) { 6470b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0); 6485ffd83dbSDimitry Andric if (!V->getType()->isPointerTy()) 6495ffd83dbSDimitry Andric return V; 6508bcb0991SDimitry Andric } else if (StripKind != PSK_ZeroIndicesSameRepresentation && 6510b57cec5SDimitry Andric Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 6520b57cec5SDimitry Andric // TODO: If we know an address space cast will not change the 6530b57cec5SDimitry Andric // representation we could look through it here as well. 6540b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0); 6558bcb0991SDimitry Andric } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) { 6568bcb0991SDimitry Andric V = cast<GlobalAlias>(V)->getAliasee(); 657fe6060f1SDimitry Andric } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) && 658fe6060f1SDimitry Andric cast<PHINode>(V)->getNumIncomingValues() == 1) { 659fe6060f1SDimitry Andric V = cast<PHINode>(V)->getIncomingValue(0); 6600b57cec5SDimitry Andric } else { 6610b57cec5SDimitry Andric if (const auto *Call = dyn_cast<CallBase>(V)) { 6620b57cec5SDimitry Andric if (const Value *RV = Call->getReturnedArgOperand()) { 6630b57cec5SDimitry Andric V = RV; 6640b57cec5SDimitry Andric continue; 6650b57cec5SDimitry Andric } 6660b57cec5SDimitry Andric // The result of launder.invariant.group must alias it's argument, 6670b57cec5SDimitry Andric // but it can't be marked with returned attribute, that's why it needs 6680b57cec5SDimitry Andric // special case. 669fe6060f1SDimitry Andric if (StripKind == PSK_ForAliasAnalysis && 6700b57cec5SDimitry Andric (Call->getIntrinsicID() == Intrinsic::launder_invariant_group || 6710b57cec5SDimitry Andric Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) { 6720b57cec5SDimitry Andric V = Call->getArgOperand(0); 6730b57cec5SDimitry Andric continue; 6740b57cec5SDimitry Andric } 6750b57cec5SDimitry Andric } 6760b57cec5SDimitry Andric return V; 6770b57cec5SDimitry Andric } 6780b57cec5SDimitry Andric assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 6790b57cec5SDimitry Andric } while (Visited.insert(V).second); 6800b57cec5SDimitry Andric 6810b57cec5SDimitry Andric return V; 6820b57cec5SDimitry Andric } 6830b57cec5SDimitry Andric } // end anonymous namespace 6840b57cec5SDimitry Andric 6850b57cec5SDimitry Andric const Value *Value::stripPointerCasts() const { 6868bcb0991SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this); 6878bcb0991SDimitry Andric } 6888bcb0991SDimitry Andric 6898bcb0991SDimitry Andric const Value *Value::stripPointerCastsAndAliases() const { 6900b57cec5SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this); 6910b57cec5SDimitry Andric } 6920b57cec5SDimitry Andric 6930b57cec5SDimitry Andric const Value *Value::stripPointerCastsSameRepresentation() const { 6948bcb0991SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this); 6950b57cec5SDimitry Andric } 6960b57cec5SDimitry Andric 6970b57cec5SDimitry Andric const Value *Value::stripInBoundsConstantOffsets() const { 6980b57cec5SDimitry Andric return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this); 6990b57cec5SDimitry Andric } 7000b57cec5SDimitry Andric 701fe6060f1SDimitry Andric const Value *Value::stripPointerCastsForAliasAnalysis() const { 702fe6060f1SDimitry Andric return stripPointerCastsAndOffsets<PSK_ForAliasAnalysis>(this); 7030b57cec5SDimitry Andric } 7040b57cec5SDimitry Andric 7055ffd83dbSDimitry Andric const Value *Value::stripAndAccumulateConstantOffsets( 7065ffd83dbSDimitry Andric const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, 707349cc55cSDimitry Andric bool AllowInvariantGroup, 7085ffd83dbSDimitry Andric function_ref<bool(Value &, APInt &)> ExternalAnalysis) const { 7090b57cec5SDimitry Andric if (!getType()->isPtrOrPtrVectorTy()) 7100b57cec5SDimitry Andric return this; 7110b57cec5SDimitry Andric 7120b57cec5SDimitry Andric unsigned BitWidth = Offset.getBitWidth(); 7130b57cec5SDimitry Andric assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) && 7140b57cec5SDimitry Andric "The offset bit width does not match the DL specification."); 7150b57cec5SDimitry Andric 7160b57cec5SDimitry Andric // Even though we don't look through PHI nodes, we could be called on an 7170b57cec5SDimitry Andric // instruction in an unreachable block, which may be on a cycle. 7180b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> Visited; 7190b57cec5SDimitry Andric Visited.insert(this); 7200b57cec5SDimitry Andric const Value *V = this; 7210b57cec5SDimitry Andric do { 7220b57cec5SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(V)) { 7230b57cec5SDimitry Andric // If in-bounds was requested, we do not strip non-in-bounds GEPs. 7240b57cec5SDimitry Andric if (!AllowNonInbounds && !GEP->isInBounds()) 7250b57cec5SDimitry Andric return V; 7260b57cec5SDimitry Andric 7270b57cec5SDimitry Andric // If one of the values we have visited is an addrspacecast, then 7280b57cec5SDimitry Andric // the pointer type of this GEP may be different from the type 7290b57cec5SDimitry Andric // of the Ptr parameter which was passed to this function. This 7300b57cec5SDimitry Andric // means when we construct GEPOffset, we need to use the size 7310b57cec5SDimitry Andric // of GEP's pointer type rather than the size of the original 7320b57cec5SDimitry Andric // pointer type. 7330b57cec5SDimitry Andric APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0); 7345ffd83dbSDimitry Andric if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis)) 7350b57cec5SDimitry Andric return V; 7360b57cec5SDimitry Andric 7370b57cec5SDimitry Andric // Stop traversal if the pointer offset wouldn't fit in the bit-width 7380b57cec5SDimitry Andric // provided by the Offset argument. This can happen due to AddrSpaceCast 7390b57cec5SDimitry Andric // stripping. 7400b57cec5SDimitry Andric if (GEPOffset.getMinSignedBits() > BitWidth) 7410b57cec5SDimitry Andric return V; 7420b57cec5SDimitry Andric 7435ffd83dbSDimitry Andric // External Analysis can return a result higher/lower than the value 7445ffd83dbSDimitry Andric // represents. We need to detect overflow/underflow. 7455ffd83dbSDimitry Andric APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth); 7465ffd83dbSDimitry Andric if (!ExternalAnalysis) { 7475ffd83dbSDimitry Andric Offset += GEPOffsetST; 7485ffd83dbSDimitry Andric } else { 7495ffd83dbSDimitry Andric bool Overflow = false; 7505ffd83dbSDimitry Andric APInt OldOffset = Offset; 7515ffd83dbSDimitry Andric Offset = Offset.sadd_ov(GEPOffsetST, Overflow); 7525ffd83dbSDimitry Andric if (Overflow) { 7535ffd83dbSDimitry Andric Offset = OldOffset; 7545ffd83dbSDimitry Andric return V; 7555ffd83dbSDimitry Andric } 7565ffd83dbSDimitry Andric } 7570b57cec5SDimitry Andric V = GEP->getPointerOperand(); 7580b57cec5SDimitry Andric } else if (Operator::getOpcode(V) == Instruction::BitCast || 7590b57cec5SDimitry Andric Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 7600b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0); 7610b57cec5SDimitry Andric } else if (auto *GA = dyn_cast<GlobalAlias>(V)) { 7620b57cec5SDimitry Andric if (!GA->isInterposable()) 7630b57cec5SDimitry Andric V = GA->getAliasee(); 7640b57cec5SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(V)) { 7650b57cec5SDimitry Andric if (const Value *RV = Call->getReturnedArgOperand()) 7660b57cec5SDimitry Andric V = RV; 767349cc55cSDimitry Andric if (AllowInvariantGroup && Call->isLaunderOrStripInvariantGroup()) 768349cc55cSDimitry Andric V = Call->getArgOperand(0); 7690b57cec5SDimitry Andric } 7700b57cec5SDimitry Andric assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!"); 7710b57cec5SDimitry Andric } while (Visited.insert(V).second); 7720b57cec5SDimitry Andric 7730b57cec5SDimitry Andric return V; 7740b57cec5SDimitry Andric } 7750b57cec5SDimitry Andric 7765ffd83dbSDimitry Andric const Value * 7775ffd83dbSDimitry Andric Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const { 7785ffd83dbSDimitry Andric return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func); 7790b57cec5SDimitry Andric } 7800b57cec5SDimitry Andric 781fe6060f1SDimitry Andric bool Value::canBeFreed() const { 782fe6060f1SDimitry Andric assert(getType()->isPointerTy()); 783fe6060f1SDimitry Andric 784fe6060f1SDimitry Andric // Cases that can simply never be deallocated 785fe6060f1SDimitry Andric // *) Constants aren't allocated per se, thus not deallocated either. 786fe6060f1SDimitry Andric if (isa<Constant>(this)) 787fe6060f1SDimitry Andric return false; 788fe6060f1SDimitry Andric 789fe6060f1SDimitry Andric // Handle byval/byref/sret/inalloca/preallocated arguments. The storage 790fe6060f1SDimitry Andric // lifetime is guaranteed to be longer than the callee's lifetime. 791fe6060f1SDimitry Andric if (auto *A = dyn_cast<Argument>(this)) { 792fe6060f1SDimitry Andric if (A->hasPointeeInMemoryValueAttr()) 793fe6060f1SDimitry Andric return false; 794fe6060f1SDimitry Andric // A pointer to an object in a function which neither frees, nor can arrange 795fe6060f1SDimitry Andric // for another thread to free on its behalf, can not be freed in the scope 796fe6060f1SDimitry Andric // of the function. Note that this logic is restricted to memory 797fe6060f1SDimitry Andric // allocations in existance before the call; a nofree function *is* allowed 798fe6060f1SDimitry Andric // to free memory it allocated. 799fe6060f1SDimitry Andric const Function *F = A->getParent(); 800fe6060f1SDimitry Andric if (F->doesNotFreeMemory() && F->hasNoSync()) 801fe6060f1SDimitry Andric return false; 802fe6060f1SDimitry Andric } 803fe6060f1SDimitry Andric 804fe6060f1SDimitry Andric const Function *F = nullptr; 805fe6060f1SDimitry Andric if (auto *I = dyn_cast<Instruction>(this)) 806fe6060f1SDimitry Andric F = I->getFunction(); 807fe6060f1SDimitry Andric if (auto *A = dyn_cast<Argument>(this)) 808fe6060f1SDimitry Andric F = A->getParent(); 809fe6060f1SDimitry Andric 810fe6060f1SDimitry Andric if (!F) 811fe6060f1SDimitry Andric return true; 812fe6060f1SDimitry Andric 813fe6060f1SDimitry Andric // With garbage collection, deallocation typically occurs solely at or after 814fe6060f1SDimitry Andric // safepoints. If we're compiling for a collector which uses the 815fe6060f1SDimitry Andric // gc.statepoint infrastructure, safepoints aren't explicitly present 816fe6060f1SDimitry Andric // in the IR until after lowering from abstract to physical machine model. 817fe6060f1SDimitry Andric // The collector could chose to mix explicit deallocation and gc'd objects 818fe6060f1SDimitry Andric // which is why we need the explicit opt in on a per collector basis. 819fe6060f1SDimitry Andric if (!F->hasGC()) 820fe6060f1SDimitry Andric return true; 821fe6060f1SDimitry Andric 822fe6060f1SDimitry Andric const auto &GCName = F->getGC(); 823fe6060f1SDimitry Andric if (GCName == "statepoint-example") { 824fe6060f1SDimitry Andric auto *PT = cast<PointerType>(this->getType()); 825fe6060f1SDimitry Andric if (PT->getAddressSpace() != 1) 826fe6060f1SDimitry Andric // For the sake of this example GC, we arbitrarily pick addrspace(1) as 827fe6060f1SDimitry Andric // our GC managed heap. This must match the same check in 828fe6060f1SDimitry Andric // RewriteStatepointsForGC (and probably needs better factored.) 829fe6060f1SDimitry Andric return true; 830fe6060f1SDimitry Andric 831fe6060f1SDimitry Andric // It is cheaper to scan for a declaration than to scan for a use in this 832fe6060f1SDimitry Andric // function. Note that gc.statepoint is a type overloaded function so the 833fe6060f1SDimitry Andric // usual trick of requesting declaration of the intrinsic from the module 834fe6060f1SDimitry Andric // doesn't work. 835fe6060f1SDimitry Andric for (auto &Fn : *F->getParent()) 836fe6060f1SDimitry Andric if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint) 837fe6060f1SDimitry Andric return true; 838fe6060f1SDimitry Andric return false; 839fe6060f1SDimitry Andric } 840fe6060f1SDimitry Andric return true; 841fe6060f1SDimitry Andric } 842fe6060f1SDimitry Andric 8430b57cec5SDimitry Andric uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL, 844fe6060f1SDimitry Andric bool &CanBeNull, 845fe6060f1SDimitry Andric bool &CanBeFreed) const { 8460b57cec5SDimitry Andric assert(getType()->isPointerTy() && "must be pointer"); 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric uint64_t DerefBytes = 0; 8490b57cec5SDimitry Andric CanBeNull = false; 850fe6060f1SDimitry Andric CanBeFreed = UseDerefAtPointSemantics && canBeFreed(); 8510b57cec5SDimitry Andric if (const Argument *A = dyn_cast<Argument>(this)) { 8520b57cec5SDimitry Andric DerefBytes = A->getDereferenceableBytes(); 853e8d8bef9SDimitry Andric if (DerefBytes == 0) { 854e8d8bef9SDimitry Andric // Handle byval/byref/inalloca/preallocated arguments 855e8d8bef9SDimitry Andric if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) { 856e8d8bef9SDimitry Andric if (ArgMemTy->isSized()) { 857e8d8bef9SDimitry Andric // FIXME: Why isn't this the type alloc size? 858e8d8bef9SDimitry Andric DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinSize(); 8590b57cec5SDimitry Andric } 860e8d8bef9SDimitry Andric } 861e8d8bef9SDimitry Andric } 862e8d8bef9SDimitry Andric 8630b57cec5SDimitry Andric if (DerefBytes == 0) { 8640b57cec5SDimitry Andric DerefBytes = A->getDereferenceableOrNullBytes(); 8650b57cec5SDimitry Andric CanBeNull = true; 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(this)) { 868349cc55cSDimitry Andric DerefBytes = Call->getRetDereferenceableBytes(); 8690b57cec5SDimitry Andric if (DerefBytes == 0) { 870349cc55cSDimitry Andric DerefBytes = Call->getRetDereferenceableOrNullBytes(); 8710b57cec5SDimitry Andric CanBeNull = true; 8720b57cec5SDimitry Andric } 8730b57cec5SDimitry Andric } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 8740b57cec5SDimitry Andric if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) { 8750b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8760b57cec5SDimitry Andric DerefBytes = CI->getLimitedValue(); 8770b57cec5SDimitry Andric } 8780b57cec5SDimitry Andric if (DerefBytes == 0) { 8790b57cec5SDimitry Andric if (MDNode *MD = 8800b57cec5SDimitry Andric LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 8810b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8820b57cec5SDimitry Andric DerefBytes = CI->getLimitedValue(); 8830b57cec5SDimitry Andric } 8840b57cec5SDimitry Andric CanBeNull = true; 8850b57cec5SDimitry Andric } 8868bcb0991SDimitry Andric } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) { 8878bcb0991SDimitry Andric if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) { 8888bcb0991SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8898bcb0991SDimitry Andric DerefBytes = CI->getLimitedValue(); 8908bcb0991SDimitry Andric } 8918bcb0991SDimitry Andric if (DerefBytes == 0) { 8928bcb0991SDimitry Andric if (MDNode *MD = 8938bcb0991SDimitry Andric IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 8948bcb0991SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 8958bcb0991SDimitry Andric DerefBytes = CI->getLimitedValue(); 8968bcb0991SDimitry Andric } 8978bcb0991SDimitry Andric CanBeNull = true; 8988bcb0991SDimitry Andric } 8990b57cec5SDimitry Andric } else if (auto *AI = dyn_cast<AllocaInst>(this)) { 9000b57cec5SDimitry Andric if (!AI->isArrayAllocation()) { 9015ffd83dbSDimitry Andric DerefBytes = 9025ffd83dbSDimitry Andric DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize(); 9030b57cec5SDimitry Andric CanBeNull = false; 904fe6060f1SDimitry Andric CanBeFreed = false; 9050b57cec5SDimitry Andric } 9060b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<GlobalVariable>(this)) { 9070b57cec5SDimitry Andric if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) { 9080b57cec5SDimitry Andric // TODO: Don't outright reject hasExternalWeakLinkage but set the 9090b57cec5SDimitry Andric // CanBeNull flag. 9105ffd83dbSDimitry Andric DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize(); 9110b57cec5SDimitry Andric CanBeNull = false; 912fe6060f1SDimitry Andric CanBeFreed = false; 9130b57cec5SDimitry Andric } 9140b57cec5SDimitry Andric } 9150b57cec5SDimitry Andric return DerefBytes; 9160b57cec5SDimitry Andric } 9170b57cec5SDimitry Andric 9185ffd83dbSDimitry Andric Align Value::getPointerAlignment(const DataLayout &DL) const { 9190b57cec5SDimitry Andric assert(getType()->isPointerTy() && "must be pointer"); 9200b57cec5SDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(this)) { 9210b57cec5SDimitry Andric if (isa<Function>(GO)) { 9225ffd83dbSDimitry Andric Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne(); 9230b57cec5SDimitry Andric switch (DL.getFunctionPtrAlignType()) { 9240b57cec5SDimitry Andric case DataLayout::FunctionPtrAlignType::Independent: 9258bcb0991SDimitry Andric return FunctionPtrAlign; 9260b57cec5SDimitry Andric case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign: 9275ffd83dbSDimitry Andric return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne()); 9280b57cec5SDimitry Andric } 9298bcb0991SDimitry Andric llvm_unreachable("Unhandled FunctionPtrAlignType"); 9300b57cec5SDimitry Andric } 931*0eae32dcSDimitry Andric const MaybeAlign Alignment(GO->getAlign()); 9328bcb0991SDimitry Andric if (!Alignment) { 9330b57cec5SDimitry Andric if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 9340b57cec5SDimitry Andric Type *ObjectType = GVar->getValueType(); 9350b57cec5SDimitry Andric if (ObjectType->isSized()) { 9360b57cec5SDimitry Andric // If the object is defined in the current Module, we'll be giving 9370b57cec5SDimitry Andric // it the preferred alignment. Otherwise, we have to assume that it 9380b57cec5SDimitry Andric // may only have the minimum ABI alignment. 9390b57cec5SDimitry Andric if (GVar->isStrongDefinitionForLinker()) 9405ffd83dbSDimitry Andric return DL.getPreferredAlign(GVar); 9410b57cec5SDimitry Andric else 9425ffd83dbSDimitry Andric return DL.getABITypeAlign(ObjectType); 9430b57cec5SDimitry Andric } 9440b57cec5SDimitry Andric } 9450b57cec5SDimitry Andric } 9465ffd83dbSDimitry Andric return Alignment.valueOrOne(); 9470b57cec5SDimitry Andric } else if (const Argument *A = dyn_cast<Argument>(this)) { 9485ffd83dbSDimitry Andric const MaybeAlign Alignment = A->getParamAlign(); 9498bcb0991SDimitry Andric if (!Alignment && A->hasStructRetAttr()) { 9500b57cec5SDimitry Andric // An sret parameter has at least the ABI alignment of the return type. 951e8d8bef9SDimitry Andric Type *EltTy = A->getParamStructRetType(); 9520b57cec5SDimitry Andric if (EltTy->isSized()) 9535ffd83dbSDimitry Andric return DL.getABITypeAlign(EltTy); 9540b57cec5SDimitry Andric } 9555ffd83dbSDimitry Andric return Alignment.valueOrOne(); 9560b57cec5SDimitry Andric } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) { 9575ffd83dbSDimitry Andric return AI->getAlign(); 9588bcb0991SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(this)) { 9595ffd83dbSDimitry Andric MaybeAlign Alignment = Call->getRetAlign(); 9608bcb0991SDimitry Andric if (!Alignment && Call->getCalledFunction()) 9615ffd83dbSDimitry Andric Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment(); 9625ffd83dbSDimitry Andric return Alignment.valueOrOne(); 9638bcb0991SDimitry Andric } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 9640b57cec5SDimitry Andric if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) { 9650b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 9665ffd83dbSDimitry Andric return Align(CI->getLimitedValue()); 9675ffd83dbSDimitry Andric } 9685ffd83dbSDimitry Andric } else if (auto *CstPtr = dyn_cast<Constant>(this)) { 9695ffd83dbSDimitry Andric if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt( 9705ffd83dbSDimitry Andric const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()), 9715ffd83dbSDimitry Andric /*OnlyIfReduced=*/true))) { 9725ffd83dbSDimitry Andric size_t TrailingZeros = CstInt->getValue().countTrailingZeros(); 9735ffd83dbSDimitry Andric // While the actual alignment may be large, elsewhere we have 9745ffd83dbSDimitry Andric // an arbitrary upper alignmet limit, so let's clamp to it. 9755ffd83dbSDimitry Andric return Align(TrailingZeros < Value::MaxAlignmentExponent 9765ffd83dbSDimitry Andric ? uint64_t(1) << TrailingZeros 9775ffd83dbSDimitry Andric : Value::MaximumAlignment); 9780b57cec5SDimitry Andric } 9798bcb0991SDimitry Andric } 9805ffd83dbSDimitry Andric return Align(1); 9810b57cec5SDimitry Andric } 9820b57cec5SDimitry Andric 9830b57cec5SDimitry Andric const Value *Value::DoPHITranslation(const BasicBlock *CurBB, 9840b57cec5SDimitry Andric const BasicBlock *PredBB) const { 9850b57cec5SDimitry Andric auto *PN = dyn_cast<PHINode>(this); 9860b57cec5SDimitry Andric if (PN && PN->getParent() == CurBB) 9870b57cec5SDimitry Andric return PN->getIncomingValueForBlock(PredBB); 9880b57cec5SDimitry Andric return this; 9890b57cec5SDimitry Andric } 9900b57cec5SDimitry Andric 9910b57cec5SDimitry Andric LLVMContext &Value::getContext() const { return VTy->getContext(); } 9920b57cec5SDimitry Andric 9930b57cec5SDimitry Andric void Value::reverseUseList() { 9940b57cec5SDimitry Andric if (!UseList || !UseList->Next) 9950b57cec5SDimitry Andric // No need to reverse 0 or 1 uses. 9960b57cec5SDimitry Andric return; 9970b57cec5SDimitry Andric 9980b57cec5SDimitry Andric Use *Head = UseList; 9990b57cec5SDimitry Andric Use *Current = UseList->Next; 10000b57cec5SDimitry Andric Head->Next = nullptr; 10010b57cec5SDimitry Andric while (Current) { 10020b57cec5SDimitry Andric Use *Next = Current->Next; 10030b57cec5SDimitry Andric Current->Next = Head; 10045ffd83dbSDimitry Andric Head->Prev = &Current->Next; 10050b57cec5SDimitry Andric Head = Current; 10060b57cec5SDimitry Andric Current = Next; 10070b57cec5SDimitry Andric } 10080b57cec5SDimitry Andric UseList = Head; 10095ffd83dbSDimitry Andric Head->Prev = &UseList; 10100b57cec5SDimitry Andric } 10110b57cec5SDimitry Andric 10120b57cec5SDimitry Andric bool Value::isSwiftError() const { 10130b57cec5SDimitry Andric auto *Arg = dyn_cast<Argument>(this); 10140b57cec5SDimitry Andric if (Arg) 10150b57cec5SDimitry Andric return Arg->hasSwiftErrorAttr(); 10160b57cec5SDimitry Andric auto *Alloca = dyn_cast<AllocaInst>(this); 10170b57cec5SDimitry Andric if (!Alloca) 10180b57cec5SDimitry Andric return false; 10190b57cec5SDimitry Andric return Alloca->isSwiftError(); 10200b57cec5SDimitry Andric } 10210b57cec5SDimitry Andric 1022fe6060f1SDimitry Andric bool Value::isTransitiveUsedByMetadataOnly() const { 1023fe6060f1SDimitry Andric if (use_empty()) 1024fe6060f1SDimitry Andric return false; 1025fe6060f1SDimitry Andric llvm::SmallVector<const User *, 32> WorkList; 1026fe6060f1SDimitry Andric llvm::SmallPtrSet<const User *, 32> Visited; 1027fe6060f1SDimitry Andric WorkList.insert(WorkList.begin(), user_begin(), user_end()); 1028fe6060f1SDimitry Andric while (!WorkList.empty()) { 1029349cc55cSDimitry Andric const User *U = WorkList.pop_back_val(); 1030fe6060f1SDimitry Andric Visited.insert(U); 1031fe6060f1SDimitry Andric // If it is transitively used by a global value or a non-constant value, 1032fe6060f1SDimitry Andric // it's obviously not only used by metadata. 1033fe6060f1SDimitry Andric if (!isa<Constant>(U) || isa<GlobalValue>(U)) 1034fe6060f1SDimitry Andric return false; 1035fe6060f1SDimitry Andric for (const User *UU : U->users()) 1036fe6060f1SDimitry Andric if (!Visited.count(UU)) 1037fe6060f1SDimitry Andric WorkList.push_back(UU); 1038fe6060f1SDimitry Andric } 1039fe6060f1SDimitry Andric return true; 1040fe6060f1SDimitry Andric } 1041fe6060f1SDimitry Andric 10420b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 10430b57cec5SDimitry Andric // ValueHandleBase Class 10440b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 10450b57cec5SDimitry Andric 10460b57cec5SDimitry Andric void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) { 10470b57cec5SDimitry Andric assert(List && "Handle list is null?"); 10480b57cec5SDimitry Andric 10490b57cec5SDimitry Andric // Splice ourselves into the list. 10500b57cec5SDimitry Andric Next = *List; 10510b57cec5SDimitry Andric *List = this; 10520b57cec5SDimitry Andric setPrevPtr(List); 10530b57cec5SDimitry Andric if (Next) { 10540b57cec5SDimitry Andric Next->setPrevPtr(&Next); 10550b57cec5SDimitry Andric assert(getValPtr() == Next->getValPtr() && "Added to wrong list?"); 10560b57cec5SDimitry Andric } 10570b57cec5SDimitry Andric } 10580b57cec5SDimitry Andric 10590b57cec5SDimitry Andric void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) { 10600b57cec5SDimitry Andric assert(List && "Must insert after existing node"); 10610b57cec5SDimitry Andric 10620b57cec5SDimitry Andric Next = List->Next; 10630b57cec5SDimitry Andric setPrevPtr(&List->Next); 10640b57cec5SDimitry Andric List->Next = this; 10650b57cec5SDimitry Andric if (Next) 10660b57cec5SDimitry Andric Next->setPrevPtr(&Next); 10670b57cec5SDimitry Andric } 10680b57cec5SDimitry Andric 10690b57cec5SDimitry Andric void ValueHandleBase::AddToUseList() { 10700b57cec5SDimitry Andric assert(getValPtr() && "Null pointer doesn't have a use list!"); 10710b57cec5SDimitry Andric 10720b57cec5SDimitry Andric LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 10730b57cec5SDimitry Andric 10740b57cec5SDimitry Andric if (getValPtr()->HasValueHandle) { 10750b57cec5SDimitry Andric // If this value already has a ValueHandle, then it must be in the 10760b57cec5SDimitry Andric // ValueHandles map already. 10770b57cec5SDimitry Andric ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()]; 10780b57cec5SDimitry Andric assert(Entry && "Value doesn't have any handles?"); 10790b57cec5SDimitry Andric AddToExistingUseList(&Entry); 10800b57cec5SDimitry Andric return; 10810b57cec5SDimitry Andric } 10820b57cec5SDimitry Andric 10830b57cec5SDimitry Andric // Ok, it doesn't have any handles yet, so we must insert it into the 10840b57cec5SDimitry Andric // DenseMap. However, doing this insertion could cause the DenseMap to 10850b57cec5SDimitry Andric // reallocate itself, which would invalidate all of the PrevP pointers that 10860b57cec5SDimitry Andric // point into the old table. Handle this by checking for reallocation and 10870b57cec5SDimitry Andric // updating the stale pointers only if needed. 10880b57cec5SDimitry Andric DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 10890b57cec5SDimitry Andric const void *OldBucketPtr = Handles.getPointerIntoBucketsArray(); 10900b57cec5SDimitry Andric 10910b57cec5SDimitry Andric ValueHandleBase *&Entry = Handles[getValPtr()]; 10920b57cec5SDimitry Andric assert(!Entry && "Value really did already have handles?"); 10930b57cec5SDimitry Andric AddToExistingUseList(&Entry); 10940b57cec5SDimitry Andric getValPtr()->HasValueHandle = true; 10950b57cec5SDimitry Andric 10960b57cec5SDimitry Andric // If reallocation didn't happen or if this was the first insertion, don't 10970b57cec5SDimitry Andric // walk the table. 10980b57cec5SDimitry Andric if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 10990b57cec5SDimitry Andric Handles.size() == 1) { 11000b57cec5SDimitry Andric return; 11010b57cec5SDimitry Andric } 11020b57cec5SDimitry Andric 11030b57cec5SDimitry Andric // Okay, reallocation did happen. Fix the Prev Pointers. 11040b57cec5SDimitry Andric for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(), 11050b57cec5SDimitry Andric E = Handles.end(); I != E; ++I) { 11060b57cec5SDimitry Andric assert(I->second && I->first == I->second->getValPtr() && 11070b57cec5SDimitry Andric "List invariant broken!"); 11080b57cec5SDimitry Andric I->second->setPrevPtr(&I->second); 11090b57cec5SDimitry Andric } 11100b57cec5SDimitry Andric } 11110b57cec5SDimitry Andric 11120b57cec5SDimitry Andric void ValueHandleBase::RemoveFromUseList() { 11130b57cec5SDimitry Andric assert(getValPtr() && getValPtr()->HasValueHandle && 11140b57cec5SDimitry Andric "Pointer doesn't have a use list!"); 11150b57cec5SDimitry Andric 11160b57cec5SDimitry Andric // Unlink this from its use list. 11170b57cec5SDimitry Andric ValueHandleBase **PrevPtr = getPrevPtr(); 11180b57cec5SDimitry Andric assert(*PrevPtr == this && "List invariant broken"); 11190b57cec5SDimitry Andric 11200b57cec5SDimitry Andric *PrevPtr = Next; 11210b57cec5SDimitry Andric if (Next) { 11220b57cec5SDimitry Andric assert(Next->getPrevPtr() == &Next && "List invariant broken"); 11230b57cec5SDimitry Andric Next->setPrevPtr(PrevPtr); 11240b57cec5SDimitry Andric return; 11250b57cec5SDimitry Andric } 11260b57cec5SDimitry Andric 11270b57cec5SDimitry Andric // If the Next pointer was null, then it is possible that this was the last 11280b57cec5SDimitry Andric // ValueHandle watching VP. If so, delete its entry from the ValueHandles 11290b57cec5SDimitry Andric // map. 11300b57cec5SDimitry Andric LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 11310b57cec5SDimitry Andric DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 11320b57cec5SDimitry Andric if (Handles.isPointerIntoBucketsArray(PrevPtr)) { 11330b57cec5SDimitry Andric Handles.erase(getValPtr()); 11340b57cec5SDimitry Andric getValPtr()->HasValueHandle = false; 11350b57cec5SDimitry Andric } 11360b57cec5SDimitry Andric } 11370b57cec5SDimitry Andric 11380b57cec5SDimitry Andric void ValueHandleBase::ValueIsDeleted(Value *V) { 11390b57cec5SDimitry Andric assert(V->HasValueHandle && "Should only be called if ValueHandles present"); 11400b57cec5SDimitry Andric 11410b57cec5SDimitry Andric // Get the linked list base, which is guaranteed to exist since the 11420b57cec5SDimitry Andric // HasValueHandle flag is set. 11430b57cec5SDimitry Andric LLVMContextImpl *pImpl = V->getContext().pImpl; 11440b57cec5SDimitry Andric ValueHandleBase *Entry = pImpl->ValueHandles[V]; 11450b57cec5SDimitry Andric assert(Entry && "Value bit set but no entries exist"); 11460b57cec5SDimitry Andric 11470b57cec5SDimitry Andric // We use a local ValueHandleBase as an iterator so that ValueHandles can add 11480b57cec5SDimitry Andric // and remove themselves from the list without breaking our iteration. This 11490b57cec5SDimitry Andric // is not really an AssertingVH; we just have to give ValueHandleBase a kind. 11500b57cec5SDimitry Andric // Note that we deliberately do not the support the case when dropping a value 11510b57cec5SDimitry Andric // handle results in a new value handle being permanently added to the list 11520b57cec5SDimitry Andric // (as might occur in theory for CallbackVH's): the new value handle will not 11530b57cec5SDimitry Andric // be processed and the checking code will mete out righteous punishment if 11540b57cec5SDimitry Andric // the handle is still present once we have finished processing all the other 11550b57cec5SDimitry Andric // value handles (it is fine to momentarily add then remove a value handle). 11560b57cec5SDimitry Andric for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 11570b57cec5SDimitry Andric Iterator.RemoveFromUseList(); 11580b57cec5SDimitry Andric Iterator.AddToExistingUseListAfter(Entry); 11590b57cec5SDimitry Andric assert(Entry->Next == &Iterator && "Loop invariant broken."); 11600b57cec5SDimitry Andric 11610b57cec5SDimitry Andric switch (Entry->getKind()) { 11620b57cec5SDimitry Andric case Assert: 11630b57cec5SDimitry Andric break; 11640b57cec5SDimitry Andric case Weak: 11650b57cec5SDimitry Andric case WeakTracking: 11660b57cec5SDimitry Andric // WeakTracking and Weak just go to null, which unlinks them 11670b57cec5SDimitry Andric // from the list. 11680b57cec5SDimitry Andric Entry->operator=(nullptr); 11690b57cec5SDimitry Andric break; 11700b57cec5SDimitry Andric case Callback: 11710b57cec5SDimitry Andric // Forward to the subclass's implementation. 11720b57cec5SDimitry Andric static_cast<CallbackVH*>(Entry)->deleted(); 11730b57cec5SDimitry Andric break; 11740b57cec5SDimitry Andric } 11750b57cec5SDimitry Andric } 11760b57cec5SDimitry Andric 11770b57cec5SDimitry Andric // All callbacks, weak references, and assertingVHs should be dropped by now. 11780b57cec5SDimitry Andric if (V->HasValueHandle) { 11790b57cec5SDimitry Andric #ifndef NDEBUG // Only in +Asserts mode... 11800b57cec5SDimitry Andric dbgs() << "While deleting: " << *V->getType() << " %" << V->getName() 11810b57cec5SDimitry Andric << "\n"; 11820b57cec5SDimitry Andric if (pImpl->ValueHandles[V]->getKind() == Assert) 11830b57cec5SDimitry Andric llvm_unreachable("An asserting value handle still pointed to this" 11840b57cec5SDimitry Andric " value!"); 11850b57cec5SDimitry Andric 11860b57cec5SDimitry Andric #endif 11870b57cec5SDimitry Andric llvm_unreachable("All references to V were not removed?"); 11880b57cec5SDimitry Andric } 11890b57cec5SDimitry Andric } 11900b57cec5SDimitry Andric 11910b57cec5SDimitry Andric void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) { 11920b57cec5SDimitry Andric assert(Old->HasValueHandle &&"Should only be called if ValueHandles present"); 11930b57cec5SDimitry Andric assert(Old != New && "Changing value into itself!"); 11940b57cec5SDimitry Andric assert(Old->getType() == New->getType() && 11950b57cec5SDimitry Andric "replaceAllUses of value with new value of different type!"); 11960b57cec5SDimitry Andric 11970b57cec5SDimitry Andric // Get the linked list base, which is guaranteed to exist since the 11980b57cec5SDimitry Andric // HasValueHandle flag is set. 11990b57cec5SDimitry Andric LLVMContextImpl *pImpl = Old->getContext().pImpl; 12000b57cec5SDimitry Andric ValueHandleBase *Entry = pImpl->ValueHandles[Old]; 12010b57cec5SDimitry Andric 12020b57cec5SDimitry Andric assert(Entry && "Value bit set but no entries exist"); 12030b57cec5SDimitry Andric 12040b57cec5SDimitry Andric // We use a local ValueHandleBase as an iterator so that 12050b57cec5SDimitry Andric // ValueHandles can add and remove themselves from the list without 12060b57cec5SDimitry Andric // breaking our iteration. This is not really an AssertingVH; we 12070b57cec5SDimitry Andric // just have to give ValueHandleBase some kind. 12080b57cec5SDimitry Andric for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 12090b57cec5SDimitry Andric Iterator.RemoveFromUseList(); 12100b57cec5SDimitry Andric Iterator.AddToExistingUseListAfter(Entry); 12110b57cec5SDimitry Andric assert(Entry->Next == &Iterator && "Loop invariant broken."); 12120b57cec5SDimitry Andric 12130b57cec5SDimitry Andric switch (Entry->getKind()) { 12140b57cec5SDimitry Andric case Assert: 12150b57cec5SDimitry Andric case Weak: 12160b57cec5SDimitry Andric // Asserting and Weak handles do not follow RAUW implicitly. 12170b57cec5SDimitry Andric break; 12180b57cec5SDimitry Andric case WeakTracking: 12190b57cec5SDimitry Andric // Weak goes to the new value, which will unlink it from Old's list. 12200b57cec5SDimitry Andric Entry->operator=(New); 12210b57cec5SDimitry Andric break; 12220b57cec5SDimitry Andric case Callback: 12230b57cec5SDimitry Andric // Forward to the subclass's implementation. 12240b57cec5SDimitry Andric static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New); 12250b57cec5SDimitry Andric break; 12260b57cec5SDimitry Andric } 12270b57cec5SDimitry Andric } 12280b57cec5SDimitry Andric 12290b57cec5SDimitry Andric #ifndef NDEBUG 12300b57cec5SDimitry Andric // If any new weak value handles were added while processing the 12310b57cec5SDimitry Andric // list, then complain about it now. 12320b57cec5SDimitry Andric if (Old->HasValueHandle) 12330b57cec5SDimitry Andric for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next) 12340b57cec5SDimitry Andric switch (Entry->getKind()) { 12350b57cec5SDimitry Andric case WeakTracking: 12360b57cec5SDimitry Andric dbgs() << "After RAUW from " << *Old->getType() << " %" 12370b57cec5SDimitry Andric << Old->getName() << " to " << *New->getType() << " %" 12380b57cec5SDimitry Andric << New->getName() << "\n"; 12390b57cec5SDimitry Andric llvm_unreachable( 12400b57cec5SDimitry Andric "A weak tracking value handle still pointed to the old value!\n"); 12410b57cec5SDimitry Andric default: 12420b57cec5SDimitry Andric break; 12430b57cec5SDimitry Andric } 12440b57cec5SDimitry Andric #endif 12450b57cec5SDimitry Andric } 12460b57cec5SDimitry Andric 12470b57cec5SDimitry Andric // Pin the vtable to this file. 12480b57cec5SDimitry Andric void CallbackVH::anchor() {} 1249