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 "llvm/Constant.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/InstrTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/LeakDetector.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "llvm/ADT/DenseMap.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 static inline const Type
*checkType(const Type
*Ty
) {
34 assert(Ty
&& "Value defined with a null type: Error!");
38 Value::Value(const Type
*ty
, unsigned scid
)
39 : SubclassID(scid
), HasValueHandle(0), SubclassData(0), VTy(checkType(ty
)),
41 if (isa
<CallInst
>(this) || isa
<InvokeInst
>(this))
42 assert((VTy
->isFirstClassType() || VTy
== Type::VoidTy
||
43 isa
<OpaqueType
>(ty
) || VTy
->getTypeID() == Type::StructTyID
) &&
44 "invalid CallInst type!");
45 else if (!isa
<Constant
>(this) && !isa
<BasicBlock
>(this))
46 assert((VTy
->isFirstClassType() || VTy
== Type::VoidTy
||
47 isa
<OpaqueType
>(ty
)) &&
48 "Cannot create non-first-class values except for constants!");
52 // Notify all ValueHandles (if present) that this value is going away.
54 ValueHandleBase::ValueIsDeleted(this);
56 #ifndef NDEBUG // Only in -g mode...
57 // Check to make sure that there are no uses of this value that are still
58 // around when the value is destroyed. If there are, then we have a dangling
59 // reference and something is wrong. This code is here to print out what is
60 // still being referenced. The value in question should be printed as
64 cerr
<< "While deleting: " << *VTy
<< " %" << getNameStr() << "\n";
65 for (use_iterator I
= use_begin(), E
= use_end(); I
!= E
; ++I
)
66 cerr
<< "Use still stuck around after Def is destroyed:"
70 assert(use_empty() && "Uses remain when a value is destroyed!");
72 // If this value is named, destroy the name. This should not be in a symtab
77 // There should be no uses of this object anymore, remove it.
78 LeakDetector::removeGarbageObject(this);
81 /// hasNUses - Return true if this Value has exactly N users.
83 bool Value::hasNUses(unsigned N
) const {
84 use_const_iterator UI
= use_begin(), E
= use_end();
87 if (UI
== E
) return false; // Too few.
91 /// hasNUsesOrMore - Return true if this value has N users or more. This is
92 /// logically equivalent to getNumUses() >= N.
94 bool Value::hasNUsesOrMore(unsigned N
) const {
95 use_const_iterator UI
= use_begin(), E
= use_end();
98 if (UI
== E
) return false; // Too few.
103 /// isUsedInBasicBlock - Return true if this value is used in the specified
105 bool Value::isUsedInBasicBlock(const BasicBlock
*BB
) const {
106 for (use_const_iterator I
= use_begin(), E
= use_end(); I
!= E
; ++I
) {
107 const Instruction
*User
= dyn_cast
<Instruction
>(*I
);
108 if (User
&& User
->getParent() == BB
)
115 /// getNumUses - This method computes the number of uses of this Value. This
116 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
118 unsigned Value::getNumUses() const {
119 return (unsigned)std::distance(use_begin(), use_end());
122 static bool getSymTab(Value
*V
, ValueSymbolTable
*&ST
) {
124 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
125 if (BasicBlock
*P
= I
->getParent())
126 if (Function
*PP
= P
->getParent())
127 ST
= &PP
->getValueSymbolTable();
128 } else if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
)) {
129 if (Function
*P
= BB
->getParent())
130 ST
= &P
->getValueSymbolTable();
131 } else if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
132 if (Module
*P
= GV
->getParent())
133 ST
= &P
->getValueSymbolTable();
134 } else if (Argument
*A
= dyn_cast
<Argument
>(V
)) {
135 if (Function
*P
= A
->getParent())
136 ST
= &P
->getValueSymbolTable();
138 assert(isa
<Constant
>(V
) && "Unknown value type!");
139 return true; // no name is setable for this.
144 /// getNameStart - Return a pointer to a null terminated string for this name.
145 /// Note that names can have null characters within the string as well as at
146 /// their end. This always returns a non-null pointer.
147 const char *Value::getNameStart() const {
148 if (Name
== 0) return "";
149 return Name
->getKeyData();
152 /// getNameLen - Return the length of the string, correctly handling nul
153 /// characters embedded into them.
154 unsigned Value::getNameLen() const {
155 return Name
? Name
->getKeyLength() : 0;
158 /// isName - Return true if this value has the name specified by the provided
159 /// nul terminated string.
160 bool Value::isName(const char *N
) const {
161 unsigned InLen
= strlen(N
);
162 return InLen
== getNameLen() && memcmp(getNameStart(), N
, InLen
) == 0;
166 std::string
Value::getNameStr() const {
167 if (Name
== 0) return "";
168 return std::string(Name
->getKeyData(),
169 Name
->getKeyData()+Name
->getKeyLength());
172 void Value::setName(const std::string
&name
) {
173 setName(&name
[0], name
.size());
176 void Value::setName(const char *Name
) {
177 setName(Name
, Name
? strlen(Name
) : 0);
180 void Value::setName(const char *NameStr
, unsigned NameLen
) {
181 if (NameLen
== 0 && !hasName()) return;
182 assert(getType() != Type::VoidTy
&& "Cannot assign a name to void values!");
184 // Get the symbol table to update for this object.
185 ValueSymbolTable
*ST
;
186 if (getSymTab(this, ST
))
187 return; // Cannot set a name on this value (e.g. constant).
189 if (!ST
) { // No symbol table to update? Just do the change.
191 // Free the name for this value.
198 // Name isn't changing?
199 if (NameLen
== Name
->getKeyLength() &&
200 !memcmp(Name
->getKeyData(), NameStr
, NameLen
))
205 // NOTE: Could optimize for the case the name is shrinking to not deallocate
208 // Create the new name.
209 Name
= ValueName::Create(NameStr
, NameStr
+NameLen
);
210 Name
->setValue(this);
214 // NOTE: Could optimize for the case the name is shrinking to not deallocate
217 // Name isn't changing?
218 if (NameLen
== Name
->getKeyLength() &&
219 !memcmp(Name
->getKeyData(), NameStr
, NameLen
))
223 ST
->removeValueName(Name
);
231 // Name is changing to something new.
232 Name
= ST
->createValueName(NameStr
, NameLen
, this);
236 /// takeName - transfer the name from V to this value, setting V's name to
237 /// empty. It is an error to call V->takeName(V).
238 void Value::takeName(Value
*V
) {
239 ValueSymbolTable
*ST
= 0;
240 // If this value has a name, drop it.
242 // Get the symtab this is in.
243 if (getSymTab(this, ST
)) {
244 // We can't set a name on this value, but we need to clear V's name if
246 if (V
->hasName()) V
->setName(0, 0);
247 return; // Cannot set a name on this value (e.g. constant).
252 ST
->removeValueName(Name
);
257 // Now we know that this has no name.
259 // If V has no name either, we're done.
260 if (!V
->hasName()) return;
262 // Get this's symtab if we didn't before.
264 if (getSymTab(this, ST
)) {
267 return; // Cannot set a name on this value (e.g. constant).
271 // Get V's ST, this should always succed, because V has a name.
272 ValueSymbolTable
*VST
;
273 bool Failure
= getSymTab(V
, VST
);
274 assert(!Failure
&& "V has a name, so it should have a ST!"); Failure
=Failure
;
276 // If these values are both in the same symtab, we can do this very fast.
277 // This works even if both values have no symtab yet.
282 Name
->setValue(this);
286 // Otherwise, things are slightly more complex. Remove V's name from VST and
287 // then reinsert it into ST.
290 VST
->removeValueName(V
->Name
);
293 Name
->setValue(this);
296 ST
->reinsertValue(this);
300 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
301 // except that it doesn't have all of the asserts. The asserts fail because we
302 // are half-way done resolving types, which causes some types to exist as two
303 // different Type*'s at the same time. This is a sledgehammer to work around
306 void Value::uncheckedReplaceAllUsesWith(Value
*New
) {
307 // Notify all ValueHandles (if present) that this value is going away.
309 ValueHandleBase::ValueIsRAUWd(this, New
);
311 while (!use_empty()) {
313 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
314 // constant because they are uniqued.
315 if (Constant
*C
= dyn_cast
<Constant
>(U
.getUser())) {
316 if (!isa
<GlobalValue
>(C
)) {
317 C
->replaceUsesOfWithOnConstant(this, New
, &U
);
326 void Value::replaceAllUsesWith(Value
*New
) {
327 assert(New
&& "Value::replaceAllUsesWith(<null>) is invalid!");
328 assert(New
!= this && "this->replaceAllUsesWith(this) is NOT valid!");
329 assert(New
->getType() == getType() &&
330 "replaceAllUses of value with new value of different type!");
332 uncheckedReplaceAllUsesWith(New
);
335 Value
*Value::stripPointerCasts() {
336 if (!isa
<PointerType
>(getType()))
340 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
)) {
341 if (CE
->getOpcode() == Instruction::GetElementPtr
) {
342 for (unsigned i
= 1, e
= CE
->getNumOperands(); i
!= e
; ++i
)
343 if (!CE
->getOperand(i
)->isNullValue())
345 V
= CE
->getOperand(0);
346 } else if (CE
->getOpcode() == Instruction::BitCast
) {
347 V
= CE
->getOperand(0);
351 } else if (GetElementPtrInst
*GEP
= dyn_cast
<GetElementPtrInst
>(V
)) {
352 if (!GEP
->hasAllZeroIndices())
354 V
= GEP
->getOperand(0);
355 } else if (BitCastInst
*CI
= dyn_cast
<BitCastInst
>(V
)) {
356 V
= CI
->getOperand(0);
360 assert(isa
<PointerType
>(V
->getType()) && "Unexpected operand type!");
364 Value
*Value::getUnderlyingObject() {
365 if (!isa
<PointerType
>(getType()))
368 unsigned MaxLookup
= 6;
370 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
371 if (!isa
<BitCastInst
>(I
) && !isa
<GetElementPtrInst
>(I
))
373 V
= I
->getOperand(0);
374 } else if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
)) {
375 if (CE
->getOpcode() != Instruction::BitCast
&&
376 CE
->getOpcode() != Instruction::GetElementPtr
)
378 V
= CE
->getOperand(0);
382 assert(isa
<PointerType
>(V
->getType()) && "Unexpected operand type!");
383 } while (--MaxLookup
);
387 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
388 /// return the value in the PHI node corresponding to PredBB. If not, return
389 /// ourself. This is useful if you want to know the value something has in a
390 /// predecessor block.
391 Value
*Value::DoPHITranslation(const BasicBlock
*CurBB
,
392 const BasicBlock
*PredBB
) {
393 PHINode
*PN
= dyn_cast
<PHINode
>(this);
394 if (PN
&& PN
->getParent() == CurBB
)
395 return PN
->getIncomingValueForBlock(PredBB
);
399 //===----------------------------------------------------------------------===//
400 // ValueHandleBase Class
401 //===----------------------------------------------------------------------===//
403 /// ValueHandles - This map keeps track of all of the value handles that are
404 /// watching a Value*. The Value::HasValueHandle bit is used to know whether or
405 /// not a value has an entry in this map.
406 typedef DenseMap
<Value
*, ValueHandleBase
*> ValueHandlesTy
;
407 static ManagedStatic
<ValueHandlesTy
> ValueHandles
;
409 /// AddToUseList - Add this ValueHandle to the use list for VP, where List is
410 /// known to point into the existing use list.
411 void ValueHandleBase::AddToExistingUseList(ValueHandleBase
**List
) {
412 assert(List
&& "Handle list is null?");
414 // Splice ourselves into the list.
419 Next
->setPrevPtr(&Next
);
420 assert(VP
== Next
->VP
&& "Added to wrong list?");
424 /// AddToUseList - Add this ValueHandle to the use list for VP.
425 void ValueHandleBase::AddToUseList() {
426 assert(VP
&& "Null pointer doesn't have a use list!");
427 if (VP
->HasValueHandle
) {
428 // If this value already has a ValueHandle, then it must be in the
429 // ValueHandles map already.
430 ValueHandleBase
*&Entry
= (*ValueHandles
)[VP
];
431 assert(Entry
!= 0 && "Value doesn't have any handles?");
432 return AddToExistingUseList(&Entry
);
435 // Ok, it doesn't have any handles yet, so we must insert it into the
436 // DenseMap. However, doing this insertion could cause the DenseMap to
437 // reallocate itself, which would invalidate all of the PrevP pointers that
438 // point into the old table. Handle this by checking for reallocation and
439 // updating the stale pointers only if needed.
440 ValueHandlesTy
&Handles
= *ValueHandles
;
441 const void *OldBucketPtr
= Handles
.getPointerIntoBucketsArray();
443 ValueHandleBase
*&Entry
= Handles
[VP
];
444 assert(Entry
== 0 && "Value really did already have handles?");
445 AddToExistingUseList(&Entry
);
446 VP
->HasValueHandle
= 1;
448 // If reallocation didn't happen or if this was the first insertion, don't
450 if (Handles
.isPointerIntoBucketsArray(OldBucketPtr
) ||
454 // Okay, reallocation did happen. Fix the Prev Pointers.
455 for (ValueHandlesTy::iterator I
= Handles
.begin(), E
= Handles
.end();
457 assert(I
->second
&& I
->first
== I
->second
->VP
&& "List invariant broken!");
458 I
->second
->setPrevPtr(&I
->second
);
462 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
463 void ValueHandleBase::RemoveFromUseList() {
464 assert(VP
&& VP
->HasValueHandle
&& "Pointer doesn't have a use list!");
466 // Unlink this from its use list.
467 ValueHandleBase
**PrevPtr
= getPrevPtr();
468 assert(*PrevPtr
== this && "List invariant broken");
472 assert(Next
->getPrevPtr() == &Next
&& "List invariant broken");
473 Next
->setPrevPtr(PrevPtr
);
477 // If the Next pointer was null, then it is possible that this was the last
478 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
480 ValueHandlesTy
&Handles
= *ValueHandles
;
481 if (Handles
.isPointerIntoBucketsArray(PrevPtr
)) {
483 VP
->HasValueHandle
= false;
488 void ValueHandleBase::ValueIsDeleted(Value
*V
) {
489 assert(V
->HasValueHandle
&& "Should only be called if ValueHandles present");
491 // Get the linked list base, which is guaranteed to exist since the
492 // HasValueHandle flag is set.
493 ValueHandleBase
*Entry
= (*ValueHandles
)[V
];
494 assert(Entry
&& "Value bit set but no entries exist");
497 // Advance pointer to avoid invalidation.
498 ValueHandleBase
*ThisNode
= Entry
;
501 switch (ThisNode
->getKind()) {
503 #ifndef NDEBUG // Only in -g mode...
504 cerr
<< "While deleting: " << *V
->getType() << " %" << V
->getNameStr()
507 cerr
<< "An asserting value handle still pointed to this value!\n";
510 // Weak just goes to null, which will unlink it from the list.
511 ThisNode
->operator=(0);
514 // Forward to the subclass's implementation.
515 static_cast<CallbackVH
*>(ThisNode
)->deleted();
520 // All callbacks and weak references should be dropped by now.
521 assert(!V
->HasValueHandle
&& "All references to V were not removed?");
525 void ValueHandleBase::ValueIsRAUWd(Value
*Old
, Value
*New
) {
526 assert(Old
->HasValueHandle
&&"Should only be called if ValueHandles present");
527 assert(Old
!= New
&& "Changing value into itself!");
529 // Get the linked list base, which is guaranteed to exist since the
530 // HasValueHandle flag is set.
531 ValueHandleBase
*Entry
= (*ValueHandles
)[Old
];
532 assert(Entry
&& "Value bit set but no entries exist");
535 // Advance pointer to avoid invalidation.
536 ValueHandleBase
*ThisNode
= Entry
;
539 switch (ThisNode
->getKind()) {
541 // Asserting handle does not follow RAUW implicitly.
544 // Weak goes to the new value, which will unlink it from Old's list.
545 ThisNode
->operator=(New
);
548 // Forward to the subclass's implementation.
549 static_cast<CallbackVH
*>(ThisNode
)->allUsesReplacedWith(New
);
555 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
557 CallbackVH::~CallbackVH() {}
560 //===----------------------------------------------------------------------===//
562 //===----------------------------------------------------------------------===//
564 // replaceUsesOfWith - Replaces all references to the "From" definition with
565 // references to the "To" definition.
567 void User::replaceUsesOfWith(Value
*From
, Value
*To
) {
568 if (From
== To
) return; // Duh what?
570 assert((!isa
<Constant
>(this) || isa
<GlobalValue
>(this)) &&
571 "Cannot call User::replaceUsesofWith on a constant!");
573 for (unsigned i
= 0, E
= getNumOperands(); i
!= E
; ++i
)
574 if (getOperand(i
) == From
) { // Is This operand is pointing to oldval?
575 // The side effects of this setOperand call include linking to
576 // "To", adding "this" to the uses list of To, and
577 // most importantly, removing "this" from the use list of "From".
578 setOperand(i
, To
); // Fix it now...