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/ErrorHandling.h"
23 #include "llvm/Support/LeakDetector.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/RWMutex.h"
28 #include "llvm/System/Threading.h"
29 #include "llvm/ADT/DenseMap.h"
33 //===----------------------------------------------------------------------===//
35 //===----------------------------------------------------------------------===//
37 static inline const Type *checkType(const Type *Ty) {
38 assert(Ty && "Value defined with a null type: Error!");
42 Value::Value(const Type *ty, unsigned scid)
43 : SubclassID(scid), HasValueHandle(0), SubclassData(0), VTy(checkType(ty)),
45 if (isa<CallInst>(this) || isa<InvokeInst>(this))
46 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
47 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
48 "invalid CallInst type!");
49 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
50 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
51 isa<OpaqueType>(ty)) &&
52 "Cannot create non-first-class values except for constants!");
56 // Notify all ValueHandles (if present) that this value is going away.
58 ValueHandleBase::ValueIsDeleted(this);
60 #ifndef NDEBUG // Only in -g mode...
61 // Check to make sure that there are no uses of this value that are still
62 // around when the value is destroyed. If there are, then we have a dangling
63 // reference and something is wrong. This code is here to print out what is
64 // still being referenced. The value in question should be printed as
68 cerr << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
69 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
70 cerr << "Use still stuck around after Def is destroyed:"
74 assert(use_empty() && "Uses remain when a value is destroyed!");
76 // If this value is named, destroy the name. This should not be in a symtab
81 // There should be no uses of this object anymore, remove it.
82 LeakDetector::removeGarbageObject(this);
85 /// hasNUses - Return true if this Value has exactly N users.
87 bool Value::hasNUses(unsigned N) const {
88 use_const_iterator UI = use_begin(), E = use_end();
91 if (UI == E) return false; // Too few.
95 /// hasNUsesOrMore - Return true if this value has N users or more. This is
96 /// logically equivalent to getNumUses() >= N.
98 bool Value::hasNUsesOrMore(unsigned N) const {
99 use_const_iterator UI = use_begin(), E = use_end();
102 if (UI == E) return false; // Too few.
107 /// isUsedInBasicBlock - Return true if this value is used in the specified
109 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
110 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
111 const Instruction *User = dyn_cast<Instruction>(*I);
112 if (User && User->getParent() == BB)
119 /// getNumUses - This method computes the number of uses of this Value. This
120 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
122 unsigned Value::getNumUses() const {
123 return (unsigned)std::distance(use_begin(), use_end());
126 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
128 if (Instruction *I = dyn_cast<Instruction>(V)) {
129 if (BasicBlock *P = I->getParent())
130 if (Function *PP = P->getParent())
131 ST = &PP->getValueSymbolTable();
132 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
133 if (Function *P = BB->getParent())
134 ST = &P->getValueSymbolTable();
135 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
136 if (Module *P = GV->getParent())
137 ST = &P->getValueSymbolTable();
138 } else if (Argument *A = dyn_cast<Argument>(V)) {
139 if (Function *P = A->getParent())
140 ST = &P->getValueSymbolTable();
142 assert(isa<Constant>(V) && "Unknown value type!");
143 return true; // no name is setable for this.
148 /// getNameStart - Return a pointer to a null terminated string for this name.
149 /// Note that names can have null characters within the string as well as at
150 /// their end. This always returns a non-null pointer.
151 const char *Value::getNameStart() const {
152 if (Name == 0) return "";
153 return Name->getKeyData();
156 /// getNameLen - Return the length of the string, correctly handling nul
157 /// characters embedded into them.
158 unsigned Value::getNameLen() const {
159 return Name ? Name->getKeyLength() : 0;
162 /// isName - Return true if this value has the name specified by the provided
163 /// nul terminated string.
164 bool Value::isName(const char *N) const {
165 unsigned InLen = strlen(N);
166 return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
170 std::string Value::getNameStr() const {
171 if (Name == 0) return "";
172 return std::string(Name->getKeyData(),
173 Name->getKeyData()+Name->getKeyLength());
176 void Value::setName(const std::string &name) {
177 setName(&name[0], name.size());
180 void Value::setName(const char *Name) {
181 setName(Name, Name ? strlen(Name) : 0);
184 void Value::setName(const char *NameStr, unsigned NameLen) {
185 if (NameLen == 0 && !hasName()) return;
186 assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
188 // Get the symbol table to update for this object.
189 ValueSymbolTable *ST;
190 if (getSymTab(this, ST))
191 return; // Cannot set a name on this value (e.g. constant).
193 if (!ST) { // No symbol table to update? Just do the change.
195 // Free the name for this value.
202 // Name isn't changing?
203 if (NameLen == Name->getKeyLength() &&
204 !memcmp(Name->getKeyData(), NameStr, NameLen))
209 // NOTE: Could optimize for the case the name is shrinking to not deallocate
212 // Create the new name.
213 Name = ValueName::Create(NameStr, NameStr+NameLen);
214 Name->setValue(this);
218 // NOTE: Could optimize for the case the name is shrinking to not deallocate
221 // Name isn't changing?
222 if (NameLen == Name->getKeyLength() &&
223 !memcmp(Name->getKeyData(), NameStr, NameLen))
227 ST->removeValueName(Name);
235 // Name is changing to something new.
236 Name = ST->createValueName(NameStr, NameLen, this);
240 /// takeName - transfer the name from V to this value, setting V's name to
241 /// empty. It is an error to call V->takeName(V).
242 void Value::takeName(Value *V) {
243 ValueSymbolTable *ST = 0;
244 // If this value has a name, drop it.
246 // Get the symtab this is in.
247 if (getSymTab(this, ST)) {
248 // We can't set a name on this value, but we need to clear V's name if
250 if (V->hasName()) V->setName(0, 0);
251 return; // Cannot set a name on this value (e.g. constant).
256 ST->removeValueName(Name);
261 // Now we know that this has no name.
263 // If V has no name either, we're done.
264 if (!V->hasName()) return;
266 // Get this's symtab if we didn't before.
268 if (getSymTab(this, ST)) {
271 return; // Cannot set a name on this value (e.g. constant).
275 // Get V's ST, this should always succed, because V has a name.
276 ValueSymbolTable *VST;
277 bool Failure = getSymTab(V, VST);
278 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
280 // If these values are both in the same symtab, we can do this very fast.
281 // This works even if both values have no symtab yet.
286 Name->setValue(this);
290 // Otherwise, things are slightly more complex. Remove V's name from VST and
291 // then reinsert it into ST.
294 VST->removeValueName(V->Name);
297 Name->setValue(this);
300 ST->reinsertValue(this);
304 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
305 // except that it doesn't have all of the asserts. The asserts fail because we
306 // are half-way done resolving types, which causes some types to exist as two
307 // different Type*'s at the same time. This is a sledgehammer to work around
310 void Value::uncheckedReplaceAllUsesWith(Value *New) {
311 // Notify all ValueHandles (if present) that this value is going away.
313 ValueHandleBase::ValueIsRAUWd(this, New);
315 while (!use_empty()) {
317 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
318 // constant because they are uniqued.
319 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
320 if (!isa<GlobalValue>(C)) {
321 C->replaceUsesOfWithOnConstant(this, New, &U);
330 void Value::replaceAllUsesWith(Value *New) {
331 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
332 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
333 assert(New->getType() == getType() &&
334 "replaceAllUses of value with new value of different type!");
336 uncheckedReplaceAllUsesWith(New);
339 Value *Value::stripPointerCasts() {
340 if (!isa<PointerType>(getType()))
344 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
345 if (CE->getOpcode() == Instruction::GetElementPtr) {
346 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
347 if (!CE->getOperand(i)->isNullValue())
349 V = CE->getOperand(0);
350 } else if (CE->getOpcode() == Instruction::BitCast) {
351 V = CE->getOperand(0);
355 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
356 if (!GEP->hasAllZeroIndices())
358 V = GEP->getOperand(0);
359 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(V)) {
360 V = CI->getOperand(0);
364 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
368 Value *Value::getUnderlyingObject() {
369 if (!isa<PointerType>(getType()))
372 unsigned MaxLookup = 6;
374 if (Instruction *I = dyn_cast<Instruction>(V)) {
375 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
377 V = I->getOperand(0);
378 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
379 if (CE->getOpcode() != Instruction::BitCast &&
380 CE->getOpcode() != Instruction::GetElementPtr)
382 V = CE->getOperand(0);
386 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
387 } while (--MaxLookup);
391 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
392 /// return the value in the PHI node corresponding to PredBB. If not, return
393 /// ourself. This is useful if you want to know the value something has in a
394 /// predecessor block.
395 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
396 const BasicBlock *PredBB) {
397 PHINode *PN = dyn_cast<PHINode>(this);
398 if (PN && PN->getParent() == CurBB)
399 return PN->getIncomingValueForBlock(PredBB);
403 //===----------------------------------------------------------------------===//
404 // ValueHandleBase Class
405 //===----------------------------------------------------------------------===//
407 /// ValueHandles - This map keeps track of all of the value handles that are
408 /// watching a Value*. The Value::HasValueHandle bit is used to know whether or
409 /// not a value has an entry in this map.
410 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
411 static ManagedStatic<ValueHandlesTy> ValueHandles;
412 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
414 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
415 /// List is known to point into the existing use list.
416 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
417 assert(List && "Handle list is null?");
419 // Splice ourselves into the list.
424 Next->setPrevPtr(&Next);
425 assert(VP == Next->VP && "Added to wrong list?");
429 /// AddToUseList - Add this ValueHandle to the use list for VP.
430 void ValueHandleBase::AddToUseList() {
431 assert(VP && "Null pointer doesn't have a use list!");
432 if (VP->HasValueHandle) {
433 // If this value already has a ValueHandle, then it must be in the
434 // ValueHandles map already.
435 sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
436 ValueHandleBase *&Entry = (*ValueHandles)[VP];
437 assert(Entry != 0 && "Value doesn't have any handles?");
438 AddToExistingUseList(&Entry);
442 // Ok, it doesn't have any handles yet, so we must insert it into the
443 // DenseMap. However, doing this insertion could cause the DenseMap to
444 // reallocate itself, which would invalidate all of the PrevP pointers that
445 // point into the old table. Handle this by checking for reallocation and
446 // updating the stale pointers only if needed.
447 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
448 ValueHandlesTy &Handles = *ValueHandles;
449 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
451 ValueHandleBase *&Entry = Handles[VP];
452 assert(Entry == 0 && "Value really did already have handles?");
453 AddToExistingUseList(&Entry);
454 VP->HasValueHandle = true;
456 // If reallocation didn't happen or if this was the first insertion, don't
458 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
459 Handles.size() == 1) {
463 // Okay, reallocation did happen. Fix the Prev Pointers.
464 for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
466 assert(I->second && I->first == I->second->VP && "List invariant broken!");
467 I->second->setPrevPtr(&I->second);
471 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
472 void ValueHandleBase::RemoveFromUseList() {
473 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
475 // Unlink this from its use list.
476 ValueHandleBase **PrevPtr = getPrevPtr();
477 assert(*PrevPtr == this && "List invariant broken");
481 assert(Next->getPrevPtr() == &Next && "List invariant broken");
482 Next->setPrevPtr(PrevPtr);
486 // If the Next pointer was null, then it is possible that this was the last
487 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
489 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
490 ValueHandlesTy &Handles = *ValueHandles;
491 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
493 VP->HasValueHandle = false;
498 void ValueHandleBase::ValueIsDeleted(Value *V) {
499 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
501 // Get the linked list base, which is guaranteed to exist since the
502 // HasValueHandle flag is set.
503 ValueHandlesLock->reader_acquire();
504 ValueHandleBase *Entry = (*ValueHandles)[V];
505 ValueHandlesLock->reader_release();
506 assert(Entry && "Value bit set but no entries exist");
509 // Advance pointer to avoid invalidation.
510 ValueHandleBase *ThisNode = Entry;
513 switch (ThisNode->getKind()) {
515 #ifndef NDEBUG // Only in -g mode...
516 cerr << "While deleting: " << *V->getType() << " %" << V->getNameStr()
519 llvm_unreachable("An asserting value handle still pointed to this"
522 // Weak just goes to null, which will unlink it from the list.
523 ThisNode->operator=(0);
526 // Forward to the subclass's implementation.
527 static_cast<CallbackVH*>(ThisNode)->deleted();
532 // All callbacks and weak references should be dropped by now.
533 assert(!V->HasValueHandle && "All references to V were not removed?");
537 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
538 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
539 assert(Old != New && "Changing value into itself!");
541 // Get the linked list base, which is guaranteed to exist since the
542 // HasValueHandle flag is set.
543 ValueHandlesLock->reader_acquire();
544 ValueHandleBase *Entry = (*ValueHandles)[Old];
545 ValueHandlesLock->reader_release();
546 assert(Entry && "Value bit set but no entries exist");
549 // Advance pointer to avoid invalidation.
550 ValueHandleBase *ThisNode = Entry;
553 switch (ThisNode->getKind()) {
555 // Asserting handle does not follow RAUW implicitly.
558 // Weak goes to the new value, which will unlink it from Old's list.
559 ThisNode->operator=(New);
562 // Forward to the subclass's implementation.
563 static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
569 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
571 CallbackVH::~CallbackVH() {}
574 //===----------------------------------------------------------------------===//
576 //===----------------------------------------------------------------------===//
578 // replaceUsesOfWith - Replaces all references to the "From" definition with
579 // references to the "To" definition.
581 void User::replaceUsesOfWith(Value *From, Value *To) {
582 if (From == To) return; // Duh what?
584 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
585 "Cannot call User::replaceUsesofWith on a constant!");
587 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
588 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
589 // The side effects of this setOperand call include linking to
590 // "To", adding "this" to the uses list of To, and
591 // most importantly, removing "this" from the use list of "From".
592 setOperand(i, To); // Fix it now...