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/Value.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/Constant.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/InstrTypes.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/LeakDetector.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/ValueHandle.h"
31 #include "llvm/ValueSymbolTable.h"
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 static inline Type *checkType(Type *Ty) {
40 assert(Ty && "Value defined with a null type: Error!");
41 return const_cast<Type*>(Ty);
44 Value::Value(Type *ty, unsigned scid)
45 : SubclassID(scid), HasValueHandle(0),
46 SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
48 // FIXME: Why isn't this in the subclass gunk??
49 if (isa<CallInst>(this) || isa<InvokeInst>(this))
50 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
51 "invalid CallInst type!");
52 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
53 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
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 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
71 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
72 dbgs() << "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
80 if (Name && SubclassID != MDStringVal)
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 const_use_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 const_use_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 // Start by scanning over the instructions looking for a use before we start
113 // the expensive use iteration.
114 unsigned MaxBlockSize = 3;
115 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
116 if (std::find(I->op_begin(), I->op_end(), this) != I->op_end())
118 if (MaxBlockSize-- == 0) // If the block is larger fall back to use_iterator
122 if (MaxBlockSize != 0) // We scanned the entire block and found no use.
125 for (const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
126 const Instruction *User = dyn_cast<Instruction>(*I);
127 if (User && User->getParent() == BB)
134 /// getNumUses - This method computes the number of uses of this Value. This
135 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
137 unsigned Value::getNumUses() const {
138 return (unsigned)std::distance(use_begin(), use_end());
141 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
143 if (Instruction *I = dyn_cast<Instruction>(V)) {
144 if (BasicBlock *P = I->getParent())
145 if (Function *PP = P->getParent())
146 ST = &PP->getValueSymbolTable();
147 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
148 if (Function *P = BB->getParent())
149 ST = &P->getValueSymbolTable();
150 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
151 if (Module *P = GV->getParent())
152 ST = &P->getValueSymbolTable();
153 } else if (Argument *A = dyn_cast<Argument>(V)) {
154 if (Function *P = A->getParent())
155 ST = &P->getValueSymbolTable();
156 } else if (isa<MDString>(V))
159 assert(isa<Constant>(V) && "Unknown value type!");
160 return true; // no name is setable for this.
165 StringRef Value::getName() const {
166 // Make sure the empty string is still a C string. For historical reasons,
167 // some clients want to call .data() on the result and expect it to be null
169 if (!Name) return StringRef("", 0);
170 return Name->getKey();
173 void Value::setName(const Twine &NewName) {
174 assert(SubclassID != MDStringVal &&
175 "Cannot set the name of MDString with this method!");
177 // Fast path for common IRBuilder case of setName("") when there is no name.
178 if (NewName.isTriviallyEmpty() && !hasName())
181 SmallString<256> NameData;
182 StringRef NameRef = NewName.toStringRef(NameData);
184 // Name isn't changing?
185 if (getName() == NameRef)
188 assert(!getType()->isVoidTy() && "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.
196 if (NameRef.empty()) {
197 // Free the name for this value.
206 // NOTE: Could optimize for the case the name is shrinking to not deallocate
209 // Create the new name.
210 Name = ValueName::Create(NameRef.begin(), NameRef.end());
211 Name->setValue(this);
215 // NOTE: Could optimize for the case the name is shrinking to not deallocate
219 ST->removeValueName(Name);
227 // Name is changing to something new.
228 Name = ST->createValueName(NameRef, this);
232 /// takeName - transfer the name from V to this value, setting V's name to
233 /// empty. It is an error to call V->takeName(V).
234 void Value::takeName(Value *V) {
235 assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
237 ValueSymbolTable *ST = 0;
238 // If this value has a name, drop it.
240 // Get the symtab this is in.
241 if (getSymTab(this, ST)) {
242 // We can't set a name on this value, but we need to clear V's name if
244 if (V->hasName()) V->setName("");
245 return; // Cannot set a name on this value (e.g. constant).
250 ST->removeValueName(Name);
255 // Now we know that this has no name.
257 // If V has no name either, we're done.
258 if (!V->hasName()) return;
260 // Get this's symtab if we didn't before.
262 if (getSymTab(this, ST)) {
265 return; // Cannot set a name on this value (e.g. constant).
269 // Get V's ST, this should always succed, because V has a name.
270 ValueSymbolTable *VST;
271 bool Failure = getSymTab(V, VST);
272 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
274 // If these values are both in the same symtab, we can do this very fast.
275 // This works even if both values have no symtab yet.
280 Name->setValue(this);
284 // Otherwise, things are slightly more complex. Remove V's name from VST and
285 // then reinsert it into ST.
288 VST->removeValueName(V->Name);
291 Name->setValue(this);
294 ST->reinsertValue(this);
298 void Value::replaceAllUsesWith(Value *New) {
299 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
300 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
301 assert(New->getType() == getType() &&
302 "replaceAllUses of value with new value of different type!");
304 // Notify all ValueHandles (if present) that this value is going away.
306 ValueHandleBase::ValueIsRAUWd(this, New);
308 while (!use_empty()) {
310 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
311 // constant because they are uniqued.
312 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
313 if (!isa<GlobalValue>(C)) {
314 C->replaceUsesOfWithOnConstant(this, New, &U);
322 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
323 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
327 // Various metrics for how much to strip off of pointers.
328 enum PointerStripKind {
330 PSK_InBoundsConstantIndices,
334 template <PointerStripKind StripKind>
335 static Value *stripPointerCastsAndOffsets(Value *V) {
336 if (!V->getType()->isPointerTy())
339 // Even though we don't look through PHI nodes, we could be called on an
340 // instruction in an unreachable block, which may be on a cycle.
341 SmallPtrSet<Value *, 4> Visited;
345 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
347 case PSK_ZeroIndices:
348 if (!GEP->hasAllZeroIndices())
351 case PSK_InBoundsConstantIndices:
352 if (!GEP->hasAllConstantIndices())
356 if (!GEP->isInBounds())
360 V = GEP->getPointerOperand();
361 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
362 V = cast<Operator>(V)->getOperand(0);
363 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
364 if (GA->mayBeOverridden())
366 V = GA->getAliasee();
370 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
371 } while (Visited.insert(V));
377 Value *Value::stripPointerCasts() {
378 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
381 Value *Value::stripInBoundsConstantOffsets() {
382 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
385 Value *Value::stripInBoundsOffsets() {
386 return stripPointerCastsAndOffsets<PSK_InBounds>(this);
389 /// isDereferenceablePointer - Test if this value is always a pointer to
390 /// allocated and suitably aligned memory for a simple load or store.
391 static bool isDereferenceablePointer(const Value *V,
392 SmallPtrSet<const Value *, 32> &Visited) {
393 // Note that it is not safe to speculate into a malloc'd region because
394 // malloc may return null.
395 // It's also not always safe to follow a bitcast, for example:
396 // bitcast i8* (alloca i8) to i32*
397 // would result in a 4-byte load from a 1-byte alloca. Some cases could
398 // be handled using DataLayout to check sizes and alignments though.
400 // These are obviously ok.
401 if (isa<AllocaInst>(V)) return true;
403 // Global variables which can't collapse to null are ok.
404 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
405 return !GV->hasExternalWeakLinkage();
407 // byval arguments are ok.
408 if (const Argument *A = dyn_cast<Argument>(V))
409 return A->hasByValAttr();
411 // For GEPs, determine if the indexing lands within the allocated object.
412 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
413 // Conservatively require that the base pointer be fully dereferenceable.
414 if (!Visited.insert(GEP->getOperand(0)))
416 if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
418 // Check the indices.
419 gep_type_iterator GTI = gep_type_begin(GEP);
420 for (User::const_op_iterator I = GEP->op_begin()+1,
421 E = GEP->op_end(); I != E; ++I) {
424 // Struct indices can't be out of bounds.
425 if (isa<StructType>(Ty))
427 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
430 // Zero is always ok.
433 // Check to see that it's within the bounds of an array.
434 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
437 if (CI->getValue().getActiveBits() > 64)
439 if (CI->getZExtValue() >= ATy->getNumElements())
442 // Indices check out; this is dereferenceable.
446 // If we don't know, assume the worst.
450 /// isDereferenceablePointer - Test if this value is always a pointer to
451 /// allocated and suitably aligned memory for a simple load or store.
452 bool Value::isDereferenceablePointer() const {
453 SmallPtrSet<const Value *, 32> Visited;
454 return ::isDereferenceablePointer(this, Visited);
457 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
458 /// return the value in the PHI node corresponding to PredBB. If not, return
459 /// ourself. This is useful if you want to know the value something has in a
460 /// predecessor block.
461 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
462 const BasicBlock *PredBB) {
463 PHINode *PN = dyn_cast<PHINode>(this);
464 if (PN && PN->getParent() == CurBB)
465 return PN->getIncomingValueForBlock(PredBB);
469 LLVMContext &Value::getContext() const { return VTy->getContext(); }
471 //===----------------------------------------------------------------------===//
472 // ValueHandleBase Class
473 //===----------------------------------------------------------------------===//
475 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
476 /// List is known to point into the existing use list.
477 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
478 assert(List && "Handle list is null?");
480 // Splice ourselves into the list.
485 Next->setPrevPtr(&Next);
486 assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
490 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
491 assert(List && "Must insert after existing node");
494 setPrevPtr(&List->Next);
497 Next->setPrevPtr(&Next);
500 /// AddToUseList - Add this ValueHandle to the use list for VP.
501 void ValueHandleBase::AddToUseList() {
502 assert(VP.getPointer() && "Null pointer doesn't have a use list!");
504 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
506 if (VP.getPointer()->HasValueHandle) {
507 // If this value already has a ValueHandle, then it must be in the
508 // ValueHandles map already.
509 ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
510 assert(Entry != 0 && "Value doesn't have any handles?");
511 AddToExistingUseList(&Entry);
515 // Ok, it doesn't have any handles yet, so we must insert it into the
516 // DenseMap. However, doing this insertion could cause the DenseMap to
517 // reallocate itself, which would invalidate all of the PrevP pointers that
518 // point into the old table. Handle this by checking for reallocation and
519 // updating the stale pointers only if needed.
520 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
521 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
523 ValueHandleBase *&Entry = Handles[VP.getPointer()];
524 assert(Entry == 0 && "Value really did already have handles?");
525 AddToExistingUseList(&Entry);
526 VP.getPointer()->HasValueHandle = true;
528 // If reallocation didn't happen or if this was the first insertion, don't
530 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
531 Handles.size() == 1) {
535 // Okay, reallocation did happen. Fix the Prev Pointers.
536 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
537 E = Handles.end(); I != E; ++I) {
538 assert(I->second && I->first == I->second->VP.getPointer() &&
539 "List invariant broken!");
540 I->second->setPrevPtr(&I->second);
544 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
545 void ValueHandleBase::RemoveFromUseList() {
546 assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
547 "Pointer doesn't have a use list!");
549 // Unlink this from its use list.
550 ValueHandleBase **PrevPtr = getPrevPtr();
551 assert(*PrevPtr == this && "List invariant broken");
555 assert(Next->getPrevPtr() == &Next && "List invariant broken");
556 Next->setPrevPtr(PrevPtr);
560 // If the Next pointer was null, then it is possible that this was the last
561 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
563 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
564 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
565 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
566 Handles.erase(VP.getPointer());
567 VP.getPointer()->HasValueHandle = false;
572 void ValueHandleBase::ValueIsDeleted(Value *V) {
573 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
575 // Get the linked list base, which is guaranteed to exist since the
576 // HasValueHandle flag is set.
577 LLVMContextImpl *pImpl = V->getContext().pImpl;
578 ValueHandleBase *Entry = pImpl->ValueHandles[V];
579 assert(Entry && "Value bit set but no entries exist");
581 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
582 // and remove themselves from the list without breaking our iteration. This
583 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
584 // Note that we deliberately do not the support the case when dropping a value
585 // handle results in a new value handle being permanently added to the list
586 // (as might occur in theory for CallbackVH's): the new value handle will not
587 // be processed and the checking code will mete out righteous punishment if
588 // the handle is still present once we have finished processing all the other
589 // value handles (it is fine to momentarily add then remove a value handle).
590 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
591 Iterator.RemoveFromUseList();
592 Iterator.AddToExistingUseListAfter(Entry);
593 assert(Entry->Next == &Iterator && "Loop invariant broken.");
595 switch (Entry->getKind()) {
599 // Mark that this value has been deleted by setting it to an invalid Value
601 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
604 // Weak just goes to null, which will unlink it from the list.
608 // Forward to the subclass's implementation.
609 static_cast<CallbackVH*>(Entry)->deleted();
614 // All callbacks, weak references, and assertingVHs should be dropped by now.
615 if (V->HasValueHandle) {
616 #ifndef NDEBUG // Only in +Asserts mode...
617 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
619 if (pImpl->ValueHandles[V]->getKind() == Assert)
620 llvm_unreachable("An asserting value handle still pointed to this"
624 llvm_unreachable("All references to V were not removed?");
629 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
630 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
631 assert(Old != New && "Changing value into itself!");
633 // Get the linked list base, which is guaranteed to exist since the
634 // HasValueHandle flag is set.
635 LLVMContextImpl *pImpl = Old->getContext().pImpl;
636 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
638 assert(Entry && "Value bit set but no entries exist");
640 // We use a local ValueHandleBase as an iterator so that
641 // ValueHandles can add and remove themselves from the list without
642 // breaking our iteration. This is not really an AssertingVH; we
643 // just have to give ValueHandleBase some kind.
644 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
645 Iterator.RemoveFromUseList();
646 Iterator.AddToExistingUseListAfter(Entry);
647 assert(Entry->Next == &Iterator && "Loop invariant broken.");
649 switch (Entry->getKind()) {
651 // Asserting handle does not follow RAUW implicitly.
654 // Tracking goes to new value like a WeakVH. Note that this may make it
655 // something incompatible with its templated type. We don't want to have a
656 // virtual (or inline) interface to handle this though, so instead we make
657 // the TrackingVH accessors guarantee that a client never sees this value.
661 // Weak goes to the new value, which will unlink it from Old's list.
662 Entry->operator=(New);
665 // Forward to the subclass's implementation.
666 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
672 // If any new tracking or weak value handles were added while processing the
673 // list, then complain about it now.
674 if (Old->HasValueHandle)
675 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
676 switch (Entry->getKind()) {
679 dbgs() << "After RAUW from " << *Old->getType() << " %"
680 << Old->getName() << " to " << *New->getType() << " %"
681 << New->getName() << "\n";
682 llvm_unreachable("A tracking or weak value handle still pointed to the"
690 // Default implementation for CallbackVH.
691 void CallbackVH::allUsesReplacedWith(Value *) {}
693 void CallbackVH::deleted() {