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/MDNode.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/LeakDetector.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 static inline const Type *checkType(const Type *Ty) {
41 assert(Ty && "Value defined with a null type: Error!");
45 Value::Value(const Type *ty, unsigned scid)
46 : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0),
47 SubclassData(0), VTy(checkType(ty)),
49 if (isa<CallInst>(this) || isa<InvokeInst>(this))
50 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
51 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
52 "invalid CallInst type!");
53 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
54 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
55 isa<OpaqueType>(ty)) &&
56 "Cannot create non-first-class values except for constants!");
60 // Notify all ValueHandles (if present) that this value is going away.
62 ValueHandleBase::ValueIsDeleted(this);
64 #ifndef NDEBUG // Only in -g mode...
65 // Check to make sure that there are no uses of this value that are still
66 // around when the value is destroyed. If there are, then we have a dangling
67 // reference and something is wrong. This code is here to print out what is
68 // still being referenced. The value in question should be printed as
72 errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
73 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
74 errs() << "Use still stuck around after Def is destroyed:"
78 assert(use_empty() && "Uses remain when a value is destroyed!");
80 // If this value is named, destroy the name. This should not be in a symtab
85 // There should be no uses of this object anymore, remove it.
86 LeakDetector::removeGarbageObject(this);
89 /// hasNUses - Return true if this Value has exactly N users.
91 bool Value::hasNUses(unsigned N) const {
92 use_const_iterator UI = use_begin(), E = use_end();
95 if (UI == E) return false; // Too few.
99 /// hasNUsesOrMore - Return true if this value has N users or more. This is
100 /// logically equivalent to getNumUses() >= N.
102 bool Value::hasNUsesOrMore(unsigned N) const {
103 use_const_iterator UI = use_begin(), E = use_end();
106 if (UI == E) return false; // Too few.
111 /// isUsedInBasicBlock - Return true if this value is used in the specified
113 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
114 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
115 const Instruction *User = dyn_cast<Instruction>(*I);
116 if (User && User->getParent() == BB)
123 /// getNumUses - This method computes the number of uses of this Value. This
124 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
126 unsigned Value::getNumUses() const {
127 return (unsigned)std::distance(use_begin(), use_end());
130 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
132 if (Instruction *I = dyn_cast<Instruction>(V)) {
133 if (BasicBlock *P = I->getParent())
134 if (Function *PP = P->getParent())
135 ST = &PP->getValueSymbolTable();
136 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
137 if (Function *P = BB->getParent())
138 ST = &P->getValueSymbolTable();
139 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
140 if (Module *P = GV->getParent())
141 ST = &P->getValueSymbolTable();
142 } else if (Argument *A = dyn_cast<Argument>(V)) {
143 if (Function *P = A->getParent())
144 ST = &P->getValueSymbolTable();
145 } else if (isa<MDString>(V))
148 assert(isa<Constant>(V) && "Unknown value type!");
149 return true; // no name is setable for this.
154 /// getNameStart - Return a pointer to a null terminated string for this name.
155 /// Note that names can have null characters within the string as well as at
156 /// their end. This always returns a non-null pointer.
157 const char *Value::getNameStart() const {
158 if (Name == 0) return "";
159 return Name->getKeyData();
162 /// getNameLen - Return the length of the string, correctly handling nul
163 /// characters embedded into them.
164 unsigned Value::getNameLen() const {
165 return Name ? Name->getKeyLength() : 0;
169 std::string Value::getNameStr() const {
170 return getName().str();
173 void Value::setName(const Twine &NewName) {
174 SmallString<32> NameData;
175 NewName.toVector(NameData);
177 const char *NameStr = NameData.data();
178 unsigned NameLen = NameData.size();
180 // Name isn't changing?
181 if (getName() == StringRef(NameStr, NameLen))
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.
202 // NOTE: Could optimize for the case the name is shrinking to not deallocate
205 // Create the new name.
206 Name = ValueName::Create(NameStr, NameStr+NameLen);
207 Name->setValue(this);
211 // NOTE: Could optimize for the case the name is shrinking to not deallocate
215 ST->removeValueName(Name);
223 // Name is changing to something new.
224 Name = ST->createValueName(StringRef(NameStr, NameLen), this);
228 /// takeName - transfer the name from V to this value, setting V's name to
229 /// empty. It is an error to call V->takeName(V).
230 void Value::takeName(Value *V) {
231 ValueSymbolTable *ST = 0;
232 // If this value has a name, drop it.
234 // Get the symtab this is in.
235 if (getSymTab(this, ST)) {
236 // We can't set a name on this value, but we need to clear V's name if
238 if (V->hasName()) V->setName("");
239 return; // Cannot set a name on this value (e.g. constant).
244 ST->removeValueName(Name);
249 // Now we know that this has no name.
251 // If V has no name either, we're done.
252 if (!V->hasName()) return;
254 // Get this's symtab if we didn't before.
256 if (getSymTab(this, ST)) {
259 return; // Cannot set a name on this value (e.g. constant).
263 // Get V's ST, this should always succed, because V has a name.
264 ValueSymbolTable *VST;
265 bool Failure = getSymTab(V, VST);
266 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
268 // If these values are both in the same symtab, we can do this very fast.
269 // This works even if both values have no symtab yet.
274 Name->setValue(this);
278 // Otherwise, things are slightly more complex. Remove V's name from VST and
279 // then reinsert it into ST.
282 VST->removeValueName(V->Name);
285 Name->setValue(this);
288 ST->reinsertValue(this);
292 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
293 // except that it doesn't have all of the asserts. The asserts fail because we
294 // are half-way done resolving types, which causes some types to exist as two
295 // different Type*'s at the same time. This is a sledgehammer to work around
298 void Value::uncheckedReplaceAllUsesWith(Value *New) {
299 // Notify all ValueHandles (if present) that this value is going away.
301 ValueHandleBase::ValueIsRAUWd(this, New);
303 while (!use_empty()) {
305 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
306 // constant because they are uniqued.
307 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
308 if (!isa<GlobalValue>(C)) {
309 C->replaceUsesOfWithOnConstant(this, New, &U);
318 void Value::replaceAllUsesWith(Value *New) {
319 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
320 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
321 assert(New->getType() == getType() &&
322 "replaceAllUses of value with new value of different type!");
324 uncheckedReplaceAllUsesWith(New);
327 Value *Value::stripPointerCasts() {
328 if (!isa<PointerType>(getType()))
332 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
333 if (!GEP->hasAllZeroIndices())
335 V = GEP->getPointerOperand();
336 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
337 V = cast<Operator>(V)->getOperand(0);
341 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
345 Value *Value::getUnderlyingObject() {
346 if (!isa<PointerType>(getType()))
349 unsigned MaxLookup = 6;
351 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
352 V = GEP->getPointerOperand();
353 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
354 V = cast<Operator>(V)->getOperand(0);
358 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
359 } while (--MaxLookup);
363 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
364 /// return the value in the PHI node corresponding to PredBB. If not, return
365 /// ourself. This is useful if you want to know the value something has in a
366 /// predecessor block.
367 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
368 const BasicBlock *PredBB) {
369 PHINode *PN = dyn_cast<PHINode>(this);
370 if (PN && PN->getParent() == CurBB)
371 return PN->getIncomingValueForBlock(PredBB);
375 LLVMContext &Value::getContext() const { return VTy->getContext(); }
377 //===----------------------------------------------------------------------===//
378 // ValueHandleBase Class
379 //===----------------------------------------------------------------------===//
381 /// ValueHandles - This map keeps track of all of the value handles that are
382 /// watching a Value*. The Value::HasValueHandle bit is used to know whether or
383 /// not a value has an entry in this map.
384 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
385 static ManagedStatic<ValueHandlesTy> ValueHandles;
386 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
388 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
389 /// List is known to point into the existing use list.
390 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
391 assert(List && "Handle list is null?");
393 // Splice ourselves into the list.
398 Next->setPrevPtr(&Next);
399 assert(VP == Next->VP && "Added to wrong list?");
403 /// AddToUseList - Add this ValueHandle to the use list for VP.
404 void ValueHandleBase::AddToUseList() {
405 assert(VP && "Null pointer doesn't have a use list!");
406 if (VP->HasValueHandle) {
407 // If this value already has a ValueHandle, then it must be in the
408 // ValueHandles map already.
409 sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
410 ValueHandleBase *&Entry = (*ValueHandles)[VP];
411 assert(Entry != 0 && "Value doesn't have any handles?");
412 AddToExistingUseList(&Entry);
416 // Ok, it doesn't have any handles yet, so we must insert it into the
417 // DenseMap. However, doing this insertion could cause the DenseMap to
418 // reallocate itself, which would invalidate all of the PrevP pointers that
419 // point into the old table. Handle this by checking for reallocation and
420 // updating the stale pointers only if needed.
421 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
422 ValueHandlesTy &Handles = *ValueHandles;
423 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
425 ValueHandleBase *&Entry = Handles[VP];
426 assert(Entry == 0 && "Value really did already have handles?");
427 AddToExistingUseList(&Entry);
428 VP->HasValueHandle = true;
430 // If reallocation didn't happen or if this was the first insertion, don't
432 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
433 Handles.size() == 1) {
437 // Okay, reallocation did happen. Fix the Prev Pointers.
438 for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
440 assert(I->second && I->first == I->second->VP && "List invariant broken!");
441 I->second->setPrevPtr(&I->second);
445 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
446 void ValueHandleBase::RemoveFromUseList() {
447 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
449 // Unlink this from its use list.
450 ValueHandleBase **PrevPtr = getPrevPtr();
451 assert(*PrevPtr == this && "List invariant broken");
455 assert(Next->getPrevPtr() == &Next && "List invariant broken");
456 Next->setPrevPtr(PrevPtr);
460 // If the Next pointer was null, then it is possible that this was the last
461 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
463 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
464 ValueHandlesTy &Handles = *ValueHandles;
465 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
467 VP->HasValueHandle = false;
472 void ValueHandleBase::ValueIsDeleted(Value *V) {
473 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
475 // Get the linked list base, which is guaranteed to exist since the
476 // HasValueHandle flag is set.
477 ValueHandlesLock->reader_acquire();
478 ValueHandleBase *Entry = (*ValueHandles)[V];
479 ValueHandlesLock->reader_release();
480 assert(Entry && "Value bit set but no entries exist");
483 // Advance pointer to avoid invalidation.
484 ValueHandleBase *ThisNode = Entry;
487 switch (ThisNode->getKind()) {
489 #ifndef NDEBUG // Only in -g mode...
490 errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
493 llvm_unreachable("An asserting value handle still pointed to this"
496 // Weak just goes to null, which will unlink it from the list.
497 ThisNode->operator=(0);
500 // Forward to the subclass's implementation.
501 static_cast<CallbackVH*>(ThisNode)->deleted();
506 // All callbacks and weak references should be dropped by now.
507 assert(!V->HasValueHandle && "All references to V were not removed?");
511 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
512 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
513 assert(Old != New && "Changing value into itself!");
515 // Get the linked list base, which is guaranteed to exist since the
516 // HasValueHandle flag is set.
517 ValueHandlesLock->reader_acquire();
518 ValueHandleBase *Entry = (*ValueHandles)[Old];
519 ValueHandlesLock->reader_release();
520 assert(Entry && "Value bit set but no entries exist");
523 // Advance pointer to avoid invalidation.
524 ValueHandleBase *ThisNode = Entry;
527 switch (ThisNode->getKind()) {
529 // Asserting handle does not follow RAUW implicitly.
532 // Weak goes to the new value, which will unlink it from Old's list.
533 ThisNode->operator=(New);
536 // Forward to the subclass's implementation.
537 static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
543 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
545 CallbackVH::~CallbackVH() {}
548 //===----------------------------------------------------------------------===//
550 //===----------------------------------------------------------------------===//
552 // replaceUsesOfWith - Replaces all references to the "From" definition with
553 // references to the "To" definition.
555 void User::replaceUsesOfWith(Value *From, Value *To) {
556 if (From == To) return; // Duh what?
558 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
559 "Cannot call User::replaceUsesofWith on a constant!");
561 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
562 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
563 // The side effects of this setOperand call include linking to
564 // "To", adding "this" to the uses list of To, and
565 // most importantly, removing "this" from the use list of "From".
566 setOperand(i, To); // Fix it now...