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 "LLVMContextImpl.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InstrTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Operator.h"
21 #include "llvm/Module.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LeakDetector.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/ValueHandle.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), HasMetadata(0),
47 SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
49 if (isa<CallInst>(this) || isa<InvokeInst>(this))
50 assert((VTy->isFirstClassType() ||
51 VTy == Type::getVoidTy(ty->getContext()) ||
52 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
53 "invalid CallInst type!");
54 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
55 assert((VTy->isFirstClassType() ||
56 VTy == Type::getVoidTy(ty->getContext()) ||
57 isa<OpaqueType>(ty)) &&
58 "Cannot create non-first-class values except for constants!");
63 LLVMContext &Context = getContext();
64 Context.pImpl->TheMetadata.ValueIsDeleted(this);
67 // Notify all ValueHandles (if present) that this value is going away.
69 ValueHandleBase::ValueIsDeleted(this);
71 #ifndef NDEBUG // Only in -g mode...
72 // Check to make sure that there are no uses of this value that are still
73 // around when the value is destroyed. If there are, then we have a dangling
74 // reference and something is wrong. This code is here to print out what is
75 // still being referenced. The value in question should be printed as
79 errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
80 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
81 errs() << "Use still stuck around after Def is destroyed:"
85 assert(use_empty() && "Uses remain when a value is destroyed!");
87 // If this value is named, destroy the name. This should not be in a symtab
92 // There should be no uses of this object anymore, remove it.
93 LeakDetector::removeGarbageObject(this);
96 /// hasNUses - Return true if this Value has exactly N users.
98 bool Value::hasNUses(unsigned N) const {
99 use_const_iterator UI = use_begin(), E = use_end();
102 if (UI == E) return false; // Too few.
106 /// hasNUsesOrMore - Return true if this value has N users or more. This is
107 /// logically equivalent to getNumUses() >= N.
109 bool Value::hasNUsesOrMore(unsigned N) const {
110 use_const_iterator UI = use_begin(), E = use_end();
113 if (UI == E) return false; // Too few.
118 /// isUsedInBasicBlock - Return true if this value is used in the specified
120 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
121 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
122 const Instruction *User = dyn_cast<Instruction>(*I);
123 if (User && User->getParent() == BB)
130 /// getNumUses - This method computes the number of uses of this Value. This
131 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
133 unsigned Value::getNumUses() const {
134 return (unsigned)std::distance(use_begin(), use_end());
137 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
139 if (Instruction *I = dyn_cast<Instruction>(V)) {
140 if (BasicBlock *P = I->getParent())
141 if (Function *PP = P->getParent())
142 ST = &PP->getValueSymbolTable();
143 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
144 if (Function *P = BB->getParent())
145 ST = &P->getValueSymbolTable();
146 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
147 if (Module *P = GV->getParent())
148 ST = &P->getValueSymbolTable();
149 } else if (Argument *A = dyn_cast<Argument>(V)) {
150 if (Function *P = A->getParent())
151 ST = &P->getValueSymbolTable();
152 } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
153 if (Module *P = N->getParent()) {
154 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 std::string Value::getNameStr() const {
174 return getName().str();
177 void Value::setName(const Twine &NewName) {
178 // Fast path for common IRBuilder case of setName("") when there is no name.
179 if (NewName.isTriviallyEmpty() && !hasName())
182 SmallString<256> NameData;
183 NewName.toVector(NameData);
185 const char *NameStr = NameData.data();
186 unsigned NameLen = NameData.size();
188 // Name isn't changing?
189 if (getName() == StringRef(NameStr, NameLen))
192 assert(getType() != Type::getVoidTy(getContext()) &&
193 "Cannot assign a name to void values!");
195 // Get the symbol table to update for this object.
196 ValueSymbolTable *ST;
197 if (getSymTab(this, ST))
198 return; // Cannot set a name on this value (e.g. constant).
200 if (!ST) { // No symbol table to update? Just do the change.
202 // Free the name for this value.
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
224 ST->removeValueName(Name);
232 // Name is changing to something new.
233 Name = ST->createValueName(StringRef(NameStr, NameLen), this);
237 /// takeName - transfer the name from V to this value, setting V's name to
238 /// empty. It is an error to call V->takeName(V).
239 void Value::takeName(Value *V) {
240 ValueSymbolTable *ST = 0;
241 // If this value has a name, drop it.
243 // Get the symtab this is in.
244 if (getSymTab(this, ST)) {
245 // We can't set a name on this value, but we need to clear V's name if
247 if (V->hasName()) V->setName("");
248 return; // Cannot set a name on this value (e.g. constant).
253 ST->removeValueName(Name);
258 // Now we know that this has no name.
260 // If V has no name either, we're done.
261 if (!V->hasName()) return;
263 // Get this's symtab if we didn't before.
265 if (getSymTab(this, ST)) {
268 return; // Cannot set a name on this value (e.g. constant).
272 // Get V's ST, this should always succed, because V has a name.
273 ValueSymbolTable *VST;
274 bool Failure = getSymTab(V, VST);
275 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
277 // If these values are both in the same symtab, we can do this very fast.
278 // This works even if both values have no symtab yet.
283 Name->setValue(this);
287 // Otherwise, things are slightly more complex. Remove V's name from VST and
288 // then reinsert it into ST.
291 VST->removeValueName(V->Name);
294 Name->setValue(this);
297 ST->reinsertValue(this);
301 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
302 // except that it doesn't have all of the asserts. The asserts fail because we
303 // are half-way done resolving types, which causes some types to exist as two
304 // different Type*'s at the same time. This is a sledgehammer to work around
307 void Value::uncheckedReplaceAllUsesWith(Value *New) {
308 // Notify all ValueHandles (if present) that this value is going away.
310 ValueHandleBase::ValueIsRAUWd(this, New);
312 LLVMContext &Context = getContext();
313 Context.pImpl->TheMetadata.ValueIsRAUWd(this, New);
316 while (!use_empty()) {
318 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
319 // constant because they are uniqued.
320 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
321 if (!isa<GlobalValue>(C)) {
322 C->replaceUsesOfWithOnConstant(this, New, &U);
331 void Value::replaceAllUsesWith(Value *New) {
332 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
333 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
334 assert(New->getType() == getType() &&
335 "replaceAllUses of value with new value of different type!");
337 uncheckedReplaceAllUsesWith(New);
340 Value *Value::stripPointerCasts() {
341 if (!isa<PointerType>(getType()))
345 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
346 if (!GEP->hasAllZeroIndices())
348 V = GEP->getPointerOperand();
349 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
350 V = cast<Operator>(V)->getOperand(0);
351 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
352 if (GA->mayBeOverridden())
354 V = GA->getAliasee();
358 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
362 Value *Value::getUnderlyingObject() {
363 if (!isa<PointerType>(getType()))
366 unsigned MaxLookup = 6;
368 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
369 V = GEP->getPointerOperand();
370 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
371 V = cast<Operator>(V)->getOperand(0);
372 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
373 if (GA->mayBeOverridden())
375 V = GA->getAliasee();
379 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
380 } while (--MaxLookup);
384 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
385 /// return the value in the PHI node corresponding to PredBB. If not, return
386 /// ourself. This is useful if you want to know the value something has in a
387 /// predecessor block.
388 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
389 const BasicBlock *PredBB) {
390 PHINode *PN = dyn_cast<PHINode>(this);
391 if (PN && PN->getParent() == CurBB)
392 return PN->getIncomingValueForBlock(PredBB);
396 LLVMContext &Value::getContext() const { return VTy->getContext(); }
398 //===----------------------------------------------------------------------===//
399 // ValueHandleBase Class
400 //===----------------------------------------------------------------------===//
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 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
418 assert(List && "Must insert after existing node");
421 setPrevPtr(&List->Next);
424 Next->setPrevPtr(&Next);
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!");
431 LLVMContextImpl *pImpl = VP->getContext().pImpl;
433 if (VP->HasValueHandle) {
434 // If this value already has a ValueHandle, then it must be in the
435 // ValueHandles map already.
436 ValueHandleBase *&Entry = pImpl->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 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->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) {
462 // Okay, reallocation did happen. Fix the Prev Pointers.
463 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
464 E = Handles.end(); I != E; ++I) {
465 assert(I->second && I->first == I->second->VP && "List invariant broken!");
466 I->second->setPrevPtr(&I->second);
470 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
471 void ValueHandleBase::RemoveFromUseList() {
472 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
474 // Unlink this from its use list.
475 ValueHandleBase **PrevPtr = getPrevPtr();
476 assert(*PrevPtr == this && "List invariant broken");
480 assert(Next->getPrevPtr() == &Next && "List invariant broken");
481 Next->setPrevPtr(PrevPtr);
485 // If the Next pointer was null, then it is possible that this was the last
486 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
488 LLVMContextImpl *pImpl = VP->getContext().pImpl;
489 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
490 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
492 VP->HasValueHandle = false;
497 void ValueHandleBase::ValueIsDeleted(Value *V) {
498 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
500 // Get the linked list base, which is guaranteed to exist since the
501 // HasValueHandle flag is set.
502 LLVMContextImpl *pImpl = V->getContext().pImpl;
503 ValueHandleBase *Entry = pImpl->ValueHandles[V];
504 assert(Entry && "Value bit set but no entries exist");
506 // We use a local ValueHandleBase as an iterator so that
507 // ValueHandles can add and remove themselves from the list without
508 // breaking our iteration. This is not really an AssertingVH; we
509 // just have to give ValueHandleBase some kind.
510 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
511 Iterator.RemoveFromUseList();
512 Iterator.AddToExistingUseListAfter(Entry);
513 assert(Entry->Next == &Iterator && "Loop invariant broken.");
515 switch (Entry->getKind()) {
519 // Mark that this value has been deleted by setting it to an invalid Value
521 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
524 // Weak just goes to null, which will unlink it from the list.
528 // Forward to the subclass's implementation.
529 static_cast<CallbackVH*>(Entry)->deleted();
534 // All callbacks, weak references, and assertingVHs should be dropped by now.
535 if (V->HasValueHandle) {
536 #ifndef NDEBUG // Only in +Asserts mode...
537 errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
539 if (pImpl->ValueHandles[V]->getKind() == Assert)
540 llvm_unreachable("An asserting value handle still pointed to this"
544 llvm_unreachable("All references to V were not removed?");
549 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
550 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
551 assert(Old != New && "Changing value into itself!");
553 // Get the linked list base, which is guaranteed to exist since the
554 // HasValueHandle flag is set.
555 LLVMContextImpl *pImpl = Old->getContext().pImpl;
556 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
558 assert(Entry && "Value bit set but no entries exist");
560 // We use a local ValueHandleBase as an iterator so that
561 // ValueHandles can add and remove themselves from the list without
562 // breaking our iteration. This is not really an AssertingVH; we
563 // just have to give ValueHandleBase some kind.
564 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
565 Iterator.RemoveFromUseList();
566 Iterator.AddToExistingUseListAfter(Entry);
567 assert(Entry->Next == &Iterator && "Loop invariant broken.");
569 switch (Entry->getKind()) {
571 // Asserting handle does not follow RAUW implicitly.
574 // Tracking goes to new value like a WeakVH. Note that this may make it
575 // something incompatible with its templated type. We don't want to have a
576 // virtual (or inline) interface to handle this though, so instead we make
577 // the TrackingVH accessors guarantee that a client never sees this value.
581 // Weak goes to the new value, which will unlink it from Old's list.
582 Entry->operator=(New);
585 // Forward to the subclass's implementation.
586 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
592 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
594 CallbackVH::~CallbackVH() {}
597 //===----------------------------------------------------------------------===//
599 //===----------------------------------------------------------------------===//
601 // replaceUsesOfWith - Replaces all references to the "From" definition with
602 // references to the "To" definition.
604 void User::replaceUsesOfWith(Value *From, Value *To) {
605 if (From == To) return; // Duh what?
607 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
608 "Cannot call User::replaceUsesOfWith on a constant!");
610 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
611 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
612 // The side effects of this setOperand call include linking to
613 // "To", adding "this" to the uses list of To, and
614 // most importantly, removing "this" from the use list of "From".
615 setOperand(i, To); // Fix it now...