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"
16480093f4SDimitry Andric #include "llvm/ADT/SmallString.h"
170b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
180b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
190b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
20fe6060f1SDimitry Andric #include "llvm/IR/DebugInfo.h"
210b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
220b57cec5SDimitry Andric #include "llvm/IR/DerivedUser.h"
2306c3fb27SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
240b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
250b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
260b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
270b57cec5SDimitry Andric #include "llvm/IR/Module.h"
280b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
29bdd1243dSDimitry Andric #include "llvm/IR/TypedPointerType.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/ErrorHandling.h"
340b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
350b57cec5SDimitry Andric #include <algorithm>
360b57cec5SDimitry Andric
370b57cec5SDimitry Andric using namespace llvm;
380b57cec5SDimitry Andric
39fe6060f1SDimitry Andric static cl::opt<unsigned> UseDerefAtPointSemantics(
40fe6060f1SDimitry Andric "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false),
41fe6060f1SDimitry Andric cl::desc("Deref attributes and metadata infer facts at definition only"));
420b57cec5SDimitry Andric
430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
440b57cec5SDimitry Andric // Value Class
450b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
checkType(Type * Ty)460b57cec5SDimitry Andric static inline Type *checkType(Type *Ty) {
470b57cec5SDimitry Andric assert(Ty && "Value defined with a null type: Error!");
48bdd1243dSDimitry Andric assert(!isa<TypedPointerType>(Ty->getScalarType()) &&
49bdd1243dSDimitry Andric "Cannot have values with typed pointer types");
500b57cec5SDimitry Andric return Ty;
510b57cec5SDimitry Andric }
520b57cec5SDimitry Andric
Value(Type * ty,unsigned scid)530b57cec5SDimitry Andric Value::Value(Type *ty, unsigned scid)
547a6dacacSDimitry Andric : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0),
557a6dacacSDimitry Andric SubclassData(0), NumUserOperands(0), IsUsedByMD(false), HasName(false),
567a6dacacSDimitry Andric HasMetadata(false), VTy(checkType(ty)), UseList(nullptr) {
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
~Value()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
deleteValue()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
destroyValueName()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
hasNUses(unsigned N) const1490b57cec5SDimitry Andric bool Value::hasNUses(unsigned N) const {
1500b57cec5SDimitry Andric return hasNItems(use_begin(), use_end(), N);
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric
hasNUsesOrMore(unsigned N) const1530b57cec5SDimitry Andric bool Value::hasNUsesOrMore(unsigned N) const {
1540b57cec5SDimitry Andric return hasNItemsOrMore(use_begin(), use_end(), N);
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric
hasOneUser() const157e8d8bef9SDimitry 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
isUnDroppableUser(const User * U)1655ffd83dbSDimitry Andric static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
1665ffd83dbSDimitry Andric
getSingleUndroppableUse()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
getUniqueUndroppableUser()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
hasNUndroppableUses(unsigned int N) const1915ffd83dbSDimitry Andric bool Value::hasNUndroppableUses(unsigned int N) const {
1925ffd83dbSDimitry Andric return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
1935ffd83dbSDimitry Andric }
1945ffd83dbSDimitry Andric
hasNUndroppableUsesOrMore(unsigned int N) const1955ffd83dbSDimitry Andric bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
1965ffd83dbSDimitry Andric return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
1975ffd83dbSDimitry Andric }
1985ffd83dbSDimitry Andric
dropDroppableUses(llvm::function_ref<bool (const Use *)> ShouldDrop)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
dropDroppableUsesIn(User & Usr)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
dropDroppableUse(Use & U)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
isUsedInBasicBlock(const BasicBlock * BB) const2340b57cec5SDimitry 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
getNumUses() const2550b57cec5SDimitry Andric unsigned Value::getNumUses() const {
2560b57cec5SDimitry Andric return (unsigned)std::distance(use_begin(), use_end());
2570b57cec5SDimitry Andric }
2580b57cec5SDimitry Andric
getSymTab(Value * V,ValueSymbolTable * & ST)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
getValueName() const2810b57cec5SDimitry 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
setValueName(ValueName * VN)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
getName() const3090b57cec5SDimitry 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
setNameImpl(const Twine & NewName)3180b57cec5SDimitry Andric void Value::setNameImpl(const Twine &NewName) {
31906c3fb27SDimitry Andric bool NeedNewName =
32006c3fb27SDimitry Andric !getContext().shouldDiscardValueNames() || isa<GlobalValue>(this);
32106c3fb27SDimitry Andric
3220b57cec5SDimitry Andric // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
32306c3fb27SDimitry Andric // and there is no need to delete the old name.
32406c3fb27SDimitry Andric if (!NeedNewName && !hasName())
3250b57cec5SDimitry Andric return;
3260b57cec5SDimitry Andric
3270b57cec5SDimitry Andric // Fast path for common IRBuilder case of setName("") when there is no name.
3280b57cec5SDimitry Andric if (NewName.isTriviallyEmpty() && !hasName())
3290b57cec5SDimitry Andric return;
3300b57cec5SDimitry Andric
3310b57cec5SDimitry Andric SmallString<256> NameData;
33206c3fb27SDimitry Andric StringRef NameRef = NeedNewName ? NewName.toStringRef(NameData) : "";
3335f757f3fSDimitry Andric assert(!NameRef.contains(0) && "Null bytes are not allowed in names");
3340b57cec5SDimitry Andric
3350b57cec5SDimitry Andric // Name isn't changing?
3360b57cec5SDimitry Andric if (getName() == NameRef)
3370b57cec5SDimitry Andric return;
3380b57cec5SDimitry Andric
3390b57cec5SDimitry Andric assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
3400b57cec5SDimitry Andric
3410b57cec5SDimitry Andric // Get the symbol table to update for this object.
3420b57cec5SDimitry Andric ValueSymbolTable *ST;
3430b57cec5SDimitry Andric if (getSymTab(this, ST))
3440b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant).
3450b57cec5SDimitry Andric
3460b57cec5SDimitry Andric if (!ST) { // No symbol table to update? Just do the change.
3470b57cec5SDimitry Andric // NOTE: Could optimize for the case the name is shrinking to not deallocate
3480b57cec5SDimitry Andric // then reallocated.
3490b57cec5SDimitry Andric destroyValueName();
3500b57cec5SDimitry Andric
35106c3fb27SDimitry Andric if (!NameRef.empty()) {
3520b57cec5SDimitry Andric // Create the new name.
35306c3fb27SDimitry Andric assert(NeedNewName);
3545ffd83dbSDimitry Andric MallocAllocator Allocator;
355bdd1243dSDimitry Andric setValueName(ValueName::create(NameRef, Allocator));
3560b57cec5SDimitry Andric getValueName()->setValue(this);
35706c3fb27SDimitry Andric }
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.
37306c3fb27SDimitry Andric assert(NeedNewName);
3740b57cec5SDimitry Andric setValueName(ST->createValueName(NameRef, this));
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric
setName(const Twine & NewName)3770b57cec5SDimitry Andric void Value::setName(const Twine &NewName) {
3780b57cec5SDimitry Andric setNameImpl(NewName);
3790b57cec5SDimitry Andric if (Function *F = dyn_cast<Function>(this))
3805f757f3fSDimitry Andric F->updateAfterNameChange();
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric
takeName(Value * V)3830b57cec5SDimitry Andric void Value::takeName(Value *V) {
38481ad6265SDimitry Andric assert(V != this && "Illegal call to this->takeName(this)!");
3850b57cec5SDimitry Andric ValueSymbolTable *ST = nullptr;
3860b57cec5SDimitry Andric // If this value has a name, drop it.
3870b57cec5SDimitry Andric if (hasName()) {
3880b57cec5SDimitry Andric // Get the symtab this is in.
3890b57cec5SDimitry Andric if (getSymTab(this, ST)) {
3900b57cec5SDimitry Andric // We can't set a name on this value, but we need to clear V's name if
3910b57cec5SDimitry Andric // it has one.
3920b57cec5SDimitry Andric if (V->hasName()) V->setName("");
3930b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant).
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric
3960b57cec5SDimitry Andric // Remove old name.
3970b57cec5SDimitry Andric if (ST)
3980b57cec5SDimitry Andric ST->removeValueName(getValueName());
3990b57cec5SDimitry Andric destroyValueName();
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric
4020b57cec5SDimitry Andric // Now we know that this has no name.
4030b57cec5SDimitry Andric
4040b57cec5SDimitry Andric // If V has no name either, we're done.
4050b57cec5SDimitry Andric if (!V->hasName()) return;
4060b57cec5SDimitry Andric
4070b57cec5SDimitry Andric // Get this's symtab if we didn't before.
4080b57cec5SDimitry Andric if (!ST) {
4090b57cec5SDimitry Andric if (getSymTab(this, ST)) {
4100b57cec5SDimitry Andric // Clear V's name.
4110b57cec5SDimitry Andric V->setName("");
4120b57cec5SDimitry Andric return; // Cannot set a name on this value (e.g. constant).
4130b57cec5SDimitry Andric }
4140b57cec5SDimitry Andric }
4150b57cec5SDimitry Andric
41681ad6265SDimitry Andric // Get V's ST, this should always succeed, because V has a name.
4170b57cec5SDimitry Andric ValueSymbolTable *VST;
4180b57cec5SDimitry Andric bool Failure = getSymTab(V, VST);
4190b57cec5SDimitry Andric assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
4200b57cec5SDimitry Andric
4210b57cec5SDimitry Andric // If these values are both in the same symtab, we can do this very fast.
4220b57cec5SDimitry Andric // This works even if both values have no symtab yet.
4230b57cec5SDimitry Andric if (ST == VST) {
4240b57cec5SDimitry Andric // Take the name!
4250b57cec5SDimitry Andric setValueName(V->getValueName());
4260b57cec5SDimitry Andric V->setValueName(nullptr);
4270b57cec5SDimitry Andric getValueName()->setValue(this);
4280b57cec5SDimitry Andric return;
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric
4310b57cec5SDimitry Andric // Otherwise, things are slightly more complex. Remove V's name from VST and
4320b57cec5SDimitry Andric // then reinsert it into ST.
4330b57cec5SDimitry Andric
4340b57cec5SDimitry Andric if (VST)
4350b57cec5SDimitry Andric VST->removeValueName(V->getValueName());
4360b57cec5SDimitry Andric setValueName(V->getValueName());
4370b57cec5SDimitry Andric V->setValueName(nullptr);
4380b57cec5SDimitry Andric getValueName()->setValue(this);
4390b57cec5SDimitry Andric
4400b57cec5SDimitry Andric if (ST)
4410b57cec5SDimitry Andric ST->reinsertValue(this);
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric
444e8d8bef9SDimitry Andric #ifndef NDEBUG
getNameOrAsOperand() const445e8d8bef9SDimitry Andric std::string Value::getNameOrAsOperand() const {
446e8d8bef9SDimitry Andric if (!getName().empty())
447e8d8bef9SDimitry Andric return std::string(getName());
448e8d8bef9SDimitry Andric
449e8d8bef9SDimitry Andric std::string BBName;
450e8d8bef9SDimitry Andric raw_string_ostream OS(BBName);
451e8d8bef9SDimitry Andric printAsOperand(OS, false);
452e8d8bef9SDimitry Andric return OS.str();
453e8d8bef9SDimitry Andric }
454e8d8bef9SDimitry Andric #endif
455e8d8bef9SDimitry Andric
assertModuleIsMaterializedImpl() const4560b57cec5SDimitry Andric void Value::assertModuleIsMaterializedImpl() const {
4570b57cec5SDimitry Andric #ifndef NDEBUG
4580b57cec5SDimitry Andric const GlobalValue *GV = dyn_cast<GlobalValue>(this);
4590b57cec5SDimitry Andric if (!GV)
4600b57cec5SDimitry Andric return;
4610b57cec5SDimitry Andric const Module *M = GV->getParent();
4620b57cec5SDimitry Andric if (!M)
4630b57cec5SDimitry Andric return;
4640b57cec5SDimitry Andric assert(M->isMaterialized());
4650b57cec5SDimitry Andric #endif
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric
4680b57cec5SDimitry Andric #ifndef NDEBUG
contains(SmallPtrSetImpl<ConstantExpr * > & Cache,ConstantExpr * Expr,Constant * C)4690b57cec5SDimitry Andric static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
4700b57cec5SDimitry Andric Constant *C) {
4710b57cec5SDimitry Andric if (!Cache.insert(Expr).second)
4720b57cec5SDimitry Andric return false;
4730b57cec5SDimitry Andric
4740b57cec5SDimitry Andric for (auto &O : Expr->operands()) {
4750b57cec5SDimitry Andric if (O == C)
4760b57cec5SDimitry Andric return true;
4770b57cec5SDimitry Andric auto *CE = dyn_cast<ConstantExpr>(O);
4780b57cec5SDimitry Andric if (!CE)
4790b57cec5SDimitry Andric continue;
4800b57cec5SDimitry Andric if (contains(Cache, CE, C))
4810b57cec5SDimitry Andric return true;
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric return false;
4840b57cec5SDimitry Andric }
4850b57cec5SDimitry Andric
contains(Value * Expr,Value * V)4860b57cec5SDimitry Andric static bool contains(Value *Expr, Value *V) {
4870b57cec5SDimitry Andric if (Expr == V)
4880b57cec5SDimitry Andric return true;
4890b57cec5SDimitry Andric
4900b57cec5SDimitry Andric auto *C = dyn_cast<Constant>(V);
4910b57cec5SDimitry Andric if (!C)
4920b57cec5SDimitry Andric return false;
4930b57cec5SDimitry Andric
4940b57cec5SDimitry Andric auto *CE = dyn_cast<ConstantExpr>(Expr);
4950b57cec5SDimitry Andric if (!CE)
4960b57cec5SDimitry Andric return false;
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric SmallPtrSet<ConstantExpr *, 4> Cache;
4990b57cec5SDimitry Andric return contains(Cache, CE, C);
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric #endif // NDEBUG
5020b57cec5SDimitry Andric
doRAUW(Value * New,ReplaceMetadataUses ReplaceMetaUses)5030b57cec5SDimitry Andric void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
5040b57cec5SDimitry Andric assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
5050b57cec5SDimitry Andric assert(!contains(New, this) &&
5060b57cec5SDimitry Andric "this->replaceAllUsesWith(expr(this)) is NOT valid!");
5070b57cec5SDimitry Andric assert(New->getType() == getType() &&
5080b57cec5SDimitry Andric "replaceAllUses of value with new value of different type!");
5090b57cec5SDimitry Andric
5100b57cec5SDimitry Andric // Notify all ValueHandles (if present) that this value is going away.
5110b57cec5SDimitry Andric if (HasValueHandle)
5120b57cec5SDimitry Andric ValueHandleBase::ValueIsRAUWd(this, New);
5130b57cec5SDimitry Andric if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
5140b57cec5SDimitry Andric ValueAsMetadata::handleRAUW(this, New);
5150b57cec5SDimitry Andric
5160b57cec5SDimitry Andric while (!materialized_use_empty()) {
5170b57cec5SDimitry Andric Use &U = *UseList;
5180b57cec5SDimitry Andric // Must handle Constants specially, we cannot call replaceUsesOfWith on a
5190b57cec5SDimitry Andric // constant because they are uniqued.
5200b57cec5SDimitry Andric if (auto *C = dyn_cast<Constant>(U.getUser())) {
5210b57cec5SDimitry Andric if (!isa<GlobalValue>(C)) {
5220b57cec5SDimitry Andric C->handleOperandChange(this, New);
5230b57cec5SDimitry Andric continue;
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric
5270b57cec5SDimitry Andric U.set(New);
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric
5300b57cec5SDimitry Andric if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
5310b57cec5SDimitry Andric BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
5320b57cec5SDimitry Andric }
5330b57cec5SDimitry Andric
replaceAllUsesWith(Value * New)5340b57cec5SDimitry Andric void Value::replaceAllUsesWith(Value *New) {
5350b57cec5SDimitry Andric doRAUW(New, ReplaceMetadataUses::Yes);
5360b57cec5SDimitry Andric }
5370b57cec5SDimitry Andric
replaceNonMetadataUsesWith(Value * New)5380b57cec5SDimitry Andric void Value::replaceNonMetadataUsesWith(Value *New) {
5390b57cec5SDimitry Andric doRAUW(New, ReplaceMetadataUses::No);
5400b57cec5SDimitry Andric }
5410b57cec5SDimitry Andric
replaceUsesWithIf(Value * New,llvm::function_ref<bool (Use & U)> ShouldReplace)542fe6060f1SDimitry Andric void Value::replaceUsesWithIf(Value *New,
543fe6060f1SDimitry Andric llvm::function_ref<bool(Use &U)> ShouldReplace) {
544fe6060f1SDimitry Andric assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
545fe6060f1SDimitry Andric assert(New->getType() == getType() &&
546fe6060f1SDimitry Andric "replaceUses of value with new value of different type!");
547fe6060f1SDimitry Andric
548fe6060f1SDimitry Andric SmallVector<TrackingVH<Constant>, 8> Consts;
549fe6060f1SDimitry Andric SmallPtrSet<Constant *, 8> Visited;
550fe6060f1SDimitry Andric
551349cc55cSDimitry Andric for (Use &U : llvm::make_early_inc_range(uses())) {
552fe6060f1SDimitry Andric if (!ShouldReplace(U))
553fe6060f1SDimitry Andric continue;
554fe6060f1SDimitry Andric // Must handle Constants specially, we cannot call replaceUsesOfWith on a
555fe6060f1SDimitry Andric // constant because they are uniqued.
556fe6060f1SDimitry Andric if (auto *C = dyn_cast<Constant>(U.getUser())) {
557fe6060f1SDimitry Andric if (!isa<GlobalValue>(C)) {
558fe6060f1SDimitry Andric if (Visited.insert(C).second)
559fe6060f1SDimitry Andric Consts.push_back(TrackingVH<Constant>(C));
560fe6060f1SDimitry Andric continue;
561fe6060f1SDimitry Andric }
562fe6060f1SDimitry Andric }
563fe6060f1SDimitry Andric U.set(New);
564fe6060f1SDimitry Andric }
565fe6060f1SDimitry Andric
566fe6060f1SDimitry Andric while (!Consts.empty()) {
567fe6060f1SDimitry Andric // FIXME: handleOperandChange() updates all the uses in a given Constant,
568fe6060f1SDimitry Andric // not just the one passed to ShouldReplace
569fe6060f1SDimitry Andric Consts.pop_back_val()->handleOperandChange(this, New);
570fe6060f1SDimitry Andric }
571fe6060f1SDimitry Andric }
572fe6060f1SDimitry Andric
573fe6060f1SDimitry Andric /// Replace llvm.dbg.* uses of MetadataAsValue(ValueAsMetadata(V)) outside BB
574fe6060f1SDimitry Andric /// with New.
replaceDbgUsesOutsideBlock(Value * V,Value * New,BasicBlock * BB)575fe6060f1SDimitry Andric static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) {
576fe6060f1SDimitry Andric SmallVector<DbgVariableIntrinsic *> DbgUsers;
577*0fca6ea1SDimitry Andric SmallVector<DbgVariableRecord *> DPUsers;
5785f757f3fSDimitry Andric findDbgUsers(DbgUsers, V, &DPUsers);
579fe6060f1SDimitry Andric for (auto *DVI : DbgUsers) {
580fe6060f1SDimitry Andric if (DVI->getParent() != BB)
581fe6060f1SDimitry Andric DVI->replaceVariableLocationOp(V, New);
582fe6060f1SDimitry Andric }
583*0fca6ea1SDimitry Andric for (auto *DVR : DPUsers) {
584*0fca6ea1SDimitry Andric DbgMarker *Marker = DVR->getMarker();
5855f757f3fSDimitry Andric if (Marker->getParent() != BB)
586*0fca6ea1SDimitry Andric DVR->replaceVariableLocationOp(V, New);
5875f757f3fSDimitry Andric }
588fe6060f1SDimitry Andric }
589fe6060f1SDimitry Andric
5900b57cec5SDimitry Andric // Like replaceAllUsesWith except it does not handle constants or basic blocks.
5910b57cec5SDimitry Andric // This routine leaves uses within BB.
replaceUsesOutsideBlock(Value * New,BasicBlock * BB)5920b57cec5SDimitry Andric void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
5930b57cec5SDimitry Andric assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
5940b57cec5SDimitry Andric assert(!contains(New, this) &&
5950b57cec5SDimitry Andric "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
5960b57cec5SDimitry Andric assert(New->getType() == getType() &&
5970b57cec5SDimitry Andric "replaceUses of value with new value of different type!");
5980b57cec5SDimitry Andric assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
5990b57cec5SDimitry Andric
600fe6060f1SDimitry Andric replaceDbgUsesOutsideBlock(this, New, BB);
6018bcb0991SDimitry Andric replaceUsesWithIf(New, [BB](Use &U) {
6028bcb0991SDimitry Andric auto *I = dyn_cast<Instruction>(U.getUser());
6038bcb0991SDimitry Andric // Don't replace if it's an instruction in the BB basic block.
6048bcb0991SDimitry Andric return !I || I->getParent() != BB;
6058bcb0991SDimitry Andric });
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric
6080b57cec5SDimitry Andric namespace {
6090b57cec5SDimitry Andric // Various metrics for how much to strip off of pointers.
6100b57cec5SDimitry Andric enum PointerStripKind {
6110b57cec5SDimitry Andric PSK_ZeroIndices,
6120b57cec5SDimitry Andric PSK_ZeroIndicesAndAliases,
6138bcb0991SDimitry Andric PSK_ZeroIndicesSameRepresentation,
614fe6060f1SDimitry Andric PSK_ForAliasAnalysis,
6150b57cec5SDimitry Andric PSK_InBoundsConstantIndices,
6160b57cec5SDimitry Andric PSK_InBounds
6170b57cec5SDimitry Andric };
6180b57cec5SDimitry Andric
NoopCallback(const Value *)6195ffd83dbSDimitry Andric template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
6205ffd83dbSDimitry Andric
6210b57cec5SDimitry Andric template <PointerStripKind StripKind>
stripPointerCastsAndOffsets(const Value * V,function_ref<void (const Value *)> Func=NoopCallback<StripKind>)6225ffd83dbSDimitry Andric static const Value *stripPointerCastsAndOffsets(
6235ffd83dbSDimitry Andric const Value *V,
6245ffd83dbSDimitry Andric function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
6250b57cec5SDimitry Andric if (!V->getType()->isPointerTy())
6260b57cec5SDimitry Andric return V;
6270b57cec5SDimitry Andric
6280b57cec5SDimitry Andric // Even though we don't look through PHI nodes, we could be called on an
6290b57cec5SDimitry Andric // instruction in an unreachable block, which may be on a cycle.
6300b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> Visited;
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric Visited.insert(V);
6330b57cec5SDimitry Andric do {
6345ffd83dbSDimitry Andric Func(V);
6350b57cec5SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(V)) {
6360b57cec5SDimitry Andric switch (StripKind) {
6370b57cec5SDimitry Andric case PSK_ZeroIndices:
6388bcb0991SDimitry Andric case PSK_ZeroIndicesAndAliases:
6398bcb0991SDimitry Andric case PSK_ZeroIndicesSameRepresentation:
640fe6060f1SDimitry Andric case PSK_ForAliasAnalysis:
6410b57cec5SDimitry Andric if (!GEP->hasAllZeroIndices())
6420b57cec5SDimitry Andric return V;
6430b57cec5SDimitry Andric break;
6440b57cec5SDimitry Andric case PSK_InBoundsConstantIndices:
6450b57cec5SDimitry Andric if (!GEP->hasAllConstantIndices())
6460b57cec5SDimitry Andric return V;
647bdd1243dSDimitry Andric [[fallthrough]];
6480b57cec5SDimitry Andric case PSK_InBounds:
6490b57cec5SDimitry Andric if (!GEP->isInBounds())
6500b57cec5SDimitry Andric return V;
6510b57cec5SDimitry Andric break;
6520b57cec5SDimitry Andric }
6530b57cec5SDimitry Andric V = GEP->getPointerOperand();
6540b57cec5SDimitry Andric } else if (Operator::getOpcode(V) == Instruction::BitCast) {
655*0fca6ea1SDimitry Andric Value *NewV = cast<Operator>(V)->getOperand(0);
656*0fca6ea1SDimitry Andric if (!NewV->getType()->isPointerTy())
6575ffd83dbSDimitry Andric return V;
658*0fca6ea1SDimitry Andric V = NewV;
6598bcb0991SDimitry Andric } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
6600b57cec5SDimitry Andric Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
6610b57cec5SDimitry Andric // TODO: If we know an address space cast will not change the
6620b57cec5SDimitry Andric // representation we could look through it here as well.
6630b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0);
6648bcb0991SDimitry Andric } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
6658bcb0991SDimitry Andric V = cast<GlobalAlias>(V)->getAliasee();
666fe6060f1SDimitry Andric } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) &&
667fe6060f1SDimitry Andric cast<PHINode>(V)->getNumIncomingValues() == 1) {
668fe6060f1SDimitry Andric V = cast<PHINode>(V)->getIncomingValue(0);
6690b57cec5SDimitry Andric } else {
6700b57cec5SDimitry Andric if (const auto *Call = dyn_cast<CallBase>(V)) {
6710b57cec5SDimitry Andric if (const Value *RV = Call->getReturnedArgOperand()) {
6720b57cec5SDimitry Andric V = RV;
6730b57cec5SDimitry Andric continue;
6740b57cec5SDimitry Andric }
6750b57cec5SDimitry Andric // The result of launder.invariant.group must alias it's argument,
6760b57cec5SDimitry Andric // but it can't be marked with returned attribute, that's why it needs
6770b57cec5SDimitry Andric // special case.
678fe6060f1SDimitry Andric if (StripKind == PSK_ForAliasAnalysis &&
6790b57cec5SDimitry Andric (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
6800b57cec5SDimitry Andric Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
6810b57cec5SDimitry Andric V = Call->getArgOperand(0);
6820b57cec5SDimitry Andric continue;
6830b57cec5SDimitry Andric }
6840b57cec5SDimitry Andric }
6850b57cec5SDimitry Andric return V;
6860b57cec5SDimitry Andric }
6870b57cec5SDimitry Andric assert(V->getType()->isPointerTy() && "Unexpected operand type!");
6880b57cec5SDimitry Andric } while (Visited.insert(V).second);
6890b57cec5SDimitry Andric
6900b57cec5SDimitry Andric return V;
6910b57cec5SDimitry Andric }
6920b57cec5SDimitry Andric } // end anonymous namespace
6930b57cec5SDimitry Andric
stripPointerCasts() const6940b57cec5SDimitry Andric const Value *Value::stripPointerCasts() const {
6958bcb0991SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
6968bcb0991SDimitry Andric }
6978bcb0991SDimitry Andric
stripPointerCastsAndAliases() const6988bcb0991SDimitry Andric const Value *Value::stripPointerCastsAndAliases() const {
6990b57cec5SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
7000b57cec5SDimitry Andric }
7010b57cec5SDimitry Andric
stripPointerCastsSameRepresentation() const7020b57cec5SDimitry Andric const Value *Value::stripPointerCastsSameRepresentation() const {
7038bcb0991SDimitry Andric return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
7040b57cec5SDimitry Andric }
7050b57cec5SDimitry Andric
stripInBoundsConstantOffsets() const7060b57cec5SDimitry Andric const Value *Value::stripInBoundsConstantOffsets() const {
7070b57cec5SDimitry Andric return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
7080b57cec5SDimitry Andric }
7090b57cec5SDimitry Andric
stripPointerCastsForAliasAnalysis() const710fe6060f1SDimitry Andric const Value *Value::stripPointerCastsForAliasAnalysis() const {
711fe6060f1SDimitry Andric return stripPointerCastsAndOffsets<PSK_ForAliasAnalysis>(this);
7120b57cec5SDimitry Andric }
7130b57cec5SDimitry Andric
stripAndAccumulateConstantOffsets(const DataLayout & DL,APInt & Offset,bool AllowNonInbounds,bool AllowInvariantGroup,function_ref<bool (Value &,APInt &)> ExternalAnalysis) const7145ffd83dbSDimitry Andric const Value *Value::stripAndAccumulateConstantOffsets(
7155ffd83dbSDimitry Andric const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
716349cc55cSDimitry Andric bool AllowInvariantGroup,
7175ffd83dbSDimitry Andric function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
7180b57cec5SDimitry Andric if (!getType()->isPtrOrPtrVectorTy())
7190b57cec5SDimitry Andric return this;
7200b57cec5SDimitry Andric
7210b57cec5SDimitry Andric unsigned BitWidth = Offset.getBitWidth();
7220b57cec5SDimitry Andric assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
7230b57cec5SDimitry Andric "The offset bit width does not match the DL specification.");
7240b57cec5SDimitry Andric
7250b57cec5SDimitry Andric // Even though we don't look through PHI nodes, we could be called on an
7260b57cec5SDimitry Andric // instruction in an unreachable block, which may be on a cycle.
7270b57cec5SDimitry Andric SmallPtrSet<const Value *, 4> Visited;
7280b57cec5SDimitry Andric Visited.insert(this);
7290b57cec5SDimitry Andric const Value *V = this;
7300b57cec5SDimitry Andric do {
7310b57cec5SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7320b57cec5SDimitry Andric // If in-bounds was requested, we do not strip non-in-bounds GEPs.
7330b57cec5SDimitry Andric if (!AllowNonInbounds && !GEP->isInBounds())
7340b57cec5SDimitry Andric return V;
7350b57cec5SDimitry Andric
7360b57cec5SDimitry Andric // If one of the values we have visited is an addrspacecast, then
7370b57cec5SDimitry Andric // the pointer type of this GEP may be different from the type
7380b57cec5SDimitry Andric // of the Ptr parameter which was passed to this function. This
7390b57cec5SDimitry Andric // means when we construct GEPOffset, we need to use the size
7400b57cec5SDimitry Andric // of GEP's pointer type rather than the size of the original
7410b57cec5SDimitry Andric // pointer type.
7420b57cec5SDimitry Andric APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
7435ffd83dbSDimitry Andric if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
7440b57cec5SDimitry Andric return V;
7450b57cec5SDimitry Andric
7460b57cec5SDimitry Andric // Stop traversal if the pointer offset wouldn't fit in the bit-width
7470b57cec5SDimitry Andric // provided by the Offset argument. This can happen due to AddrSpaceCast
7480b57cec5SDimitry Andric // stripping.
74906c3fb27SDimitry Andric if (GEPOffset.getSignificantBits() > BitWidth)
7500b57cec5SDimitry Andric return V;
7510b57cec5SDimitry Andric
7525ffd83dbSDimitry Andric // External Analysis can return a result higher/lower than the value
7535ffd83dbSDimitry Andric // represents. We need to detect overflow/underflow.
7545ffd83dbSDimitry Andric APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
7555ffd83dbSDimitry Andric if (!ExternalAnalysis) {
7565ffd83dbSDimitry Andric Offset += GEPOffsetST;
7575ffd83dbSDimitry Andric } else {
7585ffd83dbSDimitry Andric bool Overflow = false;
7595ffd83dbSDimitry Andric APInt OldOffset = Offset;
7605ffd83dbSDimitry Andric Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
7615ffd83dbSDimitry Andric if (Overflow) {
7625ffd83dbSDimitry Andric Offset = OldOffset;
7635ffd83dbSDimitry Andric return V;
7645ffd83dbSDimitry Andric }
7655ffd83dbSDimitry Andric }
7660b57cec5SDimitry Andric V = GEP->getPointerOperand();
7670b57cec5SDimitry Andric } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7680b57cec5SDimitry Andric Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7690b57cec5SDimitry Andric V = cast<Operator>(V)->getOperand(0);
7700b57cec5SDimitry Andric } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7710b57cec5SDimitry Andric if (!GA->isInterposable())
7720b57cec5SDimitry Andric V = GA->getAliasee();
7730b57cec5SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(V)) {
7740b57cec5SDimitry Andric if (const Value *RV = Call->getReturnedArgOperand())
7750b57cec5SDimitry Andric V = RV;
776349cc55cSDimitry Andric if (AllowInvariantGroup && Call->isLaunderOrStripInvariantGroup())
777349cc55cSDimitry Andric V = Call->getArgOperand(0);
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
7800b57cec5SDimitry Andric } while (Visited.insert(V).second);
7810b57cec5SDimitry Andric
7820b57cec5SDimitry Andric return V;
7830b57cec5SDimitry Andric }
7840b57cec5SDimitry Andric
7855ffd83dbSDimitry Andric const Value *
stripInBoundsOffsets(function_ref<void (const Value *)> Func) const7865ffd83dbSDimitry Andric Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
7875ffd83dbSDimitry Andric return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func);
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric
canBeFreed() const790fe6060f1SDimitry Andric bool Value::canBeFreed() const {
791fe6060f1SDimitry Andric assert(getType()->isPointerTy());
792fe6060f1SDimitry Andric
793fe6060f1SDimitry Andric // Cases that can simply never be deallocated
794fe6060f1SDimitry Andric // *) Constants aren't allocated per se, thus not deallocated either.
795fe6060f1SDimitry Andric if (isa<Constant>(this))
796fe6060f1SDimitry Andric return false;
797fe6060f1SDimitry Andric
798fe6060f1SDimitry Andric // Handle byval/byref/sret/inalloca/preallocated arguments. The storage
799fe6060f1SDimitry Andric // lifetime is guaranteed to be longer than the callee's lifetime.
800fe6060f1SDimitry Andric if (auto *A = dyn_cast<Argument>(this)) {
801fe6060f1SDimitry Andric if (A->hasPointeeInMemoryValueAttr())
802fe6060f1SDimitry Andric return false;
803fe6060f1SDimitry Andric // A pointer to an object in a function which neither frees, nor can arrange
804fe6060f1SDimitry Andric // for another thread to free on its behalf, can not be freed in the scope
805fe6060f1SDimitry Andric // of the function. Note that this logic is restricted to memory
806fe6060f1SDimitry Andric // allocations in existance before the call; a nofree function *is* allowed
807fe6060f1SDimitry Andric // to free memory it allocated.
808fe6060f1SDimitry Andric const Function *F = A->getParent();
809fe6060f1SDimitry Andric if (F->doesNotFreeMemory() && F->hasNoSync())
810fe6060f1SDimitry Andric return false;
811fe6060f1SDimitry Andric }
812fe6060f1SDimitry Andric
813fe6060f1SDimitry Andric const Function *F = nullptr;
814fe6060f1SDimitry Andric if (auto *I = dyn_cast<Instruction>(this))
815fe6060f1SDimitry Andric F = I->getFunction();
816fe6060f1SDimitry Andric if (auto *A = dyn_cast<Argument>(this))
817fe6060f1SDimitry Andric F = A->getParent();
818fe6060f1SDimitry Andric
819fe6060f1SDimitry Andric if (!F)
820fe6060f1SDimitry Andric return true;
821fe6060f1SDimitry Andric
822fe6060f1SDimitry Andric // With garbage collection, deallocation typically occurs solely at or after
823fe6060f1SDimitry Andric // safepoints. If we're compiling for a collector which uses the
824fe6060f1SDimitry Andric // gc.statepoint infrastructure, safepoints aren't explicitly present
825fe6060f1SDimitry Andric // in the IR until after lowering from abstract to physical machine model.
826fe6060f1SDimitry Andric // The collector could chose to mix explicit deallocation and gc'd objects
827fe6060f1SDimitry Andric // which is why we need the explicit opt in on a per collector basis.
828fe6060f1SDimitry Andric if (!F->hasGC())
829fe6060f1SDimitry Andric return true;
830fe6060f1SDimitry Andric
831fe6060f1SDimitry Andric const auto &GCName = F->getGC();
832fe6060f1SDimitry Andric if (GCName == "statepoint-example") {
833fe6060f1SDimitry Andric auto *PT = cast<PointerType>(this->getType());
834fe6060f1SDimitry Andric if (PT->getAddressSpace() != 1)
835fe6060f1SDimitry Andric // For the sake of this example GC, we arbitrarily pick addrspace(1) as
836fe6060f1SDimitry Andric // our GC managed heap. This must match the same check in
837fe6060f1SDimitry Andric // RewriteStatepointsForGC (and probably needs better factored.)
838fe6060f1SDimitry Andric return true;
839fe6060f1SDimitry Andric
840fe6060f1SDimitry Andric // It is cheaper to scan for a declaration than to scan for a use in this
841fe6060f1SDimitry Andric // function. Note that gc.statepoint is a type overloaded function so the
842fe6060f1SDimitry Andric // usual trick of requesting declaration of the intrinsic from the module
843fe6060f1SDimitry Andric // doesn't work.
844fe6060f1SDimitry Andric for (auto &Fn : *F->getParent())
845fe6060f1SDimitry Andric if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
846fe6060f1SDimitry Andric return true;
847fe6060f1SDimitry Andric return false;
848fe6060f1SDimitry Andric }
849fe6060f1SDimitry Andric return true;
850fe6060f1SDimitry Andric }
851fe6060f1SDimitry Andric
getPointerDereferenceableBytes(const DataLayout & DL,bool & CanBeNull,bool & CanBeFreed) const8520b57cec5SDimitry Andric uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
853fe6060f1SDimitry Andric bool &CanBeNull,
854fe6060f1SDimitry Andric bool &CanBeFreed) const {
8550b57cec5SDimitry Andric assert(getType()->isPointerTy() && "must be pointer");
8560b57cec5SDimitry Andric
8570b57cec5SDimitry Andric uint64_t DerefBytes = 0;
8580b57cec5SDimitry Andric CanBeNull = false;
859fe6060f1SDimitry Andric CanBeFreed = UseDerefAtPointSemantics && canBeFreed();
8600b57cec5SDimitry Andric if (const Argument *A = dyn_cast<Argument>(this)) {
8610b57cec5SDimitry Andric DerefBytes = A->getDereferenceableBytes();
862e8d8bef9SDimitry Andric if (DerefBytes == 0) {
863e8d8bef9SDimitry Andric // Handle byval/byref/inalloca/preallocated arguments
864e8d8bef9SDimitry Andric if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) {
865e8d8bef9SDimitry Andric if (ArgMemTy->isSized()) {
866e8d8bef9SDimitry Andric // FIXME: Why isn't this the type alloc size?
867bdd1243dSDimitry Andric DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinValue();
8680b57cec5SDimitry Andric }
869e8d8bef9SDimitry Andric }
870e8d8bef9SDimitry Andric }
871e8d8bef9SDimitry Andric
8720b57cec5SDimitry Andric if (DerefBytes == 0) {
8730b57cec5SDimitry Andric DerefBytes = A->getDereferenceableOrNullBytes();
8740b57cec5SDimitry Andric CanBeNull = true;
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(this)) {
877349cc55cSDimitry Andric DerefBytes = Call->getRetDereferenceableBytes();
8780b57cec5SDimitry Andric if (DerefBytes == 0) {
879349cc55cSDimitry Andric DerefBytes = Call->getRetDereferenceableOrNullBytes();
8800b57cec5SDimitry Andric CanBeNull = true;
8810b57cec5SDimitry Andric }
8820b57cec5SDimitry Andric } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
8830b57cec5SDimitry Andric if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
8840b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
8850b57cec5SDimitry Andric DerefBytes = CI->getLimitedValue();
8860b57cec5SDimitry Andric }
8870b57cec5SDimitry Andric if (DerefBytes == 0) {
8880b57cec5SDimitry Andric if (MDNode *MD =
8890b57cec5SDimitry Andric LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
8900b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
8910b57cec5SDimitry Andric DerefBytes = CI->getLimitedValue();
8920b57cec5SDimitry Andric }
8930b57cec5SDimitry Andric CanBeNull = true;
8940b57cec5SDimitry Andric }
8958bcb0991SDimitry Andric } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
8968bcb0991SDimitry Andric if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
8978bcb0991SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
8988bcb0991SDimitry Andric DerefBytes = CI->getLimitedValue();
8998bcb0991SDimitry Andric }
9008bcb0991SDimitry Andric if (DerefBytes == 0) {
9018bcb0991SDimitry Andric if (MDNode *MD =
9028bcb0991SDimitry Andric IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
9038bcb0991SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
9048bcb0991SDimitry Andric DerefBytes = CI->getLimitedValue();
9058bcb0991SDimitry Andric }
9068bcb0991SDimitry Andric CanBeNull = true;
9078bcb0991SDimitry Andric }
9080b57cec5SDimitry Andric } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
9090b57cec5SDimitry Andric if (!AI->isArrayAllocation()) {
9105ffd83dbSDimitry Andric DerefBytes =
911bdd1243dSDimitry Andric DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinValue();
9120b57cec5SDimitry Andric CanBeNull = false;
913fe6060f1SDimitry Andric CanBeFreed = false;
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
9160b57cec5SDimitry Andric if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
9170b57cec5SDimitry Andric // TODO: Don't outright reject hasExternalWeakLinkage but set the
9180b57cec5SDimitry Andric // CanBeNull flag.
919bdd1243dSDimitry Andric DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedValue();
9200b57cec5SDimitry Andric CanBeNull = false;
921fe6060f1SDimitry Andric CanBeFreed = false;
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric }
9240b57cec5SDimitry Andric return DerefBytes;
9250b57cec5SDimitry Andric }
9260b57cec5SDimitry Andric
getPointerAlignment(const DataLayout & DL) const9275ffd83dbSDimitry Andric Align Value::getPointerAlignment(const DataLayout &DL) const {
9280b57cec5SDimitry Andric assert(getType()->isPointerTy() && "must be pointer");
9290b57cec5SDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(this)) {
9300b57cec5SDimitry Andric if (isa<Function>(GO)) {
9315ffd83dbSDimitry Andric Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
9320b57cec5SDimitry Andric switch (DL.getFunctionPtrAlignType()) {
9330b57cec5SDimitry Andric case DataLayout::FunctionPtrAlignType::Independent:
9348bcb0991SDimitry Andric return FunctionPtrAlign;
9350b57cec5SDimitry Andric case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
9365ffd83dbSDimitry Andric return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne());
9370b57cec5SDimitry Andric }
9388bcb0991SDimitry Andric llvm_unreachable("Unhandled FunctionPtrAlignType");
9390b57cec5SDimitry Andric }
9400eae32dcSDimitry Andric const MaybeAlign Alignment(GO->getAlign());
9418bcb0991SDimitry Andric if (!Alignment) {
9420b57cec5SDimitry Andric if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
9430b57cec5SDimitry Andric Type *ObjectType = GVar->getValueType();
9440b57cec5SDimitry Andric if (ObjectType->isSized()) {
9450b57cec5SDimitry Andric // If the object is defined in the current Module, we'll be giving
9460b57cec5SDimitry Andric // it the preferred alignment. Otherwise, we have to assume that it
9470b57cec5SDimitry Andric // may only have the minimum ABI alignment.
9480b57cec5SDimitry Andric if (GVar->isStrongDefinitionForLinker())
9495ffd83dbSDimitry Andric return DL.getPreferredAlign(GVar);
9500b57cec5SDimitry Andric else
9515ffd83dbSDimitry Andric return DL.getABITypeAlign(ObjectType);
9520b57cec5SDimitry Andric }
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric }
9555ffd83dbSDimitry Andric return Alignment.valueOrOne();
9560b57cec5SDimitry Andric } else if (const Argument *A = dyn_cast<Argument>(this)) {
9575ffd83dbSDimitry Andric const MaybeAlign Alignment = A->getParamAlign();
9588bcb0991SDimitry Andric if (!Alignment && A->hasStructRetAttr()) {
9590b57cec5SDimitry Andric // An sret parameter has at least the ABI alignment of the return type.
960e8d8bef9SDimitry Andric Type *EltTy = A->getParamStructRetType();
9610b57cec5SDimitry Andric if (EltTy->isSized())
9625ffd83dbSDimitry Andric return DL.getABITypeAlign(EltTy);
9630b57cec5SDimitry Andric }
9645ffd83dbSDimitry Andric return Alignment.valueOrOne();
9650b57cec5SDimitry Andric } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
9665ffd83dbSDimitry Andric return AI->getAlign();
9678bcb0991SDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(this)) {
9685ffd83dbSDimitry Andric MaybeAlign Alignment = Call->getRetAlign();
9698bcb0991SDimitry Andric if (!Alignment && Call->getCalledFunction())
9705ffd83dbSDimitry Andric Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
9715ffd83dbSDimitry Andric return Alignment.valueOrOne();
9728bcb0991SDimitry Andric } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
9730b57cec5SDimitry Andric if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
9740b57cec5SDimitry Andric ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
9755ffd83dbSDimitry Andric return Align(CI->getLimitedValue());
9765ffd83dbSDimitry Andric }
9775ffd83dbSDimitry Andric } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
97881ad6265SDimitry Andric // Strip pointer casts to avoid creating unnecessary ptrtoint expression
97981ad6265SDimitry Andric // if the only "reduction" is combining a bitcast + ptrtoint.
98081ad6265SDimitry Andric CstPtr = CstPtr->stripPointerCasts();
9815ffd83dbSDimitry Andric if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
9825ffd83dbSDimitry Andric const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
9835ffd83dbSDimitry Andric /*OnlyIfReduced=*/true))) {
98406c3fb27SDimitry Andric size_t TrailingZeros = CstInt->getValue().countr_zero();
9855ffd83dbSDimitry Andric // While the actual alignment may be large, elsewhere we have
9865ffd83dbSDimitry Andric // an arbitrary upper alignmet limit, so let's clamp to it.
9875ffd83dbSDimitry Andric return Align(TrailingZeros < Value::MaxAlignmentExponent
9885ffd83dbSDimitry Andric ? uint64_t(1) << TrailingZeros
9895ffd83dbSDimitry Andric : Value::MaximumAlignment);
9900b57cec5SDimitry Andric }
9918bcb0991SDimitry Andric }
9925ffd83dbSDimitry Andric return Align(1);
9930b57cec5SDimitry Andric }
9940b57cec5SDimitry Andric
99506c3fb27SDimitry Andric static std::optional<int64_t>
getOffsetFromIndex(const GEPOperator * GEP,unsigned Idx,const DataLayout & DL)99606c3fb27SDimitry Andric getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) {
99706c3fb27SDimitry Andric // Skip over the first indices.
99806c3fb27SDimitry Andric gep_type_iterator GTI = gep_type_begin(GEP);
99906c3fb27SDimitry Andric for (unsigned i = 1; i != Idx; ++i, ++GTI)
100006c3fb27SDimitry Andric /*skip along*/;
100106c3fb27SDimitry Andric
100206c3fb27SDimitry Andric // Compute the offset implied by the rest of the indices.
100306c3fb27SDimitry Andric int64_t Offset = 0;
100406c3fb27SDimitry Andric for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
100506c3fb27SDimitry Andric ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
100606c3fb27SDimitry Andric if (!OpC)
100706c3fb27SDimitry Andric return std::nullopt;
100806c3fb27SDimitry Andric if (OpC->isZero())
100906c3fb27SDimitry Andric continue; // No offset.
101006c3fb27SDimitry Andric
101106c3fb27SDimitry Andric // Handle struct indices, which add their field offset to the pointer.
101206c3fb27SDimitry Andric if (StructType *STy = GTI.getStructTypeOrNull()) {
101306c3fb27SDimitry Andric Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
101406c3fb27SDimitry Andric continue;
101506c3fb27SDimitry Andric }
101606c3fb27SDimitry Andric
101706c3fb27SDimitry Andric // Otherwise, we have a sequential type like an array or fixed-length
101806c3fb27SDimitry Andric // vector. Multiply the index by the ElementSize.
10191db9f3b2SDimitry Andric TypeSize Size = GTI.getSequentialElementStride(DL);
102006c3fb27SDimitry Andric if (Size.isScalable())
102106c3fb27SDimitry Andric return std::nullopt;
102206c3fb27SDimitry Andric Offset += Size.getFixedValue() * OpC->getSExtValue();
102306c3fb27SDimitry Andric }
102406c3fb27SDimitry Andric
102506c3fb27SDimitry Andric return Offset;
102606c3fb27SDimitry Andric }
102706c3fb27SDimitry Andric
getPointerOffsetFrom(const Value * Other,const DataLayout & DL) const102806c3fb27SDimitry Andric std::optional<int64_t> Value::getPointerOffsetFrom(const Value *Other,
102906c3fb27SDimitry Andric const DataLayout &DL) const {
103006c3fb27SDimitry Andric const Value *Ptr1 = Other;
103106c3fb27SDimitry Andric const Value *Ptr2 = this;
103206c3fb27SDimitry Andric APInt Offset1(DL.getIndexTypeSizeInBits(Ptr1->getType()), 0);
103306c3fb27SDimitry Andric APInt Offset2(DL.getIndexTypeSizeInBits(Ptr2->getType()), 0);
103406c3fb27SDimitry Andric Ptr1 = Ptr1->stripAndAccumulateConstantOffsets(DL, Offset1, true);
103506c3fb27SDimitry Andric Ptr2 = Ptr2->stripAndAccumulateConstantOffsets(DL, Offset2, true);
103606c3fb27SDimitry Andric
103706c3fb27SDimitry Andric // Handle the trivial case first.
103806c3fb27SDimitry Andric if (Ptr1 == Ptr2)
103906c3fb27SDimitry Andric return Offset2.getSExtValue() - Offset1.getSExtValue();
104006c3fb27SDimitry Andric
104106c3fb27SDimitry Andric const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
104206c3fb27SDimitry Andric const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
104306c3fb27SDimitry Andric
104406c3fb27SDimitry Andric // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
104506c3fb27SDimitry Andric // base. After that base, they may have some number of common (and
104606c3fb27SDimitry Andric // potentially variable) indices. After that they handle some constant
104706c3fb27SDimitry Andric // offset, which determines their offset from each other. At this point, we
104806c3fb27SDimitry Andric // handle no other case.
104906c3fb27SDimitry Andric if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0) ||
105006c3fb27SDimitry Andric GEP1->getSourceElementType() != GEP2->getSourceElementType())
105106c3fb27SDimitry Andric return std::nullopt;
105206c3fb27SDimitry Andric
105306c3fb27SDimitry Andric // Skip any common indices and track the GEP types.
105406c3fb27SDimitry Andric unsigned Idx = 1;
105506c3fb27SDimitry Andric for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
105606c3fb27SDimitry Andric if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
105706c3fb27SDimitry Andric break;
105806c3fb27SDimitry Andric
105906c3fb27SDimitry Andric auto IOffset1 = getOffsetFromIndex(GEP1, Idx, DL);
106006c3fb27SDimitry Andric auto IOffset2 = getOffsetFromIndex(GEP2, Idx, DL);
106106c3fb27SDimitry Andric if (!IOffset1 || !IOffset2)
106206c3fb27SDimitry Andric return std::nullopt;
106306c3fb27SDimitry Andric return *IOffset2 - *IOffset1 + Offset2.getSExtValue() -
106406c3fb27SDimitry Andric Offset1.getSExtValue();
106506c3fb27SDimitry Andric }
106606c3fb27SDimitry Andric
DoPHITranslation(const BasicBlock * CurBB,const BasicBlock * PredBB) const10670b57cec5SDimitry Andric const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
10680b57cec5SDimitry Andric const BasicBlock *PredBB) const {
10690b57cec5SDimitry Andric auto *PN = dyn_cast<PHINode>(this);
10700b57cec5SDimitry Andric if (PN && PN->getParent() == CurBB)
10710b57cec5SDimitry Andric return PN->getIncomingValueForBlock(PredBB);
10720b57cec5SDimitry Andric return this;
10730b57cec5SDimitry Andric }
10740b57cec5SDimitry Andric
getContext() const10750b57cec5SDimitry Andric LLVMContext &Value::getContext() const { return VTy->getContext(); }
10760b57cec5SDimitry Andric
reverseUseList()10770b57cec5SDimitry Andric void Value::reverseUseList() {
10780b57cec5SDimitry Andric if (!UseList || !UseList->Next)
10790b57cec5SDimitry Andric // No need to reverse 0 or 1 uses.
10800b57cec5SDimitry Andric return;
10810b57cec5SDimitry Andric
10820b57cec5SDimitry Andric Use *Head = UseList;
10830b57cec5SDimitry Andric Use *Current = UseList->Next;
10840b57cec5SDimitry Andric Head->Next = nullptr;
10850b57cec5SDimitry Andric while (Current) {
10860b57cec5SDimitry Andric Use *Next = Current->Next;
10870b57cec5SDimitry Andric Current->Next = Head;
10885ffd83dbSDimitry Andric Head->Prev = &Current->Next;
10890b57cec5SDimitry Andric Head = Current;
10900b57cec5SDimitry Andric Current = Next;
10910b57cec5SDimitry Andric }
10920b57cec5SDimitry Andric UseList = Head;
10935ffd83dbSDimitry Andric Head->Prev = &UseList;
10940b57cec5SDimitry Andric }
10950b57cec5SDimitry Andric
isSwiftError() const10960b57cec5SDimitry Andric bool Value::isSwiftError() const {
10970b57cec5SDimitry Andric auto *Arg = dyn_cast<Argument>(this);
10980b57cec5SDimitry Andric if (Arg)
10990b57cec5SDimitry Andric return Arg->hasSwiftErrorAttr();
11000b57cec5SDimitry Andric auto *Alloca = dyn_cast<AllocaInst>(this);
11010b57cec5SDimitry Andric if (!Alloca)
11020b57cec5SDimitry Andric return false;
11030b57cec5SDimitry Andric return Alloca->isSwiftError();
11040b57cec5SDimitry Andric }
11050b57cec5SDimitry Andric
11060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11070b57cec5SDimitry Andric // ValueHandleBase Class
11080b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11090b57cec5SDimitry Andric
AddToExistingUseList(ValueHandleBase ** List)11100b57cec5SDimitry Andric void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
11110b57cec5SDimitry Andric assert(List && "Handle list is null?");
11120b57cec5SDimitry Andric
11130b57cec5SDimitry Andric // Splice ourselves into the list.
11140b57cec5SDimitry Andric Next = *List;
11150b57cec5SDimitry Andric *List = this;
11160b57cec5SDimitry Andric setPrevPtr(List);
11170b57cec5SDimitry Andric if (Next) {
11180b57cec5SDimitry Andric Next->setPrevPtr(&Next);
11190b57cec5SDimitry Andric assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
11200b57cec5SDimitry Andric }
11210b57cec5SDimitry Andric }
11220b57cec5SDimitry Andric
AddToExistingUseListAfter(ValueHandleBase * List)11230b57cec5SDimitry Andric void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
11240b57cec5SDimitry Andric assert(List && "Must insert after existing node");
11250b57cec5SDimitry Andric
11260b57cec5SDimitry Andric Next = List->Next;
11270b57cec5SDimitry Andric setPrevPtr(&List->Next);
11280b57cec5SDimitry Andric List->Next = this;
11290b57cec5SDimitry Andric if (Next)
11300b57cec5SDimitry Andric Next->setPrevPtr(&Next);
11310b57cec5SDimitry Andric }
11320b57cec5SDimitry Andric
AddToUseList()11330b57cec5SDimitry Andric void ValueHandleBase::AddToUseList() {
11340b57cec5SDimitry Andric assert(getValPtr() && "Null pointer doesn't have a use list!");
11350b57cec5SDimitry Andric
11360b57cec5SDimitry Andric LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
11370b57cec5SDimitry Andric
11380b57cec5SDimitry Andric if (getValPtr()->HasValueHandle) {
11390b57cec5SDimitry Andric // If this value already has a ValueHandle, then it must be in the
11400b57cec5SDimitry Andric // ValueHandles map already.
11410b57cec5SDimitry Andric ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
11420b57cec5SDimitry Andric assert(Entry && "Value doesn't have any handles?");
11430b57cec5SDimitry Andric AddToExistingUseList(&Entry);
11440b57cec5SDimitry Andric return;
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric
11470b57cec5SDimitry Andric // Ok, it doesn't have any handles yet, so we must insert it into the
11480b57cec5SDimitry Andric // DenseMap. However, doing this insertion could cause the DenseMap to
11490b57cec5SDimitry Andric // reallocate itself, which would invalidate all of the PrevP pointers that
11500b57cec5SDimitry Andric // point into the old table. Handle this by checking for reallocation and
11510b57cec5SDimitry Andric // updating the stale pointers only if needed.
11520b57cec5SDimitry Andric DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
11530b57cec5SDimitry Andric const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
11540b57cec5SDimitry Andric
11550b57cec5SDimitry Andric ValueHandleBase *&Entry = Handles[getValPtr()];
11560b57cec5SDimitry Andric assert(!Entry && "Value really did already have handles?");
11570b57cec5SDimitry Andric AddToExistingUseList(&Entry);
11580b57cec5SDimitry Andric getValPtr()->HasValueHandle = true;
11590b57cec5SDimitry Andric
11600b57cec5SDimitry Andric // If reallocation didn't happen or if this was the first insertion, don't
11610b57cec5SDimitry Andric // walk the table.
11620b57cec5SDimitry Andric if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
11630b57cec5SDimitry Andric Handles.size() == 1) {
11640b57cec5SDimitry Andric return;
11650b57cec5SDimitry Andric }
11660b57cec5SDimitry Andric
11670b57cec5SDimitry Andric // Okay, reallocation did happen. Fix the Prev Pointers.
11680b57cec5SDimitry Andric for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
11690b57cec5SDimitry Andric E = Handles.end(); I != E; ++I) {
11700b57cec5SDimitry Andric assert(I->second && I->first == I->second->getValPtr() &&
11710b57cec5SDimitry Andric "List invariant broken!");
11720b57cec5SDimitry Andric I->second->setPrevPtr(&I->second);
11730b57cec5SDimitry Andric }
11740b57cec5SDimitry Andric }
11750b57cec5SDimitry Andric
RemoveFromUseList()11760b57cec5SDimitry Andric void ValueHandleBase::RemoveFromUseList() {
11770b57cec5SDimitry Andric assert(getValPtr() && getValPtr()->HasValueHandle &&
11780b57cec5SDimitry Andric "Pointer doesn't have a use list!");
11790b57cec5SDimitry Andric
11800b57cec5SDimitry Andric // Unlink this from its use list.
11810b57cec5SDimitry Andric ValueHandleBase **PrevPtr = getPrevPtr();
11820b57cec5SDimitry Andric assert(*PrevPtr == this && "List invariant broken");
11830b57cec5SDimitry Andric
11840b57cec5SDimitry Andric *PrevPtr = Next;
11850b57cec5SDimitry Andric if (Next) {
11860b57cec5SDimitry Andric assert(Next->getPrevPtr() == &Next && "List invariant broken");
11870b57cec5SDimitry Andric Next->setPrevPtr(PrevPtr);
11880b57cec5SDimitry Andric return;
11890b57cec5SDimitry Andric }
11900b57cec5SDimitry Andric
11910b57cec5SDimitry Andric // If the Next pointer was null, then it is possible that this was the last
11920b57cec5SDimitry Andric // ValueHandle watching VP. If so, delete its entry from the ValueHandles
11930b57cec5SDimitry Andric // map.
11940b57cec5SDimitry Andric LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
11950b57cec5SDimitry Andric DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
11960b57cec5SDimitry Andric if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
11970b57cec5SDimitry Andric Handles.erase(getValPtr());
11980b57cec5SDimitry Andric getValPtr()->HasValueHandle = false;
11990b57cec5SDimitry Andric }
12000b57cec5SDimitry Andric }
12010b57cec5SDimitry Andric
ValueIsDeleted(Value * V)12020b57cec5SDimitry Andric void ValueHandleBase::ValueIsDeleted(Value *V) {
12030b57cec5SDimitry Andric assert(V->HasValueHandle && "Should only be called if ValueHandles present");
12040b57cec5SDimitry Andric
12050b57cec5SDimitry Andric // Get the linked list base, which is guaranteed to exist since the
12060b57cec5SDimitry Andric // HasValueHandle flag is set.
12070b57cec5SDimitry Andric LLVMContextImpl *pImpl = V->getContext().pImpl;
12080b57cec5SDimitry Andric ValueHandleBase *Entry = pImpl->ValueHandles[V];
12090b57cec5SDimitry Andric assert(Entry && "Value bit set but no entries exist");
12100b57cec5SDimitry Andric
12110b57cec5SDimitry Andric // We use a local ValueHandleBase as an iterator so that ValueHandles can add
12120b57cec5SDimitry Andric // and remove themselves from the list without breaking our iteration. This
12130b57cec5SDimitry Andric // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
12140b57cec5SDimitry Andric // Note that we deliberately do not the support the case when dropping a value
12150b57cec5SDimitry Andric // handle results in a new value handle being permanently added to the list
12160b57cec5SDimitry Andric // (as might occur in theory for CallbackVH's): the new value handle will not
12170b57cec5SDimitry Andric // be processed and the checking code will mete out righteous punishment if
12180b57cec5SDimitry Andric // the handle is still present once we have finished processing all the other
12190b57cec5SDimitry Andric // value handles (it is fine to momentarily add then remove a value handle).
12200b57cec5SDimitry Andric for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
12210b57cec5SDimitry Andric Iterator.RemoveFromUseList();
12220b57cec5SDimitry Andric Iterator.AddToExistingUseListAfter(Entry);
12230b57cec5SDimitry Andric assert(Entry->Next == &Iterator && "Loop invariant broken.");
12240b57cec5SDimitry Andric
12250b57cec5SDimitry Andric switch (Entry->getKind()) {
12260b57cec5SDimitry Andric case Assert:
12270b57cec5SDimitry Andric break;
12280b57cec5SDimitry Andric case Weak:
12290b57cec5SDimitry Andric case WeakTracking:
12300b57cec5SDimitry Andric // WeakTracking and Weak just go to null, which unlinks them
12310b57cec5SDimitry Andric // from the list.
12320b57cec5SDimitry Andric Entry->operator=(nullptr);
12330b57cec5SDimitry Andric break;
12340b57cec5SDimitry Andric case Callback:
12350b57cec5SDimitry Andric // Forward to the subclass's implementation.
12360b57cec5SDimitry Andric static_cast<CallbackVH*>(Entry)->deleted();
12370b57cec5SDimitry Andric break;
12380b57cec5SDimitry Andric }
12390b57cec5SDimitry Andric }
12400b57cec5SDimitry Andric
12410b57cec5SDimitry Andric // All callbacks, weak references, and assertingVHs should be dropped by now.
12420b57cec5SDimitry Andric if (V->HasValueHandle) {
12430b57cec5SDimitry Andric #ifndef NDEBUG // Only in +Asserts mode...
12440b57cec5SDimitry Andric dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
12450b57cec5SDimitry Andric << "\n";
12460b57cec5SDimitry Andric if (pImpl->ValueHandles[V]->getKind() == Assert)
12470b57cec5SDimitry Andric llvm_unreachable("An asserting value handle still pointed to this"
12480b57cec5SDimitry Andric " value!");
12490b57cec5SDimitry Andric
12500b57cec5SDimitry Andric #endif
12510b57cec5SDimitry Andric llvm_unreachable("All references to V were not removed?");
12520b57cec5SDimitry Andric }
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric
ValueIsRAUWd(Value * Old,Value * New)12550b57cec5SDimitry Andric void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
12560b57cec5SDimitry Andric assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
12570b57cec5SDimitry Andric assert(Old != New && "Changing value into itself!");
12580b57cec5SDimitry Andric assert(Old->getType() == New->getType() &&
12590b57cec5SDimitry Andric "replaceAllUses of value with new value of different type!");
12600b57cec5SDimitry Andric
12610b57cec5SDimitry Andric // Get the linked list base, which is guaranteed to exist since the
12620b57cec5SDimitry Andric // HasValueHandle flag is set.
12630b57cec5SDimitry Andric LLVMContextImpl *pImpl = Old->getContext().pImpl;
12640b57cec5SDimitry Andric ValueHandleBase *Entry = pImpl->ValueHandles[Old];
12650b57cec5SDimitry Andric
12660b57cec5SDimitry Andric assert(Entry && "Value bit set but no entries exist");
12670b57cec5SDimitry Andric
12680b57cec5SDimitry Andric // We use a local ValueHandleBase as an iterator so that
12690b57cec5SDimitry Andric // ValueHandles can add and remove themselves from the list without
12700b57cec5SDimitry Andric // breaking our iteration. This is not really an AssertingVH; we
12710b57cec5SDimitry Andric // just have to give ValueHandleBase some kind.
12720b57cec5SDimitry Andric for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
12730b57cec5SDimitry Andric Iterator.RemoveFromUseList();
12740b57cec5SDimitry Andric Iterator.AddToExistingUseListAfter(Entry);
12750b57cec5SDimitry Andric assert(Entry->Next == &Iterator && "Loop invariant broken.");
12760b57cec5SDimitry Andric
12770b57cec5SDimitry Andric switch (Entry->getKind()) {
12780b57cec5SDimitry Andric case Assert:
12790b57cec5SDimitry Andric case Weak:
12800b57cec5SDimitry Andric // Asserting and Weak handles do not follow RAUW implicitly.
12810b57cec5SDimitry Andric break;
12820b57cec5SDimitry Andric case WeakTracking:
12830b57cec5SDimitry Andric // Weak goes to the new value, which will unlink it from Old's list.
12840b57cec5SDimitry Andric Entry->operator=(New);
12850b57cec5SDimitry Andric break;
12860b57cec5SDimitry Andric case Callback:
12870b57cec5SDimitry Andric // Forward to the subclass's implementation.
12880b57cec5SDimitry Andric static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
12890b57cec5SDimitry Andric break;
12900b57cec5SDimitry Andric }
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric
12930b57cec5SDimitry Andric #ifndef NDEBUG
12940b57cec5SDimitry Andric // If any new weak value handles were added while processing the
12950b57cec5SDimitry Andric // list, then complain about it now.
12960b57cec5SDimitry Andric if (Old->HasValueHandle)
12970b57cec5SDimitry Andric for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
12980b57cec5SDimitry Andric switch (Entry->getKind()) {
12990b57cec5SDimitry Andric case WeakTracking:
13000b57cec5SDimitry Andric dbgs() << "After RAUW from " << *Old->getType() << " %"
13010b57cec5SDimitry Andric << Old->getName() << " to " << *New->getType() << " %"
13020b57cec5SDimitry Andric << New->getName() << "\n";
13030b57cec5SDimitry Andric llvm_unreachable(
13040b57cec5SDimitry Andric "A weak tracking value handle still pointed to the old value!\n");
13050b57cec5SDimitry Andric default:
13060b57cec5SDimitry Andric break;
13070b57cec5SDimitry Andric }
13080b57cec5SDimitry Andric #endif
13090b57cec5SDimitry Andric }
13100b57cec5SDimitry Andric
13110b57cec5SDimitry Andric // Pin the vtable to this file.
anchor()13120b57cec5SDimitry Andric void CallbackVH::anchor() {}
1313