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/Operator.h"
20 #include "llvm/Module.h"
21 #include "llvm/ValueSymbolTable.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/System/RWMutex.h"
29 #include "llvm/System/Threading.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), SubclassOptionalData(0),
45 SubclassData(0), VTy(checkType(ty)),
47 if (isa<CallInst>(this) || isa<InvokeInst>(this))
48 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
49 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
50 "invalid CallInst type!");
51 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
52 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
53 isa<OpaqueType>(ty)) &&
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 cerr << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
71 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
72 cerr << "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 use_const_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 use_const_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 (use_const_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();
144 assert(isa<Constant>(V) && "Unknown value type!");
145 return true; // no name is setable for this.
150 /// getNameStart - Return a pointer to a null terminated string for this name.
151 /// Note that names can have null characters within the string as well as at
152 /// their end. This always returns a non-null pointer.
153 const char *Value::getNameStart() const {
154 if (Name == 0) return "";
155 return Name->getKeyData();
158 /// getNameLen - Return the length of the string, correctly handling nul
159 /// characters embedded into them.
160 unsigned Value::getNameLen() const {
161 return Name ? Name->getKeyLength() : 0;
164 /// isName - Return true if this value has the name specified by the provided
165 /// nul terminated string.
166 bool Value::isName(const char *N) const {
167 unsigned InLen = strlen(N);
168 return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
172 std::string Value::getNameStr() const {
173 if (Name == 0) return "";
174 return std::string(Name->getKeyData(),
175 Name->getKeyData()+Name->getKeyLength());
178 void Value::setName(const std::string &name) {
179 setName(&name[0], name.size());
182 void Value::setName(const char *Name) {
183 setName(Name, Name ? strlen(Name) : 0);
186 void Value::setName(const char *NameStr, unsigned NameLen) {
187 if (NameLen == 0 && !hasName()) return;
188 assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
190 // Get the symbol table to update for this object.
191 ValueSymbolTable *ST;
192 if (getSymTab(this, ST))
193 return; // Cannot set a name on this value (e.g. constant).
195 if (!ST) { // No symbol table to update? Just do the change.
197 // Free the name for this value.
204 // Name isn't changing?
205 if (NameLen == Name->getKeyLength() &&
206 !memcmp(Name->getKeyData(), NameStr, NameLen))
211 // NOTE: Could optimize for the case the name is shrinking to not deallocate
214 // Create the new name.
215 Name = ValueName::Create(NameStr, NameStr+NameLen);
216 Name->setValue(this);
220 // NOTE: Could optimize for the case the name is shrinking to not deallocate
223 // Name isn't changing?
224 if (NameLen == Name->getKeyLength() &&
225 !memcmp(Name->getKeyData(), NameStr, NameLen))
229 ST->removeValueName(Name);
237 // Name is changing to something new.
238 Name = ST->createValueName(NameStr, NameLen, this);
242 /// takeName - transfer the name from V to this value, setting V's name to
243 /// empty. It is an error to call V->takeName(V).
244 void Value::takeName(Value *V) {
245 ValueSymbolTable *ST = 0;
246 // If this value has a name, drop it.
248 // Get the symtab this is in.
249 if (getSymTab(this, ST)) {
250 // We can't set a name on this value, but we need to clear V's name if
252 if (V->hasName()) V->setName(0, 0);
253 return; // Cannot set a name on this value (e.g. constant).
258 ST->removeValueName(Name);
263 // Now we know that this has no name.
265 // If V has no name either, we're done.
266 if (!V->hasName()) return;
268 // Get this's symtab if we didn't before.
270 if (getSymTab(this, ST)) {
273 return; // Cannot set a name on this value (e.g. constant).
277 // Get V's ST, this should always succed, because V has a name.
278 ValueSymbolTable *VST;
279 bool Failure = getSymTab(V, VST);
280 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
282 // If these values are both in the same symtab, we can do this very fast.
283 // This works even if both values have no symtab yet.
288 Name->setValue(this);
292 // Otherwise, things are slightly more complex. Remove V's name from VST and
293 // then reinsert it into ST.
296 VST->removeValueName(V->Name);
299 Name->setValue(this);
302 ST->reinsertValue(this);
306 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
307 // except that it doesn't have all of the asserts. The asserts fail because we
308 // are half-way done resolving types, which causes some types to exist as two
309 // different Type*'s at the same time. This is a sledgehammer to work around
312 void Value::uncheckedReplaceAllUsesWith(Value *New) {
313 // Notify all ValueHandles (if present) that this value is going away.
315 ValueHandleBase::ValueIsRAUWd(this, New);
317 while (!use_empty()) {
319 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
320 // constant because they are uniqued.
321 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
322 if (!isa<GlobalValue>(C)) {
323 C->replaceUsesOfWithOnConstant(this, New, &U);
332 void Value::replaceAllUsesWith(Value *New) {
333 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
334 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
335 assert(New->getType() == getType() &&
336 "replaceAllUses of value with new value of different type!");
338 uncheckedReplaceAllUsesWith(New);
341 Value *Value::stripPointerCasts() {
342 if (!isa<PointerType>(getType()))
346 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
347 if (!GEP->hasAllZeroIndices())
349 V = GEP->getPointerOperand();
350 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
351 V = cast<Operator>(V)->getOperand(0);
355 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
359 Value *Value::getUnderlyingObject() {
360 if (!isa<PointerType>(getType()))
363 unsigned MaxLookup = 6;
365 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
366 if (GEP->hasNoPointerOverflow())
368 V = GEP->getPointerOperand();
369 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
370 V = cast<Operator>(V)->getOperand(0);
374 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
375 } while (--MaxLookup);
379 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
380 /// return the value in the PHI node corresponding to PredBB. If not, return
381 /// ourself. This is useful if you want to know the value something has in a
382 /// predecessor block.
383 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
384 const BasicBlock *PredBB) {
385 PHINode *PN = dyn_cast<PHINode>(this);
386 if (PN && PN->getParent() == CurBB)
387 return PN->getIncomingValueForBlock(PredBB);
391 //===----------------------------------------------------------------------===//
392 // ValueHandleBase Class
393 //===----------------------------------------------------------------------===//
395 /// ValueHandles - This map keeps track of all of the value handles that are
396 /// watching a Value*. The Value::HasValueHandle bit is used to know whether or
397 /// not a value has an entry in this map.
398 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
399 static ManagedStatic<ValueHandlesTy> ValueHandles;
400 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
402 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
403 /// List is known to point into the existing use list.
404 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
405 assert(List && "Handle list is null?");
407 // Splice ourselves into the list.
412 Next->setPrevPtr(&Next);
413 assert(VP == Next->VP && "Added to wrong list?");
417 /// AddToUseList - Add this ValueHandle to the use list for VP.
418 void ValueHandleBase::AddToUseList() {
419 assert(VP && "Null pointer doesn't have a use list!");
420 if (VP->HasValueHandle) {
421 // If this value already has a ValueHandle, then it must be in the
422 // ValueHandles map already.
423 sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
424 ValueHandleBase *&Entry = (*ValueHandles)[VP];
425 assert(Entry != 0 && "Value doesn't have any handles?");
426 AddToExistingUseList(&Entry);
430 // Ok, it doesn't have any handles yet, so we must insert it into the
431 // DenseMap. However, doing this insertion could cause the DenseMap to
432 // reallocate itself, which would invalidate all of the PrevP pointers that
433 // point into the old table. Handle this by checking for reallocation and
434 // updating the stale pointers only if needed.
435 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
436 ValueHandlesTy &Handles = *ValueHandles;
437 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
439 ValueHandleBase *&Entry = Handles[VP];
440 assert(Entry == 0 && "Value really did already have handles?");
441 AddToExistingUseList(&Entry);
442 VP->HasValueHandle = true;
444 // If reallocation didn't happen or if this was the first insertion, don't
446 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
447 Handles.size() == 1) {
451 // Okay, reallocation did happen. Fix the Prev Pointers.
452 for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
454 assert(I->second && I->first == I->second->VP && "List invariant broken!");
455 I->second->setPrevPtr(&I->second);
459 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
460 void ValueHandleBase::RemoveFromUseList() {
461 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
463 // Unlink this from its use list.
464 ValueHandleBase **PrevPtr = getPrevPtr();
465 assert(*PrevPtr == this && "List invariant broken");
469 assert(Next->getPrevPtr() == &Next && "List invariant broken");
470 Next->setPrevPtr(PrevPtr);
474 // If the Next pointer was null, then it is possible that this was the last
475 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
477 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
478 ValueHandlesTy &Handles = *ValueHandles;
479 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
481 VP->HasValueHandle = false;
486 void ValueHandleBase::ValueIsDeleted(Value *V) {
487 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
489 // Get the linked list base, which is guaranteed to exist since the
490 // HasValueHandle flag is set.
491 ValueHandlesLock->reader_acquire();
492 ValueHandleBase *Entry = (*ValueHandles)[V];
493 ValueHandlesLock->reader_release();
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 llvm_unreachable("An asserting value handle still pointed to this"
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 ValueHandlesLock->reader_acquire();
532 ValueHandleBase *Entry = (*ValueHandles)[Old];
533 ValueHandlesLock->reader_release();
534 assert(Entry && "Value bit set but no entries exist");
537 // Advance pointer to avoid invalidation.
538 ValueHandleBase *ThisNode = Entry;
541 switch (ThisNode->getKind()) {
543 // Asserting handle does not follow RAUW implicitly.
546 // Weak goes to the new value, which will unlink it from Old's list.
547 ThisNode->operator=(New);
550 // Forward to the subclass's implementation.
551 static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
557 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
559 CallbackVH::~CallbackVH() {}
562 //===----------------------------------------------------------------------===//
564 //===----------------------------------------------------------------------===//
566 // replaceUsesOfWith - Replaces all references to the "From" definition with
567 // references to the "To" definition.
569 void User::replaceUsesOfWith(Value *From, Value *To) {
570 if (From == To) return; // Duh what?
572 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
573 "Cannot call User::replaceUsesofWith on a constant!");
575 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
576 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
577 // The side effects of this setOperand call include linking to
578 // "To", adding "this" to the uses list of To, and
579 // most importantly, removing "this" from the use list of "From".
580 setOperand(i, To); // Fix it now...