1 //===-- Value.cpp - Implement the Value class -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Value, ValueHandle, and User classes.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMContextImpl.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InstrTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Operator.h"
21 #include "llvm/Module.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LeakDetector.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/ADT/DenseMap.h"
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 static inline const Type
*checkType(const Type
*Ty
) {
39 assert(Ty
&& "Value defined with a null type: Error!");
43 Value::Value(const Type
*ty
, unsigned scid
)
44 : SubclassID(scid
), HasValueHandle(0),
45 SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty
)),
47 if (isa
<CallInst
>(this) || isa
<InvokeInst
>(this))
48 assert((VTy
->isFirstClassType() || VTy
->isVoidTy() ||
49 ty
->isOpaqueTy() || VTy
->isStructTy()) &&
50 "invalid CallInst type!");
51 else if (!isa
<Constant
>(this) && !isa
<BasicBlock
>(this))
52 assert((VTy
->isFirstClassType() || VTy
->isVoidTy() ||
54 "Cannot create non-first-class values except for constants!");
58 // Notify all ValueHandles (if present) that this value is going away.
60 ValueHandleBase::ValueIsDeleted(this);
62 #ifndef NDEBUG // Only in -g mode...
63 // Check to make sure that there are no uses of this value that are still
64 // around when the value is destroyed. If there are, then we have a dangling
65 // reference and something is wrong. This code is here to print out what is
66 // still being referenced. The value in question should be printed as
70 dbgs() << "While deleting: " << *VTy
<< " %" << getNameStr() << "\n";
71 for (use_iterator I
= use_begin(), E
= use_end(); I
!= E
; ++I
)
72 dbgs() << "Use still stuck around after Def is destroyed:"
76 assert(use_empty() && "Uses remain when a value is destroyed!");
78 // If this value is named, destroy the name. This should not be in a symtab
83 // There should be no uses of this object anymore, remove it.
84 LeakDetector::removeGarbageObject(this);
87 /// hasNUses - Return true if this Value has exactly N users.
89 bool Value::hasNUses(unsigned N
) const {
90 const_use_iterator UI
= use_begin(), E
= use_end();
93 if (UI
== E
) return false; // Too few.
97 /// hasNUsesOrMore - Return true if this value has N users or more. This is
98 /// logically equivalent to getNumUses() >= N.
100 bool Value::hasNUsesOrMore(unsigned N
) const {
101 const_use_iterator UI
= use_begin(), E
= use_end();
104 if (UI
== E
) return false; // Too few.
109 /// isUsedInBasicBlock - Return true if this value is used in the specified
111 bool Value::isUsedInBasicBlock(const BasicBlock
*BB
) const {
112 for (const_use_iterator I
= use_begin(), E
= use_end(); I
!= E
; ++I
) {
113 const Instruction
*User
= dyn_cast
<Instruction
>(*I
);
114 if (User
&& User
->getParent() == BB
)
121 /// getNumUses - This method computes the number of uses of this Value. This
122 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
124 unsigned Value::getNumUses() const {
125 return (unsigned)std::distance(use_begin(), use_end());
128 static bool getSymTab(Value
*V
, ValueSymbolTable
*&ST
) {
130 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
131 if (BasicBlock
*P
= I
->getParent())
132 if (Function
*PP
= P
->getParent())
133 ST
= &PP
->getValueSymbolTable();
134 } else if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
)) {
135 if (Function
*P
= BB
->getParent())
136 ST
= &P
->getValueSymbolTable();
137 } else if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
138 if (Module
*P
= GV
->getParent())
139 ST
= &P
->getValueSymbolTable();
140 } else if (Argument
*A
= dyn_cast
<Argument
>(V
)) {
141 if (Function
*P
= A
->getParent())
142 ST
= &P
->getValueSymbolTable();
143 } else if (isa
<MDString
>(V
))
146 assert(isa
<Constant
>(V
) && "Unknown value type!");
147 return true; // no name is setable for this.
152 StringRef
Value::getName() const {
153 // Make sure the empty string is still a C string. For historical reasons,
154 // some clients want to call .data() on the result and expect it to be null
156 if (!Name
) return StringRef("", 0);
157 return Name
->getKey();
160 std::string
Value::getNameStr() const {
161 return getName().str();
164 void Value::setName(const Twine
&NewName
) {
165 // Fast path for common IRBuilder case of setName("") when there is no name.
166 if (NewName
.isTriviallyEmpty() && !hasName())
169 SmallString
<256> NameData
;
170 StringRef NameRef
= NewName
.toStringRef(NameData
);
172 // Name isn't changing?
173 if (getName() == NameRef
)
176 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
178 // Get the symbol table to update for this object.
179 ValueSymbolTable
*ST
;
180 if (getSymTab(this, ST
))
181 return; // Cannot set a name on this value (e.g. constant).
183 if (!ST
) { // No symbol table to update? Just do the change.
184 if (NameRef
.empty()) {
185 // Free the name for this value.
194 // NOTE: Could optimize for the case the name is shrinking to not deallocate
197 // Create the new name.
198 Name
= ValueName::Create(NameRef
.begin(), NameRef
.end());
199 Name
->setValue(this);
203 // NOTE: Could optimize for the case the name is shrinking to not deallocate
207 ST
->removeValueName(Name
);
215 // Name is changing to something new.
216 Name
= ST
->createValueName(NameRef
, this);
220 /// takeName - transfer the name from V to this value, setting V's name to
221 /// empty. It is an error to call V->takeName(V).
222 void Value::takeName(Value
*V
) {
223 ValueSymbolTable
*ST
= 0;
224 // If this value has a name, drop it.
226 // Get the symtab this is in.
227 if (getSymTab(this, ST
)) {
228 // We can't set a name on this value, but we need to clear V's name if
230 if (V
->hasName()) V
->setName("");
231 return; // Cannot set a name on this value (e.g. constant).
236 ST
->removeValueName(Name
);
241 // Now we know that this has no name.
243 // If V has no name either, we're done.
244 if (!V
->hasName()) return;
246 // Get this's symtab if we didn't before.
248 if (getSymTab(this, ST
)) {
251 return; // Cannot set a name on this value (e.g. constant).
255 // Get V's ST, this should always succed, because V has a name.
256 ValueSymbolTable
*VST
;
257 bool Failure
= getSymTab(V
, VST
);
258 assert(!Failure
&& "V has a name, so it should have a ST!"); (void)Failure
;
260 // If these values are both in the same symtab, we can do this very fast.
261 // This works even if both values have no symtab yet.
266 Name
->setValue(this);
270 // Otherwise, things are slightly more complex. Remove V's name from VST and
271 // then reinsert it into ST.
274 VST
->removeValueName(V
->Name
);
277 Name
->setValue(this);
280 ST
->reinsertValue(this);
284 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
285 // except that it doesn't have all of the asserts. The asserts fail because we
286 // are half-way done resolving types, which causes some types to exist as two
287 // different Type*'s at the same time. This is a sledgehammer to work around
290 void Value::uncheckedReplaceAllUsesWith(Value
*New
) {
291 // Notify all ValueHandles (if present) that this value is going away.
293 ValueHandleBase::ValueIsRAUWd(this, New
);
295 while (!use_empty()) {
297 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
298 // constant because they are uniqued.
299 if (Constant
*C
= dyn_cast
<Constant
>(U
.getUser())) {
300 if (!isa
<GlobalValue
>(C
)) {
301 C
->replaceUsesOfWithOnConstant(this, New
, &U
);
310 void Value::replaceAllUsesWith(Value
*New
) {
311 assert(New
&& "Value::replaceAllUsesWith(<null>) is invalid!");
312 assert(New
!= this && "this->replaceAllUsesWith(this) is NOT valid!");
313 assert(New
->getType() == getType() &&
314 "replaceAllUses of value with new value of different type!");
316 uncheckedReplaceAllUsesWith(New
);
319 Value
*Value::stripPointerCasts() {
320 if (!getType()->isPointerTy())
323 // Even though we don't look through PHI nodes, we could be called on an
324 // instruction in an unreachable block, which may be on a cycle.
325 SmallPtrSet
<Value
*, 4> Visited
;
330 if (GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(V
)) {
331 if (!GEP
->hasAllZeroIndices())
333 V
= GEP
->getPointerOperand();
334 } else if (Operator::getOpcode(V
) == Instruction::BitCast
) {
335 V
= cast
<Operator
>(V
)->getOperand(0);
336 } else if (GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(V
)) {
337 if (GA
->mayBeOverridden())
339 V
= GA
->getAliasee();
343 assert(V
->getType()->isPointerTy() && "Unexpected operand type!");
344 } while (Visited
.insert(V
));
349 /// isDereferenceablePointer - Test if this value is always a pointer to
350 /// allocated and suitably aligned memory for a simple load or store.
351 bool Value::isDereferenceablePointer() const {
352 // Note that it is not safe to speculate into a malloc'd region because
353 // malloc may return null.
354 // It's also not always safe to follow a bitcast, for example:
355 // bitcast i8* (alloca i8) to i32*
356 // would result in a 4-byte load from a 1-byte alloca. Some cases could
357 // be handled using TargetData to check sizes and alignments though.
359 // These are obviously ok.
360 if (isa
<AllocaInst
>(this)) return true;
362 // Global variables which can't collapse to null are ok.
363 if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(this))
364 return !GV
->hasExternalWeakLinkage();
366 // byval arguments are ok.
367 if (const Argument
*A
= dyn_cast
<Argument
>(this))
368 return A
->hasByValAttr();
370 // For GEPs, determine if the indexing lands within the allocated object.
371 if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(this)) {
372 // Conservatively require that the base pointer be fully dereferenceable.
373 if (!GEP
->getOperand(0)->isDereferenceablePointer())
375 // Check the indices.
376 gep_type_iterator GTI
= gep_type_begin(GEP
);
377 for (User::const_op_iterator I
= GEP
->op_begin()+1,
378 E
= GEP
->op_end(); I
!= E
; ++I
) {
380 const Type
*Ty
= *GTI
++;
381 // Struct indices can't be out of bounds.
382 if (isa
<StructType
>(Ty
))
384 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Index
);
387 // Zero is always ok.
390 // Check to see that it's within the bounds of an array.
391 const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
);
394 if (CI
->getValue().getActiveBits() > 64)
396 if (CI
->getZExtValue() >= ATy
->getNumElements())
399 // Indices check out; this is dereferenceable.
403 // If we don't know, assume the worst.
407 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
408 /// return the value in the PHI node corresponding to PredBB. If not, return
409 /// ourself. This is useful if you want to know the value something has in a
410 /// predecessor block.
411 Value
*Value::DoPHITranslation(const BasicBlock
*CurBB
,
412 const BasicBlock
*PredBB
) {
413 PHINode
*PN
= dyn_cast
<PHINode
>(this);
414 if (PN
&& PN
->getParent() == CurBB
)
415 return PN
->getIncomingValueForBlock(PredBB
);
419 LLVMContext
&Value::getContext() const { return VTy
->getContext(); }
421 //===----------------------------------------------------------------------===//
422 // ValueHandleBase Class
423 //===----------------------------------------------------------------------===//
425 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
426 /// List is known to point into the existing use list.
427 void ValueHandleBase::AddToExistingUseList(ValueHandleBase
**List
) {
428 assert(List
&& "Handle list is null?");
430 // Splice ourselves into the list.
435 Next
->setPrevPtr(&Next
);
436 assert(VP
== Next
->VP
&& "Added to wrong list?");
440 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase
*List
) {
441 assert(List
&& "Must insert after existing node");
444 setPrevPtr(&List
->Next
);
447 Next
->setPrevPtr(&Next
);
450 /// AddToUseList - Add this ValueHandle to the use list for VP.
451 void ValueHandleBase::AddToUseList() {
452 assert(VP
&& "Null pointer doesn't have a use list!");
454 LLVMContextImpl
*pImpl
= VP
->getContext().pImpl
;
456 if (VP
->HasValueHandle
) {
457 // If this value already has a ValueHandle, then it must be in the
458 // ValueHandles map already.
459 ValueHandleBase
*&Entry
= pImpl
->ValueHandles
[VP
];
460 assert(Entry
!= 0 && "Value doesn't have any handles?");
461 AddToExistingUseList(&Entry
);
465 // Ok, it doesn't have any handles yet, so we must insert it into the
466 // DenseMap. However, doing this insertion could cause the DenseMap to
467 // reallocate itself, which would invalidate all of the PrevP pointers that
468 // point into the old table. Handle this by checking for reallocation and
469 // updating the stale pointers only if needed.
470 DenseMap
<Value
*, ValueHandleBase
*> &Handles
= pImpl
->ValueHandles
;
471 const void *OldBucketPtr
= Handles
.getPointerIntoBucketsArray();
473 ValueHandleBase
*&Entry
= Handles
[VP
];
474 assert(Entry
== 0 && "Value really did already have handles?");
475 AddToExistingUseList(&Entry
);
476 VP
->HasValueHandle
= true;
478 // If reallocation didn't happen or if this was the first insertion, don't
480 if (Handles
.isPointerIntoBucketsArray(OldBucketPtr
) ||
481 Handles
.size() == 1) {
485 // Okay, reallocation did happen. Fix the Prev Pointers.
486 for (DenseMap
<Value
*, ValueHandleBase
*>::iterator I
= Handles
.begin(),
487 E
= Handles
.end(); I
!= E
; ++I
) {
488 assert(I
->second
&& I
->first
== I
->second
->VP
&& "List invariant broken!");
489 I
->second
->setPrevPtr(&I
->second
);
493 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
494 void ValueHandleBase::RemoveFromUseList() {
495 assert(VP
&& VP
->HasValueHandle
&& "Pointer doesn't have a use list!");
497 // Unlink this from its use list.
498 ValueHandleBase
**PrevPtr
= getPrevPtr();
499 assert(*PrevPtr
== this && "List invariant broken");
503 assert(Next
->getPrevPtr() == &Next
&& "List invariant broken");
504 Next
->setPrevPtr(PrevPtr
);
508 // If the Next pointer was null, then it is possible that this was the last
509 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
511 LLVMContextImpl
*pImpl
= VP
->getContext().pImpl
;
512 DenseMap
<Value
*, ValueHandleBase
*> &Handles
= pImpl
->ValueHandles
;
513 if (Handles
.isPointerIntoBucketsArray(PrevPtr
)) {
515 VP
->HasValueHandle
= false;
520 void ValueHandleBase::ValueIsDeleted(Value
*V
) {
521 assert(V
->HasValueHandle
&& "Should only be called if ValueHandles present");
523 // Get the linked list base, which is guaranteed to exist since the
524 // HasValueHandle flag is set.
525 LLVMContextImpl
*pImpl
= V
->getContext().pImpl
;
526 ValueHandleBase
*Entry
= pImpl
->ValueHandles
[V
];
527 assert(Entry
&& "Value bit set but no entries exist");
529 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
530 // and remove themselves from the list without breaking our iteration. This
531 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
532 // Note that we deliberately do not the support the case when dropping a value
533 // handle results in a new value handle being permanently added to the list
534 // (as might occur in theory for CallbackVH's): the new value handle will not
535 // be processed and the checking code will mete out righteous punishment if
536 // the handle is still present once we have finished processing all the other
537 // value handles (it is fine to momentarily add then remove a value handle).
538 for (ValueHandleBase
Iterator(Assert
, *Entry
); Entry
; Entry
= Iterator
.Next
) {
539 Iterator
.RemoveFromUseList();
540 Iterator
.AddToExistingUseListAfter(Entry
);
541 assert(Entry
->Next
== &Iterator
&& "Loop invariant broken.");
543 switch (Entry
->getKind()) {
547 // Mark that this value has been deleted by setting it to an invalid Value
549 Entry
->operator=(DenseMapInfo
<Value
*>::getTombstoneKey());
552 // Weak just goes to null, which will unlink it from the list.
556 // Forward to the subclass's implementation.
557 static_cast<CallbackVH
*>(Entry
)->deleted();
562 // All callbacks, weak references, and assertingVHs should be dropped by now.
563 if (V
->HasValueHandle
) {
564 #ifndef NDEBUG // Only in +Asserts mode...
565 dbgs() << "While deleting: " << *V
->getType() << " %" << V
->getNameStr()
567 if (pImpl
->ValueHandles
[V
]->getKind() == Assert
)
568 llvm_unreachable("An asserting value handle still pointed to this"
572 llvm_unreachable("All references to V were not removed?");
577 void ValueHandleBase::ValueIsRAUWd(Value
*Old
, Value
*New
) {
578 assert(Old
->HasValueHandle
&&"Should only be called if ValueHandles present");
579 assert(Old
!= New
&& "Changing value into itself!");
581 // Get the linked list base, which is guaranteed to exist since the
582 // HasValueHandle flag is set.
583 LLVMContextImpl
*pImpl
= Old
->getContext().pImpl
;
584 ValueHandleBase
*Entry
= pImpl
->ValueHandles
[Old
];
586 assert(Entry
&& "Value bit set but no entries exist");
588 // We use a local ValueHandleBase as an iterator so that
589 // ValueHandles can add and remove themselves from the list without
590 // breaking our iteration. This is not really an AssertingVH; we
591 // just have to give ValueHandleBase some kind.
592 for (ValueHandleBase
Iterator(Assert
, *Entry
); Entry
; Entry
= Iterator
.Next
) {
593 Iterator
.RemoveFromUseList();
594 Iterator
.AddToExistingUseListAfter(Entry
);
595 assert(Entry
->Next
== &Iterator
&& "Loop invariant broken.");
597 switch (Entry
->getKind()) {
599 // Asserting handle does not follow RAUW implicitly.
602 // Tracking goes to new value like a WeakVH. Note that this may make it
603 // something incompatible with its templated type. We don't want to have a
604 // virtual (or inline) interface to handle this though, so instead we make
605 // the TrackingVH accessors guarantee that a client never sees this value.
609 // Weak goes to the new value, which will unlink it from Old's list.
610 Entry
->operator=(New
);
613 // Forward to the subclass's implementation.
614 static_cast<CallbackVH
*>(Entry
)->allUsesReplacedWith(New
);
620 // If any new tracking or weak value handles were added while processing the
621 // list, then complain about it now.
622 if (Old
->HasValueHandle
)
623 for (Entry
= pImpl
->ValueHandles
[Old
]; Entry
; Entry
= Entry
->Next
)
624 switch (Entry
->getKind()) {
627 dbgs() << "After RAUW from " << *Old
->getType() << " %"
628 << Old
->getNameStr() << " to " << *New
->getType() << " %"
629 << New
->getNameStr() << "\n";
630 llvm_unreachable("A tracking or weak value handle still pointed to the"
638 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
640 CallbackVH::~CallbackVH() {}