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/Threading.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/System/RWMutex.h"
27 #include "llvm/ADT/DenseMap.h"
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 static inline const Type *checkType(const Type *Ty) {
36 assert(Ty && "Value defined with a null type: Error!");
40 Value::Value(const Type *ty, unsigned scid)
41 : SubclassID(scid), HasValueHandle(0), SubclassData(0), VTy(checkType(ty)),
43 if (isa<CallInst>(this) || isa<InvokeInst>(this))
44 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
45 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
46 "invalid CallInst type!");
47 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
48 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
49 isa<OpaqueType>(ty)) &&
50 "Cannot create non-first-class values except for constants!");
54 // Notify all ValueHandles (if present) that this value is going away.
56 ValueHandleBase::ValueIsDeleted(this);
58 #ifndef NDEBUG // Only in -g mode...
59 // Check to make sure that there are no uses of this value that are still
60 // around when the value is destroyed. If there are, then we have a dangling
61 // reference and something is wrong. This code is here to print out what is
62 // still being referenced. The value in question should be printed as
66 cerr << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
67 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
68 cerr << "Use still stuck around after Def is destroyed:"
72 assert(use_empty() && "Uses remain when a value is destroyed!");
74 // If this value is named, destroy the name. This should not be in a symtab
79 // There should be no uses of this object anymore, remove it.
80 LeakDetector::removeGarbageObject(this);
83 /// hasNUses - Return true if this Value has exactly N users.
85 bool Value::hasNUses(unsigned N) const {
86 use_const_iterator UI = use_begin(), E = use_end();
89 if (UI == E) return false; // Too few.
93 /// hasNUsesOrMore - Return true if this value has N users or more. This is
94 /// logically equivalent to getNumUses() >= N.
96 bool Value::hasNUsesOrMore(unsigned N) const {
97 use_const_iterator UI = use_begin(), E = use_end();
100 if (UI == E) return false; // Too few.
105 /// isUsedInBasicBlock - Return true if this value is used in the specified
107 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
108 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
109 const Instruction *User = dyn_cast<Instruction>(*I);
110 if (User && User->getParent() == BB)
117 /// getNumUses - This method computes the number of uses of this Value. This
118 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
120 unsigned Value::getNumUses() const {
121 return (unsigned)std::distance(use_begin(), use_end());
124 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
126 if (Instruction *I = dyn_cast<Instruction>(V)) {
127 if (BasicBlock *P = I->getParent())
128 if (Function *PP = P->getParent())
129 ST = &PP->getValueSymbolTable();
130 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
131 if (Function *P = BB->getParent())
132 ST = &P->getValueSymbolTable();
133 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
134 if (Module *P = GV->getParent())
135 ST = &P->getValueSymbolTable();
136 } else if (Argument *A = dyn_cast<Argument>(V)) {
137 if (Function *P = A->getParent())
138 ST = &P->getValueSymbolTable();
140 assert(isa<Constant>(V) && "Unknown value type!");
141 return true; // no name is setable for this.
146 /// getNameStart - Return a pointer to a null terminated string for this name.
147 /// Note that names can have null characters within the string as well as at
148 /// their end. This always returns a non-null pointer.
149 const char *Value::getNameStart() const {
150 if (Name == 0) return "";
151 return Name->getKeyData();
154 /// getNameLen - Return the length of the string, correctly handling nul
155 /// characters embedded into them.
156 unsigned Value::getNameLen() const {
157 return Name ? Name->getKeyLength() : 0;
160 /// isName - Return true if this value has the name specified by the provided
161 /// nul terminated string.
162 bool Value::isName(const char *N) const {
163 unsigned InLen = strlen(N);
164 return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
168 std::string Value::getNameStr() const {
169 if (Name == 0) return "";
170 return std::string(Name->getKeyData(),
171 Name->getKeyData()+Name->getKeyLength());
174 void Value::setName(const std::string &name) {
175 setName(&name[0], name.size());
178 void Value::setName(const char *Name) {
179 setName(Name, Name ? strlen(Name) : 0);
182 void Value::setName(const char *NameStr, unsigned NameLen) {
183 if (NameLen == 0 && !hasName()) return;
184 assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
186 // Get the symbol table to update for this object.
187 ValueSymbolTable *ST;
188 if (getSymTab(this, ST))
189 return; // Cannot set a name on this value (e.g. constant).
191 if (!ST) { // No symbol table to update? Just do the change.
193 // Free the name for this value.
200 // Name isn't changing?
201 if (NameLen == Name->getKeyLength() &&
202 !memcmp(Name->getKeyData(), NameStr, NameLen))
207 // NOTE: Could optimize for the case the name is shrinking to not deallocate
210 // Create the new name.
211 Name = ValueName::Create(NameStr, NameStr+NameLen);
212 Name->setValue(this);
216 // NOTE: Could optimize for the case the name is shrinking to not deallocate
219 // Name isn't changing?
220 if (NameLen == Name->getKeyLength() &&
221 !memcmp(Name->getKeyData(), NameStr, NameLen))
225 ST->removeValueName(Name);
233 // Name is changing to something new.
234 Name = ST->createValueName(NameStr, NameLen, this);
238 /// takeName - transfer the name from V to this value, setting V's name to
239 /// empty. It is an error to call V->takeName(V).
240 void Value::takeName(Value *V) {
241 ValueSymbolTable *ST = 0;
242 // If this value has a name, drop it.
244 // Get the symtab this is in.
245 if (getSymTab(this, ST)) {
246 // We can't set a name on this value, but we need to clear V's name if
248 if (V->hasName()) V->setName(0, 0);
249 return; // Cannot set a name on this value (e.g. constant).
254 ST->removeValueName(Name);
259 // Now we know that this has no name.
261 // If V has no name either, we're done.
262 if (!V->hasName()) return;
264 // Get this's symtab if we didn't before.
266 if (getSymTab(this, ST)) {
269 return; // Cannot set a name on this value (e.g. constant).
273 // Get V's ST, this should always succed, because V has a name.
274 ValueSymbolTable *VST;
275 bool Failure = getSymTab(V, VST);
276 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
278 // If these values are both in the same symtab, we can do this very fast.
279 // This works even if both values have no symtab yet.
284 Name->setValue(this);
288 // Otherwise, things are slightly more complex. Remove V's name from VST and
289 // then reinsert it into ST.
292 VST->removeValueName(V->Name);
295 Name->setValue(this);
298 ST->reinsertValue(this);
302 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
303 // except that it doesn't have all of the asserts. The asserts fail because we
304 // are half-way done resolving types, which causes some types to exist as two
305 // different Type*'s at the same time. This is a sledgehammer to work around
308 void Value::uncheckedReplaceAllUsesWith(Value *New) {
309 // Notify all ValueHandles (if present) that this value is going away.
311 ValueHandleBase::ValueIsRAUWd(this, New);
313 while (!use_empty()) {
315 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
316 // constant because they are uniqued.
317 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
318 if (!isa<GlobalValue>(C)) {
319 C->replaceUsesOfWithOnConstant(this, New, &U);
328 void Value::replaceAllUsesWith(Value *New) {
329 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
330 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
331 assert(New->getType() == getType() &&
332 "replaceAllUses of value with new value of different type!");
334 uncheckedReplaceAllUsesWith(New);
337 Value *Value::stripPointerCasts() {
338 if (!isa<PointerType>(getType()))
342 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
343 if (CE->getOpcode() == Instruction::GetElementPtr) {
344 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
345 if (!CE->getOperand(i)->isNullValue())
347 V = CE->getOperand(0);
348 } else if (CE->getOpcode() == Instruction::BitCast) {
349 V = CE->getOperand(0);
353 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
354 if (!GEP->hasAllZeroIndices())
356 V = GEP->getOperand(0);
357 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(V)) {
358 V = CI->getOperand(0);
362 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
366 Value *Value::getUnderlyingObject() {
367 if (!isa<PointerType>(getType()))
370 unsigned MaxLookup = 6;
372 if (Instruction *I = dyn_cast<Instruction>(V)) {
373 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
375 V = I->getOperand(0);
376 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
377 if (CE->getOpcode() != Instruction::BitCast &&
378 CE->getOpcode() != Instruction::GetElementPtr)
380 V = CE->getOperand(0);
384 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
385 } while (--MaxLookup);
389 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
390 /// return the value in the PHI node corresponding to PredBB. If not, return
391 /// ourself. This is useful if you want to know the value something has in a
392 /// predecessor block.
393 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
394 const BasicBlock *PredBB) {
395 PHINode *PN = dyn_cast<PHINode>(this);
396 if (PN && PN->getParent() == CurBB)
397 return PN->getIncomingValueForBlock(PredBB);
401 //===----------------------------------------------------------------------===//
402 // ValueHandleBase Class
403 //===----------------------------------------------------------------------===//
405 /// ValueHandles - This map keeps track of all of the value handles that are
406 /// watching a Value*. The Value::HasValueHandle bit is used to know whether or
407 /// not a value has an entry in this map.
408 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
409 static ManagedStatic<ValueHandlesTy> ValueHandles;
410 static ManagedStatic<sys::RWMutex> ValueHandlesLock;
412 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
413 /// List is known to point into the existing use list.
414 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
415 assert(List && "Handle list is null?");
417 // Splice ourselves into the list.
422 Next->setPrevPtr(&Next);
423 assert(VP == Next->VP && "Added to wrong list?");
427 /// AddToUseList - Add this ValueHandle to the use list for VP.
428 void ValueHandleBase::AddToUseList() {
429 assert(VP && "Null pointer doesn't have a use list!");
430 if (VP->HasValueHandle) {
431 // If this value already has a ValueHandle, then it must be in the
432 // ValueHandles map already.
433 if (llvm_is_multithreaded()) ValueHandlesLock->reader_acquire();
434 ValueHandleBase *&Entry = (*ValueHandles)[VP];
435 assert(Entry != 0 && "Value doesn't have any handles?");
436 AddToExistingUseList(&Entry);
437 if (llvm_is_multithreaded()) ValueHandlesLock->reader_release();
441 // Ok, it doesn't have any handles yet, so we must insert it into the
442 // DenseMap. However, doing this insertion could cause the DenseMap to
443 // reallocate itself, which would invalidate all of the PrevP pointers that
444 // point into the old table. Handle this by checking for reallocation and
445 // updating the stale pointers only if needed.
446 if (llvm_is_multithreaded()) ValueHandlesLock->writer_acquire();
447 ValueHandlesTy &Handles = *ValueHandles;
448 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
450 ValueHandleBase *&Entry = Handles[VP];
451 assert(Entry == 0 && "Value really did already have handles?");
452 AddToExistingUseList(&Entry);
453 VP->HasValueHandle = true;
455 // If reallocation didn't happen or if this was the first insertion, don't
457 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
458 Handles.size() == 1) {
459 if (llvm_is_multithreaded()) ValueHandlesLock->writer_release();
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);
470 if (llvm_is_multithreaded()) ValueHandlesLock->writer_release();
473 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
474 void ValueHandleBase::RemoveFromUseList() {
475 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
477 // Unlink this from its use list.
478 ValueHandleBase **PrevPtr = getPrevPtr();
479 assert(*PrevPtr == this && "List invariant broken");
483 assert(Next->getPrevPtr() == &Next && "List invariant broken");
484 Next->setPrevPtr(PrevPtr);
488 // If the Next pointer was null, then it is possible that this was the last
489 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
491 if (llvm_is_multithreaded()) ValueHandlesLock->writer_acquire();
492 ValueHandlesTy &Handles = *ValueHandles;
493 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
495 VP->HasValueHandle = false;
497 if (llvm_is_multithreaded()) ValueHandlesLock->writer_release();
501 void ValueHandleBase::ValueIsDeleted(Value *V) {
502 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
504 // Get the linked list base, which is guaranteed to exist since the
505 // HasValueHandle flag is set.
506 if (llvm_is_multithreaded()) ValueHandlesLock->reader_acquire();
507 ValueHandleBase *Entry = (*ValueHandles)[V];
508 if (llvm_is_multithreaded()) ValueHandlesLock->reader_release();
509 assert(Entry && "Value bit set but no entries exist");
512 // Advance pointer to avoid invalidation.
513 ValueHandleBase *ThisNode = Entry;
516 switch (ThisNode->getKind()) {
518 #ifndef NDEBUG // Only in -g mode...
519 cerr << "While deleting: " << *V->getType() << " %" << V->getNameStr()
522 cerr << "An asserting value handle still pointed to this value!\n";
525 // Weak just goes to null, which will unlink it from the list.
526 ThisNode->operator=(0);
529 // Forward to the subclass's implementation.
530 static_cast<CallbackVH*>(ThisNode)->deleted();
535 // All callbacks and weak references should be dropped by now.
536 assert(!V->HasValueHandle && "All references to V were not removed?");
540 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
541 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
542 assert(Old != New && "Changing value into itself!");
544 // Get the linked list base, which is guaranteed to exist since the
545 // HasValueHandle flag is set.
546 if (llvm_is_multithreaded()) ValueHandlesLock->reader_acquire();
547 ValueHandleBase *Entry = (*ValueHandles)[Old];
548 if (llvm_is_multithreaded()) ValueHandlesLock->reader_release();
549 assert(Entry && "Value bit set but no entries exist");
552 // Advance pointer to avoid invalidation.
553 ValueHandleBase *ThisNode = Entry;
556 switch (ThisNode->getKind()) {
558 // Asserting handle does not follow RAUW implicitly.
561 // Weak goes to the new value, which will unlink it from Old's list.
562 ThisNode->operator=(New);
565 // Forward to the subclass's implementation.
566 static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
572 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
574 CallbackVH::~CallbackVH() {}
577 //===----------------------------------------------------------------------===//
579 //===----------------------------------------------------------------------===//
581 // replaceUsesOfWith - Replaces all references to the "From" definition with
582 // references to the "To" definition.
584 void User::replaceUsesOfWith(Value *From, Value *To) {
585 if (From == To) return; // Duh what?
587 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
588 "Cannot call User::replaceUsesofWith on a constant!");
590 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
591 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
592 // The side effects of this setOperand call include linking to
593 // "To", adding "this" to the uses list of To, and
594 // most importantly, removing "this" from the use list of "From".
595 setOperand(i, To); // Fix it now...