1 //===-- Value.cpp - Implement the Value class -----------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Value, ValueHandle, and User classes.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Value.h"
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DerivedUser.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/InstrTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/Statepoint.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/raw_ostream.h"
41 static cl::opt<unsigned> NonGlobalValueMaxNameSize(
42 "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
43 cl::desc("Maximum size for the name of non-global values."));
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
48 static inline Type *checkType(Type *Ty) {
49 assert(Ty && "Value defined with a null type: Error!");
53 Value::Value(Type *ty, unsigned scid)
54 : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
55 HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
56 NumUserOperands(0), IsUsedByMD(false), HasName(false) {
57 static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
58 // FIXME: Why isn't this in the subclass gunk??
59 // Note, we cannot call isa<CallInst> before the CallInst has been
61 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
62 SubclassID == Instruction::CallBr)
63 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
64 "invalid CallInst type!");
65 else if (SubclassID != BasicBlockVal &&
66 (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
67 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
68 "Cannot create non-first-class values except for constants!");
69 static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
74 // Notify all ValueHandles (if present) that this value is going away.
76 ValueHandleBase::ValueIsDeleted(this);
77 if (isUsedByMetadata())
78 ValueAsMetadata::handleDeletion(this);
80 #ifndef NDEBUG // Only in -g mode...
81 // Check to make sure that there are no uses of this value that are still
82 // around when the value is destroyed. If there are, then we have a dangling
83 // reference and something is wrong. This code is here to print out where
84 // the value is still being referenced.
86 // Note that use_empty() cannot be called here, as it eventually downcasts
87 // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
88 // been destructed, so accessing it is UB.
90 if (!materialized_use_empty()) {
91 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
92 for (auto *U : users())
93 dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
96 assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
98 // If this value is named, destroy the name. This should not be in a symtab
103 void Value::deleteValue() {
104 switch (getValueID()) {
105 #define HANDLE_VALUE(Name) \
106 case Value::Name##Val: \
107 delete static_cast<Name *>(this); \
109 #define HANDLE_MEMORY_VALUE(Name) \
110 case Value::Name##Val: \
111 static_cast<DerivedUser *>(this)->DeleteValue( \
112 static_cast<DerivedUser *>(this)); \
114 #define HANDLE_INSTRUCTION(Name) /* nothing */
115 #include "llvm/IR/Value.def"
117 #define HANDLE_INST(N, OPC, CLASS) \
118 case Value::InstructionVal + Instruction::OPC: \
119 delete static_cast<CLASS *>(this); \
121 #define HANDLE_USER_INST(N, OPC, CLASS)
122 #include "llvm/IR/Instruction.def"
125 llvm_unreachable("attempting to delete unknown value kind");
129 void Value::destroyValueName() {
130 ValueName *Name = getValueName();
133 setValueName(nullptr);
136 bool Value::hasNUses(unsigned N) const {
137 return hasNItems(use_begin(), use_end(), N);
140 bool Value::hasNUsesOrMore(unsigned N) const {
141 return hasNItemsOrMore(use_begin(), use_end(), N);
144 static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
146 Use *Value::getSingleUndroppableUse() {
147 Use *Result = nullptr;
148 for (Use &U : uses()) {
149 if (!U.getUser()->isDroppable()) {
158 bool Value::hasNUndroppableUses(unsigned int N) const {
159 return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
162 bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
163 return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
166 void Value::dropDroppableUses(
167 llvm::function_ref<bool(const Use *)> ShouldDrop) {
168 SmallVector<Use *, 8> ToBeEdited;
169 for (Use &U : uses())
170 if (U.getUser()->isDroppable() && ShouldDrop(&U))
171 ToBeEdited.push_back(&U);
172 for (Use *U : ToBeEdited) {
174 if (auto *Assume = dyn_cast<IntrinsicInst>(U->getUser())) {
175 assert(Assume->getIntrinsicID() == Intrinsic::assume);
176 unsigned OpNo = U->getOperandNo();
178 Assume->setOperand(0, ConstantInt::getTrue(Assume->getContext()));
180 Assume->setOperand(OpNo, UndefValue::get(U->get()->getType()));
181 CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
182 BOI.Tag = getContext().pImpl->getOrInsertBundleTag("ignore");
185 llvm_unreachable("unkown droppable use");
189 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
190 // This can be computed either by scanning the instructions in BB, or by
191 // scanning the use list of this Value. Both lists can be very long, but
192 // usually one is quite short.
194 // Scan both lists simultaneously until one is exhausted. This limits the
195 // search to the shorter list.
196 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
197 const_user_iterator UI = user_begin(), UE = user_end();
198 for (; BI != BE && UI != UE; ++BI, ++UI) {
199 // Scan basic block: Check if this Value is used by the instruction at BI.
200 if (is_contained(BI->operands(), this))
202 // Scan use list: Check if the use at UI is in BB.
203 const auto *User = dyn_cast<Instruction>(*UI);
204 if (User && User->getParent() == BB)
210 unsigned Value::getNumUses() const {
211 return (unsigned)std::distance(use_begin(), use_end());
214 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
216 if (Instruction *I = dyn_cast<Instruction>(V)) {
217 if (BasicBlock *P = I->getParent())
218 if (Function *PP = P->getParent())
219 ST = PP->getValueSymbolTable();
220 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
221 if (Function *P = BB->getParent())
222 ST = P->getValueSymbolTable();
223 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
224 if (Module *P = GV->getParent())
225 ST = &P->getValueSymbolTable();
226 } else if (Argument *A = dyn_cast<Argument>(V)) {
227 if (Function *P = A->getParent())
228 ST = P->getValueSymbolTable();
230 assert(isa<Constant>(V) && "Unknown value type!");
231 return true; // no name is setable for this.
236 ValueName *Value::getValueName() const {
237 if (!HasName) return nullptr;
239 LLVMContext &Ctx = getContext();
240 auto I = Ctx.pImpl->ValueNames.find(this);
241 assert(I != Ctx.pImpl->ValueNames.end() &&
242 "No name entry found!");
247 void Value::setValueName(ValueName *VN) {
248 LLVMContext &Ctx = getContext();
250 assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
251 "HasName bit out of sync!");
255 Ctx.pImpl->ValueNames.erase(this);
261 Ctx.pImpl->ValueNames[this] = VN;
264 StringRef Value::getName() const {
265 // Make sure the empty string is still a C string. For historical reasons,
266 // some clients want to call .data() on the result and expect it to be null
269 return StringRef("", 0);
270 return getValueName()->getKey();
273 void Value::setNameImpl(const Twine &NewName) {
274 // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
275 if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
278 // Fast path for common IRBuilder case of setName("") when there is no name.
279 if (NewName.isTriviallyEmpty() && !hasName())
282 SmallString<256> NameData;
283 StringRef NameRef = NewName.toStringRef(NameData);
284 assert(NameRef.find_first_of(0) == StringRef::npos &&
285 "Null bytes are not allowed in names");
287 // Name isn't changing?
288 if (getName() == NameRef)
291 // Cap the size of non-GlobalValue names.
292 if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
294 NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
296 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
298 // Get the symbol table to update for this object.
299 ValueSymbolTable *ST;
300 if (getSymTab(this, ST))
301 return; // Cannot set a name on this value (e.g. constant).
303 if (!ST) { // No symbol table to update? Just do the change.
304 if (NameRef.empty()) {
305 // Free the name for this value.
310 // NOTE: Could optimize for the case the name is shrinking to not deallocate
314 // Create the new name.
315 setValueName(ValueName::Create(NameRef));
316 getValueName()->setValue(this);
320 // NOTE: Could optimize for the case the name is shrinking to not deallocate
324 ST->removeValueName(getValueName());
331 // Name is changing to something new.
332 setValueName(ST->createValueName(NameRef, this));
335 void Value::setName(const Twine &NewName) {
336 setNameImpl(NewName);
337 if (Function *F = dyn_cast<Function>(this))
338 F->recalculateIntrinsicID();
341 void Value::takeName(Value *V) {
342 ValueSymbolTable *ST = nullptr;
343 // If this value has a name, drop it.
345 // Get the symtab this is in.
346 if (getSymTab(this, ST)) {
347 // We can't set a name on this value, but we need to clear V's name if
349 if (V->hasName()) V->setName("");
350 return; // Cannot set a name on this value (e.g. constant).
355 ST->removeValueName(getValueName());
359 // Now we know that this has no name.
361 // If V has no name either, we're done.
362 if (!V->hasName()) return;
364 // Get this's symtab if we didn't before.
366 if (getSymTab(this, ST)) {
369 return; // Cannot set a name on this value (e.g. constant).
373 // Get V's ST, this should always succed, because V has a name.
374 ValueSymbolTable *VST;
375 bool Failure = getSymTab(V, VST);
376 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
378 // If these values are both in the same symtab, we can do this very fast.
379 // This works even if both values have no symtab yet.
382 setValueName(V->getValueName());
383 V->setValueName(nullptr);
384 getValueName()->setValue(this);
388 // Otherwise, things are slightly more complex. Remove V's name from VST and
389 // then reinsert it into ST.
392 VST->removeValueName(V->getValueName());
393 setValueName(V->getValueName());
394 V->setValueName(nullptr);
395 getValueName()->setValue(this);
398 ST->reinsertValue(this);
401 void Value::assertModuleIsMaterializedImpl() const {
403 const GlobalValue *GV = dyn_cast<GlobalValue>(this);
406 const Module *M = GV->getParent();
409 assert(M->isMaterialized());
414 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
416 if (!Cache.insert(Expr).second)
419 for (auto &O : Expr->operands()) {
422 auto *CE = dyn_cast<ConstantExpr>(O);
425 if (contains(Cache, CE, C))
431 static bool contains(Value *Expr, Value *V) {
435 auto *C = dyn_cast<Constant>(V);
439 auto *CE = dyn_cast<ConstantExpr>(Expr);
443 SmallPtrSet<ConstantExpr *, 4> Cache;
444 return contains(Cache, CE, C);
448 void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
449 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
450 assert(!contains(New, this) &&
451 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
452 assert(New->getType() == getType() &&
453 "replaceAllUses of value with new value of different type!");
455 // Notify all ValueHandles (if present) that this value is going away.
457 ValueHandleBase::ValueIsRAUWd(this, New);
458 if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
459 ValueAsMetadata::handleRAUW(this, New);
461 while (!materialized_use_empty()) {
463 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
464 // constant because they are uniqued.
465 if (auto *C = dyn_cast<Constant>(U.getUser())) {
466 if (!isa<GlobalValue>(C)) {
467 C->handleOperandChange(this, New);
475 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
476 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
479 void Value::replaceAllUsesWith(Value *New) {
480 doRAUW(New, ReplaceMetadataUses::Yes);
483 void Value::replaceNonMetadataUsesWith(Value *New) {
484 doRAUW(New, ReplaceMetadataUses::No);
487 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
488 // This routine leaves uses within BB.
489 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
490 assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
491 assert(!contains(New, this) &&
492 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
493 assert(New->getType() == getType() &&
494 "replaceUses of value with new value of different type!");
495 assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
497 replaceUsesWithIf(New, [BB](Use &U) {
498 auto *I = dyn_cast<Instruction>(U.getUser());
499 // Don't replace if it's an instruction in the BB basic block.
500 return !I || I->getParent() != BB;
505 // Various metrics for how much to strip off of pointers.
506 enum PointerStripKind {
508 PSK_ZeroIndicesAndAliases,
509 PSK_ZeroIndicesSameRepresentation,
510 PSK_ZeroIndicesAndInvariantGroups,
511 PSK_InBoundsConstantIndices,
515 template <PointerStripKind StripKind>
516 static const Value *stripPointerCastsAndOffsets(const Value *V) {
517 if (!V->getType()->isPointerTy())
520 // Even though we don't look through PHI nodes, we could be called on an
521 // instruction in an unreachable block, which may be on a cycle.
522 SmallPtrSet<const Value *, 4> Visited;
526 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
528 case PSK_ZeroIndices:
529 case PSK_ZeroIndicesAndAliases:
530 case PSK_ZeroIndicesSameRepresentation:
531 case PSK_ZeroIndicesAndInvariantGroups:
532 if (!GEP->hasAllZeroIndices())
535 case PSK_InBoundsConstantIndices:
536 if (!GEP->hasAllConstantIndices())
540 if (!GEP->isInBounds())
544 V = GEP->getPointerOperand();
545 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
546 V = cast<Operator>(V)->getOperand(0);
547 } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
548 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
549 // TODO: If we know an address space cast will not change the
550 // representation we could look through it here as well.
551 V = cast<Operator>(V)->getOperand(0);
552 } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
553 V = cast<GlobalAlias>(V)->getAliasee();
555 if (const auto *Call = dyn_cast<CallBase>(V)) {
556 if (const Value *RV = Call->getReturnedArgOperand()) {
560 // The result of launder.invariant.group must alias it's argument,
561 // but it can't be marked with returned attribute, that's why it needs
563 if (StripKind == PSK_ZeroIndicesAndInvariantGroups &&
564 (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
565 Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
566 V = Call->getArgOperand(0);
572 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
573 } while (Visited.insert(V).second);
577 } // end anonymous namespace
579 const Value *Value::stripPointerCasts() const {
580 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
583 const Value *Value::stripPointerCastsAndAliases() const {
584 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
587 const Value *Value::stripPointerCastsSameRepresentation() const {
588 return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
591 const Value *Value::stripInBoundsConstantOffsets() const {
592 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
595 const Value *Value::stripPointerCastsAndInvariantGroups() const {
596 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this);
600 Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
601 bool AllowNonInbounds) const {
602 if (!getType()->isPtrOrPtrVectorTy())
605 unsigned BitWidth = Offset.getBitWidth();
606 assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
607 "The offset bit width does not match the DL specification.");
609 // Even though we don't look through PHI nodes, we could be called on an
610 // instruction in an unreachable block, which may be on a cycle.
611 SmallPtrSet<const Value *, 4> Visited;
612 Visited.insert(this);
613 const Value *V = this;
615 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
616 // If in-bounds was requested, we do not strip non-in-bounds GEPs.
617 if (!AllowNonInbounds && !GEP->isInBounds())
620 // If one of the values we have visited is an addrspacecast, then
621 // the pointer type of this GEP may be different from the type
622 // of the Ptr parameter which was passed to this function. This
623 // means when we construct GEPOffset, we need to use the size
624 // of GEP's pointer type rather than the size of the original
626 APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
627 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
630 // Stop traversal if the pointer offset wouldn't fit in the bit-width
631 // provided by the Offset argument. This can happen due to AddrSpaceCast
633 if (GEPOffset.getMinSignedBits() > BitWidth)
636 Offset += GEPOffset.sextOrTrunc(BitWidth);
637 V = GEP->getPointerOperand();
638 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
639 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
640 V = cast<Operator>(V)->getOperand(0);
641 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
642 if (!GA->isInterposable())
643 V = GA->getAliasee();
644 } else if (const auto *Call = dyn_cast<CallBase>(V)) {
645 if (const Value *RV = Call->getReturnedArgOperand())
648 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
649 } while (Visited.insert(V).second);
654 const Value *Value::stripInBoundsOffsets() const {
655 return stripPointerCastsAndOffsets<PSK_InBounds>(this);
658 uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
659 bool &CanBeNull) const {
660 assert(getType()->isPointerTy() && "must be pointer");
662 uint64_t DerefBytes = 0;
664 if (const Argument *A = dyn_cast<Argument>(this)) {
665 DerefBytes = A->getDereferenceableBytes();
666 if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
667 Type *PT = cast<PointerType>(A->getType())->getElementType();
669 DerefBytes = DL.getTypeStoreSize(PT);
671 if (DerefBytes == 0) {
672 DerefBytes = A->getDereferenceableOrNullBytes();
675 } else if (const auto *Call = dyn_cast<CallBase>(this)) {
676 DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
677 if (DerefBytes == 0) {
679 Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
682 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
683 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
684 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
685 DerefBytes = CI->getLimitedValue();
687 if (DerefBytes == 0) {
689 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
690 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
691 DerefBytes = CI->getLimitedValue();
695 } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
696 if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
697 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
698 DerefBytes = CI->getLimitedValue();
700 if (DerefBytes == 0) {
702 IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
703 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
704 DerefBytes = CI->getLimitedValue();
708 } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
709 if (!AI->isArrayAllocation()) {
710 DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
713 } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
714 if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
715 // TODO: Don't outright reject hasExternalWeakLinkage but set the
717 DerefBytes = DL.getTypeStoreSize(GV->getValueType());
724 MaybeAlign Value::getPointerAlignment(const DataLayout &DL) const {
725 assert(getType()->isPointerTy() && "must be pointer");
726 if (auto *GO = dyn_cast<GlobalObject>(this)) {
727 if (isa<Function>(GO)) {
728 const MaybeAlign FunctionPtrAlign = DL.getFunctionPtrAlign();
729 switch (DL.getFunctionPtrAlignType()) {
730 case DataLayout::FunctionPtrAlignType::Independent:
731 return FunctionPtrAlign;
732 case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
733 return std::max(FunctionPtrAlign, MaybeAlign(GO->getAlignment()));
735 llvm_unreachable("Unhandled FunctionPtrAlignType");
737 const MaybeAlign Alignment(GO->getAlignment());
739 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
740 Type *ObjectType = GVar->getValueType();
741 if (ObjectType->isSized()) {
742 // If the object is defined in the current Module, we'll be giving
743 // it the preferred alignment. Otherwise, we have to assume that it
744 // may only have the minimum ABI alignment.
745 if (GVar->isStrongDefinitionForLinker())
746 return MaybeAlign(DL.getPreferredAlignment(GVar));
748 return Align(DL.getABITypeAlignment(ObjectType));
753 } else if (const Argument *A = dyn_cast<Argument>(this)) {
754 const MaybeAlign Alignment(A->getParamAlignment());
755 if (!Alignment && A->hasStructRetAttr()) {
756 // An sret parameter has at least the ABI alignment of the return type.
757 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
758 if (EltTy->isSized())
759 return Align(DL.getABITypeAlignment(EltTy));
762 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
763 const MaybeAlign Alignment(AI->getAlignment());
765 Type *AllocatedType = AI->getAllocatedType();
766 if (AllocatedType->isSized())
767 return MaybeAlign(DL.getPrefTypeAlignment(AllocatedType));
770 } else if (const auto *Call = dyn_cast<CallBase>(this)) {
771 const MaybeAlign Alignment(Call->getRetAlignment());
772 if (!Alignment && Call->getCalledFunction())
774 Call->getCalledFunction()->getAttributes().getRetAlignment());
776 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
777 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
778 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
779 return MaybeAlign(CI->getLimitedValue());
781 } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
782 if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
783 const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
784 /*OnlyIfReduced=*/true))) {
785 size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
786 // While the actual alignment may be large, elsewhere we have
787 // an arbitrary upper alignmet limit, so let's clamp to it.
788 return Align(TrailingZeros < Value::MaxAlignmentExponent
789 ? uint64_t(1) << TrailingZeros
790 : Value::MaximumAlignment);
796 const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
797 const BasicBlock *PredBB) const {
798 auto *PN = dyn_cast<PHINode>(this);
799 if (PN && PN->getParent() == CurBB)
800 return PN->getIncomingValueForBlock(PredBB);
804 LLVMContext &Value::getContext() const { return VTy->getContext(); }
806 void Value::reverseUseList() {
807 if (!UseList || !UseList->Next)
808 // No need to reverse 0 or 1 uses.
812 Use *Current = UseList->Next;
813 Head->Next = nullptr;
815 Use *Next = Current->Next;
816 Current->Next = Head;
817 Head->setPrev(&Current->Next);
822 Head->setPrev(&UseList);
825 bool Value::isSwiftError() const {
826 auto *Arg = dyn_cast<Argument>(this);
828 return Arg->hasSwiftErrorAttr();
829 auto *Alloca = dyn_cast<AllocaInst>(this);
832 return Alloca->isSwiftError();
835 //===----------------------------------------------------------------------===//
836 // ValueHandleBase Class
837 //===----------------------------------------------------------------------===//
839 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
840 assert(List && "Handle list is null?");
842 // Splice ourselves into the list.
847 Next->setPrevPtr(&Next);
848 assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
852 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
853 assert(List && "Must insert after existing node");
856 setPrevPtr(&List->Next);
859 Next->setPrevPtr(&Next);
862 void ValueHandleBase::AddToUseList() {
863 assert(getValPtr() && "Null pointer doesn't have a use list!");
865 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
867 if (getValPtr()->HasValueHandle) {
868 // If this value already has a ValueHandle, then it must be in the
869 // ValueHandles map already.
870 ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
871 assert(Entry && "Value doesn't have any handles?");
872 AddToExistingUseList(&Entry);
876 // Ok, it doesn't have any handles yet, so we must insert it into the
877 // DenseMap. However, doing this insertion could cause the DenseMap to
878 // reallocate itself, which would invalidate all of the PrevP pointers that
879 // point into the old table. Handle this by checking for reallocation and
880 // updating the stale pointers only if needed.
881 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
882 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
884 ValueHandleBase *&Entry = Handles[getValPtr()];
885 assert(!Entry && "Value really did already have handles?");
886 AddToExistingUseList(&Entry);
887 getValPtr()->HasValueHandle = true;
889 // If reallocation didn't happen or if this was the first insertion, don't
891 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
892 Handles.size() == 1) {
896 // Okay, reallocation did happen. Fix the Prev Pointers.
897 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
898 E = Handles.end(); I != E; ++I) {
899 assert(I->second && I->first == I->second->getValPtr() &&
900 "List invariant broken!");
901 I->second->setPrevPtr(&I->second);
905 void ValueHandleBase::RemoveFromUseList() {
906 assert(getValPtr() && getValPtr()->HasValueHandle &&
907 "Pointer doesn't have a use list!");
909 // Unlink this from its use list.
910 ValueHandleBase **PrevPtr = getPrevPtr();
911 assert(*PrevPtr == this && "List invariant broken");
915 assert(Next->getPrevPtr() == &Next && "List invariant broken");
916 Next->setPrevPtr(PrevPtr);
920 // If the Next pointer was null, then it is possible that this was the last
921 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
923 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
924 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
925 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
926 Handles.erase(getValPtr());
927 getValPtr()->HasValueHandle = false;
931 void ValueHandleBase::ValueIsDeleted(Value *V) {
932 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
934 // Get the linked list base, which is guaranteed to exist since the
935 // HasValueHandle flag is set.
936 LLVMContextImpl *pImpl = V->getContext().pImpl;
937 ValueHandleBase *Entry = pImpl->ValueHandles[V];
938 assert(Entry && "Value bit set but no entries exist");
940 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
941 // and remove themselves from the list without breaking our iteration. This
942 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
943 // Note that we deliberately do not the support the case when dropping a value
944 // handle results in a new value handle being permanently added to the list
945 // (as might occur in theory for CallbackVH's): the new value handle will not
946 // be processed and the checking code will mete out righteous punishment if
947 // the handle is still present once we have finished processing all the other
948 // value handles (it is fine to momentarily add then remove a value handle).
949 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
950 Iterator.RemoveFromUseList();
951 Iterator.AddToExistingUseListAfter(Entry);
952 assert(Entry->Next == &Iterator && "Loop invariant broken.");
954 switch (Entry->getKind()) {
959 // WeakTracking and Weak just go to null, which unlinks them
961 Entry->operator=(nullptr);
964 // Forward to the subclass's implementation.
965 static_cast<CallbackVH*>(Entry)->deleted();
970 // All callbacks, weak references, and assertingVHs should be dropped by now.
971 if (V->HasValueHandle) {
972 #ifndef NDEBUG // Only in +Asserts mode...
973 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
975 if (pImpl->ValueHandles[V]->getKind() == Assert)
976 llvm_unreachable("An asserting value handle still pointed to this"
980 llvm_unreachable("All references to V were not removed?");
984 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
985 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
986 assert(Old != New && "Changing value into itself!");
987 assert(Old->getType() == New->getType() &&
988 "replaceAllUses of value with new value of different type!");
990 // Get the linked list base, which is guaranteed to exist since the
991 // HasValueHandle flag is set.
992 LLVMContextImpl *pImpl = Old->getContext().pImpl;
993 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
995 assert(Entry && "Value bit set but no entries exist");
997 // We use a local ValueHandleBase as an iterator so that
998 // ValueHandles can add and remove themselves from the list without
999 // breaking our iteration. This is not really an AssertingVH; we
1000 // just have to give ValueHandleBase some kind.
1001 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1002 Iterator.RemoveFromUseList();
1003 Iterator.AddToExistingUseListAfter(Entry);
1004 assert(Entry->Next == &Iterator && "Loop invariant broken.");
1006 switch (Entry->getKind()) {
1009 // Asserting and Weak handles do not follow RAUW implicitly.
1012 // Weak goes to the new value, which will unlink it from Old's list.
1013 Entry->operator=(New);
1016 // Forward to the subclass's implementation.
1017 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1023 // If any new weak value handles were added while processing the
1024 // list, then complain about it now.
1025 if (Old->HasValueHandle)
1026 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1027 switch (Entry->getKind()) {
1029 dbgs() << "After RAUW from " << *Old->getType() << " %"
1030 << Old->getName() << " to " << *New->getType() << " %"
1031 << New->getName() << "\n";
1033 "A weak tracking value handle still pointed to the old value!\n");
1040 // Pin the vtable to this file.
1041 void CallbackVH::anchor() {}