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/SmallString.h"
17 #include "llvm/ADT/SetVector.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/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/raw_ostream.h"
40 static cl::opt
<unsigned> NonGlobalValueMaxNameSize(
41 "non-global-value-max-name-size", cl::Hidden
, cl::init(1024),
42 cl::desc("Maximum size for the name of non-global values."));
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
47 static inline Type
*checkType(Type
*Ty
) {
48 assert(Ty
&& "Value defined with a null type: Error!");
52 Value::Value(Type
*ty
, unsigned scid
)
53 : VTy(checkType(ty
)), UseList(nullptr), SubclassID(scid
),
54 HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
55 NumUserOperands(0), IsUsedByMD(false), HasName(false) {
56 static_assert(ConstantFirstVal
== 0, "!(SubclassID < ConstantFirstVal)");
57 // FIXME: Why isn't this in the subclass gunk??
58 // Note, we cannot call isa<CallInst> before the CallInst has been
60 if (SubclassID
== Instruction::Call
|| SubclassID
== Instruction::Invoke
||
61 SubclassID
== Instruction::CallBr
)
62 assert((VTy
->isFirstClassType() || VTy
->isVoidTy() || VTy
->isStructTy()) &&
63 "invalid CallInst type!");
64 else if (SubclassID
!= BasicBlockVal
&&
65 (/*SubclassID < ConstantFirstVal ||*/ SubclassID
> ConstantLastVal
))
66 assert((VTy
->isFirstClassType() || VTy
->isVoidTy()) &&
67 "Cannot create non-first-class values except for constants!");
68 static_assert(sizeof(Value
) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
73 // Notify all ValueHandles (if present) that this value is going away.
75 ValueHandleBase::ValueIsDeleted(this);
76 if (isUsedByMetadata())
77 ValueAsMetadata::handleDeletion(this);
79 #ifndef NDEBUG // Only in -g mode...
80 // Check to make sure that there are no uses of this value that are still
81 // around when the value is destroyed. If there are, then we have a dangling
82 // reference and something is wrong. This code is here to print out where
83 // the value is still being referenced.
86 dbgs() << "While deleting: " << *VTy
<< " %" << getName() << "\n";
87 for (auto *U
: users())
88 dbgs() << "Use still stuck around after Def is destroyed:" << *U
<< "\n";
91 assert(use_empty() && "Uses remain when a value is destroyed!");
93 // If this value is named, destroy the name. This should not be in a symtab
98 void Value::deleteValue() {
99 switch (getValueID()) {
100 #define HANDLE_VALUE(Name) \
101 case Value::Name##Val: \
102 delete static_cast<Name *>(this); \
104 #define HANDLE_MEMORY_VALUE(Name) \
105 case Value::Name##Val: \
106 static_cast<DerivedUser *>(this)->DeleteValue( \
107 static_cast<DerivedUser *>(this)); \
109 #define HANDLE_INSTRUCTION(Name) /* nothing */
110 #include "llvm/IR/Value.def"
112 #define HANDLE_INST(N, OPC, CLASS) \
113 case Value::InstructionVal + Instruction::OPC: \
114 delete static_cast<CLASS *>(this); \
116 #define HANDLE_USER_INST(N, OPC, CLASS)
117 #include "llvm/IR/Instruction.def"
120 llvm_unreachable("attempting to delete unknown value kind");
124 void Value::destroyValueName() {
125 ValueName
*Name
= getValueName();
128 setValueName(nullptr);
131 bool Value::hasNUses(unsigned N
) const {
132 return hasNItems(use_begin(), use_end(), N
);
135 bool Value::hasNUsesOrMore(unsigned N
) const {
136 return hasNItemsOrMore(use_begin(), use_end(), N
);
139 bool Value::isUsedInBasicBlock(const BasicBlock
*BB
) const {
140 // This can be computed either by scanning the instructions in BB, or by
141 // scanning the use list of this Value. Both lists can be very long, but
142 // usually one is quite short.
144 // Scan both lists simultaneously until one is exhausted. This limits the
145 // search to the shorter list.
146 BasicBlock::const_iterator BI
= BB
->begin(), BE
= BB
->end();
147 const_user_iterator UI
= user_begin(), UE
= user_end();
148 for (; BI
!= BE
&& UI
!= UE
; ++BI
, ++UI
) {
149 // Scan basic block: Check if this Value is used by the instruction at BI.
150 if (is_contained(BI
->operands(), this))
152 // Scan use list: Check if the use at UI is in BB.
153 const auto *User
= dyn_cast
<Instruction
>(*UI
);
154 if (User
&& User
->getParent() == BB
)
160 unsigned Value::getNumUses() const {
161 return (unsigned)std::distance(use_begin(), use_end());
164 static bool getSymTab(Value
*V
, ValueSymbolTable
*&ST
) {
166 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
167 if (BasicBlock
*P
= I
->getParent())
168 if (Function
*PP
= P
->getParent())
169 ST
= PP
->getValueSymbolTable();
170 } else if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
)) {
171 if (Function
*P
= BB
->getParent())
172 ST
= P
->getValueSymbolTable();
173 } else if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
174 if (Module
*P
= GV
->getParent())
175 ST
= &P
->getValueSymbolTable();
176 } else if (Argument
*A
= dyn_cast
<Argument
>(V
)) {
177 if (Function
*P
= A
->getParent())
178 ST
= P
->getValueSymbolTable();
180 assert(isa
<Constant
>(V
) && "Unknown value type!");
181 return true; // no name is setable for this.
186 ValueName
*Value::getValueName() const {
187 if (!HasName
) return nullptr;
189 LLVMContext
&Ctx
= getContext();
190 auto I
= Ctx
.pImpl
->ValueNames
.find(this);
191 assert(I
!= Ctx
.pImpl
->ValueNames
.end() &&
192 "No name entry found!");
197 void Value::setValueName(ValueName
*VN
) {
198 LLVMContext
&Ctx
= getContext();
200 assert(HasName
== Ctx
.pImpl
->ValueNames
.count(this) &&
201 "HasName bit out of sync!");
205 Ctx
.pImpl
->ValueNames
.erase(this);
211 Ctx
.pImpl
->ValueNames
[this] = VN
;
214 StringRef
Value::getName() const {
215 // Make sure the empty string is still a C string. For historical reasons,
216 // some clients want to call .data() on the result and expect it to be null
219 return StringRef("", 0);
220 return getValueName()->getKey();
223 void Value::setNameImpl(const Twine
&NewName
) {
224 // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
225 if (getContext().shouldDiscardValueNames() && !isa
<GlobalValue
>(this))
228 // Fast path for common IRBuilder case of setName("") when there is no name.
229 if (NewName
.isTriviallyEmpty() && !hasName())
232 SmallString
<256> NameData
;
233 StringRef NameRef
= NewName
.toStringRef(NameData
);
234 assert(NameRef
.find_first_of(0) == StringRef::npos
&&
235 "Null bytes are not allowed in names");
237 // Name isn't changing?
238 if (getName() == NameRef
)
241 // Cap the size of non-GlobalValue names.
242 if (NameRef
.size() > NonGlobalValueMaxNameSize
&& !isa
<GlobalValue
>(this))
244 NameRef
.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize
));
246 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
248 // Get the symbol table to update for this object.
249 ValueSymbolTable
*ST
;
250 if (getSymTab(this, ST
))
251 return; // Cannot set a name on this value (e.g. constant).
253 if (!ST
) { // No symbol table to update? Just do the change.
254 if (NameRef
.empty()) {
255 // Free the name for this value.
260 // NOTE: Could optimize for the case the name is shrinking to not deallocate
264 // Create the new name.
265 setValueName(ValueName::Create(NameRef
));
266 getValueName()->setValue(this);
270 // NOTE: Could optimize for the case the name is shrinking to not deallocate
274 ST
->removeValueName(getValueName());
281 // Name is changing to something new.
282 setValueName(ST
->createValueName(NameRef
, this));
285 void Value::setName(const Twine
&NewName
) {
286 setNameImpl(NewName
);
287 if (Function
*F
= dyn_cast
<Function
>(this))
288 F
->recalculateIntrinsicID();
291 void Value::takeName(Value
*V
) {
292 ValueSymbolTable
*ST
= nullptr;
293 // If this value has a name, drop it.
295 // Get the symtab this is in.
296 if (getSymTab(this, ST
)) {
297 // We can't set a name on this value, but we need to clear V's name if
299 if (V
->hasName()) V
->setName("");
300 return; // Cannot set a name on this value (e.g. constant).
305 ST
->removeValueName(getValueName());
309 // Now we know that this has no name.
311 // If V has no name either, we're done.
312 if (!V
->hasName()) return;
314 // Get this's symtab if we didn't before.
316 if (getSymTab(this, ST
)) {
319 return; // Cannot set a name on this value (e.g. constant).
323 // Get V's ST, this should always succed, because V has a name.
324 ValueSymbolTable
*VST
;
325 bool Failure
= getSymTab(V
, VST
);
326 assert(!Failure
&& "V has a name, so it should have a ST!"); (void)Failure
;
328 // If these values are both in the same symtab, we can do this very fast.
329 // This works even if both values have no symtab yet.
332 setValueName(V
->getValueName());
333 V
->setValueName(nullptr);
334 getValueName()->setValue(this);
338 // Otherwise, things are slightly more complex. Remove V's name from VST and
339 // then reinsert it into ST.
342 VST
->removeValueName(V
->getValueName());
343 setValueName(V
->getValueName());
344 V
->setValueName(nullptr);
345 getValueName()->setValue(this);
348 ST
->reinsertValue(this);
351 void Value::assertModuleIsMaterializedImpl() const {
353 const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(this);
356 const Module
*M
= GV
->getParent();
359 assert(M
->isMaterialized());
364 static bool contains(SmallPtrSetImpl
<ConstantExpr
*> &Cache
, ConstantExpr
*Expr
,
366 if (!Cache
.insert(Expr
).second
)
369 for (auto &O
: Expr
->operands()) {
372 auto *CE
= dyn_cast
<ConstantExpr
>(O
);
375 if (contains(Cache
, CE
, C
))
381 static bool contains(Value
*Expr
, Value
*V
) {
385 auto *C
= dyn_cast
<Constant
>(V
);
389 auto *CE
= dyn_cast
<ConstantExpr
>(Expr
);
393 SmallPtrSet
<ConstantExpr
*, 4> Cache
;
394 return contains(Cache
, CE
, C
);
398 void Value::doRAUW(Value
*New
, ReplaceMetadataUses ReplaceMetaUses
) {
399 assert(New
&& "Value::replaceAllUsesWith(<null>) is invalid!");
400 assert(!contains(New
, this) &&
401 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
402 assert(New
->getType() == getType() &&
403 "replaceAllUses of value with new value of different type!");
405 // Notify all ValueHandles (if present) that this value is going away.
407 ValueHandleBase::ValueIsRAUWd(this, New
);
408 if (ReplaceMetaUses
== ReplaceMetadataUses::Yes
&& isUsedByMetadata())
409 ValueAsMetadata::handleRAUW(this, New
);
411 while (!materialized_use_empty()) {
413 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
414 // constant because they are uniqued.
415 if (auto *C
= dyn_cast
<Constant
>(U
.getUser())) {
416 if (!isa
<GlobalValue
>(C
)) {
417 C
->handleOperandChange(this, New
);
425 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(this))
426 BB
->replaceSuccessorsPhiUsesWith(cast
<BasicBlock
>(New
));
429 void Value::replaceAllUsesWith(Value
*New
) {
430 doRAUW(New
, ReplaceMetadataUses::Yes
);
433 void Value::replaceNonMetadataUsesWith(Value
*New
) {
434 doRAUW(New
, ReplaceMetadataUses::No
);
437 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
438 // This routine leaves uses within BB.
439 void Value::replaceUsesOutsideBlock(Value
*New
, BasicBlock
*BB
) {
440 assert(New
&& "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
441 assert(!contains(New
, this) &&
442 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
443 assert(New
->getType() == getType() &&
444 "replaceUses of value with new value of different type!");
445 assert(BB
&& "Basic block that may contain a use of 'New' must be defined\n");
447 replaceUsesWithIf(New
, [BB
](Use
&U
) {
448 auto *I
= dyn_cast
<Instruction
>(U
.getUser());
449 // Don't replace if it's an instruction in the BB basic block.
450 return !I
|| I
->getParent() != BB
;
455 // Various metrics for how much to strip off of pointers.
456 enum PointerStripKind
{
458 PSK_ZeroIndicesAndAliases
,
459 PSK_ZeroIndicesSameRepresentation
,
460 PSK_ZeroIndicesAndInvariantGroups
,
461 PSK_InBoundsConstantIndices
,
465 template <PointerStripKind StripKind
>
466 static const Value
*stripPointerCastsAndOffsets(const Value
*V
) {
467 if (!V
->getType()->isPointerTy())
470 // Even though we don't look through PHI nodes, we could be called on an
471 // instruction in an unreachable block, which may be on a cycle.
472 SmallPtrSet
<const Value
*, 4> Visited
;
476 if (auto *GEP
= dyn_cast
<GEPOperator
>(V
)) {
478 case PSK_ZeroIndices
:
479 case PSK_ZeroIndicesAndAliases
:
480 case PSK_ZeroIndicesSameRepresentation
:
481 case PSK_ZeroIndicesAndInvariantGroups
:
482 if (!GEP
->hasAllZeroIndices())
485 case PSK_InBoundsConstantIndices
:
486 if (!GEP
->hasAllConstantIndices())
490 if (!GEP
->isInBounds())
494 V
= GEP
->getPointerOperand();
495 } else if (Operator::getOpcode(V
) == Instruction::BitCast
) {
496 V
= cast
<Operator
>(V
)->getOperand(0);
497 } else if (StripKind
!= PSK_ZeroIndicesSameRepresentation
&&
498 Operator::getOpcode(V
) == Instruction::AddrSpaceCast
) {
499 // TODO: If we know an address space cast will not change the
500 // representation we could look through it here as well.
501 V
= cast
<Operator
>(V
)->getOperand(0);
502 } else if (StripKind
== PSK_ZeroIndicesAndAliases
&& isa
<GlobalAlias
>(V
)) {
503 V
= cast
<GlobalAlias
>(V
)->getAliasee();
505 if (const auto *Call
= dyn_cast
<CallBase
>(V
)) {
506 if (const Value
*RV
= Call
->getReturnedArgOperand()) {
510 // The result of launder.invariant.group must alias it's argument,
511 // but it can't be marked with returned attribute, that's why it needs
513 if (StripKind
== PSK_ZeroIndicesAndInvariantGroups
&&
514 (Call
->getIntrinsicID() == Intrinsic::launder_invariant_group
||
515 Call
->getIntrinsicID() == Intrinsic::strip_invariant_group
)) {
516 V
= Call
->getArgOperand(0);
522 assert(V
->getType()->isPointerTy() && "Unexpected operand type!");
523 } while (Visited
.insert(V
).second
);
527 } // end anonymous namespace
529 const Value
*Value::stripPointerCasts() const {
530 return stripPointerCastsAndOffsets
<PSK_ZeroIndices
>(this);
533 const Value
*Value::stripPointerCastsAndAliases() const {
534 return stripPointerCastsAndOffsets
<PSK_ZeroIndicesAndAliases
>(this);
537 const Value
*Value::stripPointerCastsSameRepresentation() const {
538 return stripPointerCastsAndOffsets
<PSK_ZeroIndicesSameRepresentation
>(this);
541 const Value
*Value::stripInBoundsConstantOffsets() const {
542 return stripPointerCastsAndOffsets
<PSK_InBoundsConstantIndices
>(this);
545 const Value
*Value::stripPointerCastsAndInvariantGroups() const {
546 return stripPointerCastsAndOffsets
<PSK_ZeroIndicesAndInvariantGroups
>(this);
550 Value::stripAndAccumulateConstantOffsets(const DataLayout
&DL
, APInt
&Offset
,
551 bool AllowNonInbounds
) const {
552 if (!getType()->isPtrOrPtrVectorTy())
555 unsigned BitWidth
= Offset
.getBitWidth();
556 assert(BitWidth
== DL
.getIndexTypeSizeInBits(getType()) &&
557 "The offset bit width does not match the DL specification.");
559 // Even though we don't look through PHI nodes, we could be called on an
560 // instruction in an unreachable block, which may be on a cycle.
561 SmallPtrSet
<const Value
*, 4> Visited
;
562 Visited
.insert(this);
563 const Value
*V
= this;
565 if (auto *GEP
= dyn_cast
<GEPOperator
>(V
)) {
566 // If in-bounds was requested, we do not strip non-in-bounds GEPs.
567 if (!AllowNonInbounds
&& !GEP
->isInBounds())
570 // If one of the values we have visited is an addrspacecast, then
571 // the pointer type of this GEP may be different from the type
572 // of the Ptr parameter which was passed to this function. This
573 // means when we construct GEPOffset, we need to use the size
574 // of GEP's pointer type rather than the size of the original
576 APInt
GEPOffset(DL
.getIndexTypeSizeInBits(V
->getType()), 0);
577 if (!GEP
->accumulateConstantOffset(DL
, GEPOffset
))
580 // Stop traversal if the pointer offset wouldn't fit in the bit-width
581 // provided by the Offset argument. This can happen due to AddrSpaceCast
583 if (GEPOffset
.getMinSignedBits() > BitWidth
)
586 Offset
+= GEPOffset
.sextOrTrunc(BitWidth
);
587 V
= GEP
->getPointerOperand();
588 } else if (Operator::getOpcode(V
) == Instruction::BitCast
||
589 Operator::getOpcode(V
) == Instruction::AddrSpaceCast
) {
590 V
= cast
<Operator
>(V
)->getOperand(0);
591 } else if (auto *GA
= dyn_cast
<GlobalAlias
>(V
)) {
592 if (!GA
->isInterposable())
593 V
= GA
->getAliasee();
594 } else if (const auto *Call
= dyn_cast
<CallBase
>(V
)) {
595 if (const Value
*RV
= Call
->getReturnedArgOperand())
598 assert(V
->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
599 } while (Visited
.insert(V
).second
);
604 const Value
*Value::stripInBoundsOffsets() const {
605 return stripPointerCastsAndOffsets
<PSK_InBounds
>(this);
608 uint64_t Value::getPointerDereferenceableBytes(const DataLayout
&DL
,
609 bool &CanBeNull
) const {
610 assert(getType()->isPointerTy() && "must be pointer");
612 uint64_t DerefBytes
= 0;
614 if (const Argument
*A
= dyn_cast
<Argument
>(this)) {
615 DerefBytes
= A
->getDereferenceableBytes();
616 if (DerefBytes
== 0 && (A
->hasByValAttr() || A
->hasStructRetAttr())) {
617 Type
*PT
= cast
<PointerType
>(A
->getType())->getElementType();
619 DerefBytes
= DL
.getTypeStoreSize(PT
);
621 if (DerefBytes
== 0) {
622 DerefBytes
= A
->getDereferenceableOrNullBytes();
625 } else if (const auto *Call
= dyn_cast
<CallBase
>(this)) {
626 DerefBytes
= Call
->getDereferenceableBytes(AttributeList::ReturnIndex
);
627 if (DerefBytes
== 0) {
629 Call
->getDereferenceableOrNullBytes(AttributeList::ReturnIndex
);
632 } else if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(this)) {
633 if (MDNode
*MD
= LI
->getMetadata(LLVMContext::MD_dereferenceable
)) {
634 ConstantInt
*CI
= mdconst::extract
<ConstantInt
>(MD
->getOperand(0));
635 DerefBytes
= CI
->getLimitedValue();
637 if (DerefBytes
== 0) {
639 LI
->getMetadata(LLVMContext::MD_dereferenceable_or_null
)) {
640 ConstantInt
*CI
= mdconst::extract
<ConstantInt
>(MD
->getOperand(0));
641 DerefBytes
= CI
->getLimitedValue();
645 } else if (auto *IP
= dyn_cast
<IntToPtrInst
>(this)) {
646 if (MDNode
*MD
= IP
->getMetadata(LLVMContext::MD_dereferenceable
)) {
647 ConstantInt
*CI
= mdconst::extract
<ConstantInt
>(MD
->getOperand(0));
648 DerefBytes
= CI
->getLimitedValue();
650 if (DerefBytes
== 0) {
652 IP
->getMetadata(LLVMContext::MD_dereferenceable_or_null
)) {
653 ConstantInt
*CI
= mdconst::extract
<ConstantInt
>(MD
->getOperand(0));
654 DerefBytes
= CI
->getLimitedValue();
658 } else if (auto *AI
= dyn_cast
<AllocaInst
>(this)) {
659 if (!AI
->isArrayAllocation()) {
660 DerefBytes
= DL
.getTypeStoreSize(AI
->getAllocatedType());
663 } else if (auto *GV
= dyn_cast
<GlobalVariable
>(this)) {
664 if (GV
->getValueType()->isSized() && !GV
->hasExternalWeakLinkage()) {
665 // TODO: Don't outright reject hasExternalWeakLinkage but set the
667 DerefBytes
= DL
.getTypeStoreSize(GV
->getValueType());
674 MaybeAlign
Value::getPointerAlignment(const DataLayout
&DL
) const {
675 assert(getType()->isPointerTy() && "must be pointer");
676 if (auto *GO
= dyn_cast
<GlobalObject
>(this)) {
677 if (isa
<Function
>(GO
)) {
678 const MaybeAlign FunctionPtrAlign
= DL
.getFunctionPtrAlign();
679 switch (DL
.getFunctionPtrAlignType()) {
680 case DataLayout::FunctionPtrAlignType::Independent
:
681 return FunctionPtrAlign
;
682 case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign
:
683 return std::max(FunctionPtrAlign
, MaybeAlign(GO
->getAlignment()));
685 llvm_unreachable("Unhandled FunctionPtrAlignType");
687 const MaybeAlign
Alignment(GO
->getAlignment());
689 if (auto *GVar
= dyn_cast
<GlobalVariable
>(GO
)) {
690 Type
*ObjectType
= GVar
->getValueType();
691 if (ObjectType
->isSized()) {
692 // If the object is defined in the current Module, we'll be giving
693 // it the preferred alignment. Otherwise, we have to assume that it
694 // may only have the minimum ABI alignment.
695 if (GVar
->isStrongDefinitionForLinker())
696 return MaybeAlign(DL
.getPreferredAlignment(GVar
));
698 return Align(DL
.getABITypeAlignment(ObjectType
));
703 } else if (const Argument
*A
= dyn_cast
<Argument
>(this)) {
704 const MaybeAlign
Alignment(A
->getParamAlignment());
705 if (!Alignment
&& A
->hasStructRetAttr()) {
706 // An sret parameter has at least the ABI alignment of the return type.
707 Type
*EltTy
= cast
<PointerType
>(A
->getType())->getElementType();
708 if (EltTy
->isSized())
709 return Align(DL
.getABITypeAlignment(EltTy
));
712 } else if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(this)) {
713 const MaybeAlign
Alignment(AI
->getAlignment());
715 Type
*AllocatedType
= AI
->getAllocatedType();
716 if (AllocatedType
->isSized())
717 return MaybeAlign(DL
.getPrefTypeAlignment(AllocatedType
));
720 } else if (const auto *Call
= dyn_cast
<CallBase
>(this)) {
721 const MaybeAlign
Alignment(Call
->getRetAlignment());
722 if (!Alignment
&& Call
->getCalledFunction())
724 Call
->getCalledFunction()->getAttributes().getRetAlignment());
726 } else if (const LoadInst
*LI
= dyn_cast
<LoadInst
>(this)) {
727 if (MDNode
*MD
= LI
->getMetadata(LLVMContext::MD_align
)) {
728 ConstantInt
*CI
= mdconst::extract
<ConstantInt
>(MD
->getOperand(0));
729 return MaybeAlign(CI
->getLimitedValue());
735 const Value
*Value::DoPHITranslation(const BasicBlock
*CurBB
,
736 const BasicBlock
*PredBB
) const {
737 auto *PN
= dyn_cast
<PHINode
>(this);
738 if (PN
&& PN
->getParent() == CurBB
)
739 return PN
->getIncomingValueForBlock(PredBB
);
743 LLVMContext
&Value::getContext() const { return VTy
->getContext(); }
745 void Value::reverseUseList() {
746 if (!UseList
|| !UseList
->Next
)
747 // No need to reverse 0 or 1 uses.
751 Use
*Current
= UseList
->Next
;
752 Head
->Next
= nullptr;
754 Use
*Next
= Current
->Next
;
755 Current
->Next
= Head
;
756 Head
->setPrev(&Current
->Next
);
761 Head
->setPrev(&UseList
);
764 bool Value::isSwiftError() const {
765 auto *Arg
= dyn_cast
<Argument
>(this);
767 return Arg
->hasSwiftErrorAttr();
768 auto *Alloca
= dyn_cast
<AllocaInst
>(this);
771 return Alloca
->isSwiftError();
774 //===----------------------------------------------------------------------===//
775 // ValueHandleBase Class
776 //===----------------------------------------------------------------------===//
778 void ValueHandleBase::AddToExistingUseList(ValueHandleBase
**List
) {
779 assert(List
&& "Handle list is null?");
781 // Splice ourselves into the list.
786 Next
->setPrevPtr(&Next
);
787 assert(getValPtr() == Next
->getValPtr() && "Added to wrong list?");
791 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase
*List
) {
792 assert(List
&& "Must insert after existing node");
795 setPrevPtr(&List
->Next
);
798 Next
->setPrevPtr(&Next
);
801 void ValueHandleBase::AddToUseList() {
802 assert(getValPtr() && "Null pointer doesn't have a use list!");
804 LLVMContextImpl
*pImpl
= getValPtr()->getContext().pImpl
;
806 if (getValPtr()->HasValueHandle
) {
807 // If this value already has a ValueHandle, then it must be in the
808 // ValueHandles map already.
809 ValueHandleBase
*&Entry
= pImpl
->ValueHandles
[getValPtr()];
810 assert(Entry
&& "Value doesn't have any handles?");
811 AddToExistingUseList(&Entry
);
815 // Ok, it doesn't have any handles yet, so we must insert it into the
816 // DenseMap. However, doing this insertion could cause the DenseMap to
817 // reallocate itself, which would invalidate all of the PrevP pointers that
818 // point into the old table. Handle this by checking for reallocation and
819 // updating the stale pointers only if needed.
820 DenseMap
<Value
*, ValueHandleBase
*> &Handles
= pImpl
->ValueHandles
;
821 const void *OldBucketPtr
= Handles
.getPointerIntoBucketsArray();
823 ValueHandleBase
*&Entry
= Handles
[getValPtr()];
824 assert(!Entry
&& "Value really did already have handles?");
825 AddToExistingUseList(&Entry
);
826 getValPtr()->HasValueHandle
= true;
828 // If reallocation didn't happen or if this was the first insertion, don't
830 if (Handles
.isPointerIntoBucketsArray(OldBucketPtr
) ||
831 Handles
.size() == 1) {
835 // Okay, reallocation did happen. Fix the Prev Pointers.
836 for (DenseMap
<Value
*, ValueHandleBase
*>::iterator I
= Handles
.begin(),
837 E
= Handles
.end(); I
!= E
; ++I
) {
838 assert(I
->second
&& I
->first
== I
->second
->getValPtr() &&
839 "List invariant broken!");
840 I
->second
->setPrevPtr(&I
->second
);
844 void ValueHandleBase::RemoveFromUseList() {
845 assert(getValPtr() && getValPtr()->HasValueHandle
&&
846 "Pointer doesn't have a use list!");
848 // Unlink this from its use list.
849 ValueHandleBase
**PrevPtr
= getPrevPtr();
850 assert(*PrevPtr
== this && "List invariant broken");
854 assert(Next
->getPrevPtr() == &Next
&& "List invariant broken");
855 Next
->setPrevPtr(PrevPtr
);
859 // If the Next pointer was null, then it is possible that this was the last
860 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
862 LLVMContextImpl
*pImpl
= getValPtr()->getContext().pImpl
;
863 DenseMap
<Value
*, ValueHandleBase
*> &Handles
= pImpl
->ValueHandles
;
864 if (Handles
.isPointerIntoBucketsArray(PrevPtr
)) {
865 Handles
.erase(getValPtr());
866 getValPtr()->HasValueHandle
= false;
870 void ValueHandleBase::ValueIsDeleted(Value
*V
) {
871 assert(V
->HasValueHandle
&& "Should only be called if ValueHandles present");
873 // Get the linked list base, which is guaranteed to exist since the
874 // HasValueHandle flag is set.
875 LLVMContextImpl
*pImpl
= V
->getContext().pImpl
;
876 ValueHandleBase
*Entry
= pImpl
->ValueHandles
[V
];
877 assert(Entry
&& "Value bit set but no entries exist");
879 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
880 // and remove themselves from the list without breaking our iteration. This
881 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
882 // Note that we deliberately do not the support the case when dropping a value
883 // handle results in a new value handle being permanently added to the list
884 // (as might occur in theory for CallbackVH's): the new value handle will not
885 // be processed and the checking code will mete out righteous punishment if
886 // the handle is still present once we have finished processing all the other
887 // value handles (it is fine to momentarily add then remove a value handle).
888 for (ValueHandleBase
Iterator(Assert
, *Entry
); Entry
; Entry
= Iterator
.Next
) {
889 Iterator
.RemoveFromUseList();
890 Iterator
.AddToExistingUseListAfter(Entry
);
891 assert(Entry
->Next
== &Iterator
&& "Loop invariant broken.");
893 switch (Entry
->getKind()) {
898 // WeakTracking and Weak just go to null, which unlinks them
900 Entry
->operator=(nullptr);
903 // Forward to the subclass's implementation.
904 static_cast<CallbackVH
*>(Entry
)->deleted();
909 // All callbacks, weak references, and assertingVHs should be dropped by now.
910 if (V
->HasValueHandle
) {
911 #ifndef NDEBUG // Only in +Asserts mode...
912 dbgs() << "While deleting: " << *V
->getType() << " %" << V
->getName()
914 if (pImpl
->ValueHandles
[V
]->getKind() == Assert
)
915 llvm_unreachable("An asserting value handle still pointed to this"
919 llvm_unreachable("All references to V were not removed?");
923 void ValueHandleBase::ValueIsRAUWd(Value
*Old
, Value
*New
) {
924 assert(Old
->HasValueHandle
&&"Should only be called if ValueHandles present");
925 assert(Old
!= New
&& "Changing value into itself!");
926 assert(Old
->getType() == New
->getType() &&
927 "replaceAllUses of value with new value of different type!");
929 // Get the linked list base, which is guaranteed to exist since the
930 // HasValueHandle flag is set.
931 LLVMContextImpl
*pImpl
= Old
->getContext().pImpl
;
932 ValueHandleBase
*Entry
= pImpl
->ValueHandles
[Old
];
934 assert(Entry
&& "Value bit set but no entries exist");
936 // We use a local ValueHandleBase as an iterator so that
937 // ValueHandles can add and remove themselves from the list without
938 // breaking our iteration. This is not really an AssertingVH; we
939 // just have to give ValueHandleBase some kind.
940 for (ValueHandleBase
Iterator(Assert
, *Entry
); Entry
; Entry
= Iterator
.Next
) {
941 Iterator
.RemoveFromUseList();
942 Iterator
.AddToExistingUseListAfter(Entry
);
943 assert(Entry
->Next
== &Iterator
&& "Loop invariant broken.");
945 switch (Entry
->getKind()) {
948 // Asserting and Weak handles do not follow RAUW implicitly.
951 // Weak goes to the new value, which will unlink it from Old's list.
952 Entry
->operator=(New
);
955 // Forward to the subclass's implementation.
956 static_cast<CallbackVH
*>(Entry
)->allUsesReplacedWith(New
);
962 // If any new weak value handles were added while processing the
963 // list, then complain about it now.
964 if (Old
->HasValueHandle
)
965 for (Entry
= pImpl
->ValueHandles
[Old
]; Entry
; Entry
= Entry
->Next
)
966 switch (Entry
->getKind()) {
968 dbgs() << "After RAUW from " << *Old
->getType() << " %"
969 << Old
->getName() << " to " << *New
->getType() << " %"
970 << New
->getName() << "\n";
972 "A weak tracking value handle still pointed to the old value!\n");
979 // Pin the vtable to this file.
980 void CallbackVH::anchor() {}