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/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/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),
44 SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
46 if (isa<CallInst>(this) || isa<InvokeInst>(this))
47 assert((VTy->isFirstClassType() || VTy->isVoidTy() ||
48 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
49 "invalid CallInst type!");
50 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
51 assert((VTy->isFirstClassType() || VTy->isVoidTy() ||
52 isa<OpaqueType>(ty)) &&
53 "Cannot create non-first-class values except for constants!");
57 // Notify all ValueHandles (if present) that this value is going away.
59 ValueHandleBase::ValueIsDeleted(this);
61 #ifndef NDEBUG // Only in -g mode...
62 // Check to make sure that there are no uses of this value that are still
63 // around when the value is destroyed. If there are, then we have a dangling
64 // reference and something is wrong. This code is here to print out what is
65 // still being referenced. The value in question should be printed as
69 dbgs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
70 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
71 dbgs() << "Use still stuck around after Def is destroyed:"
75 assert(use_empty() && "Uses remain when a value is destroyed!");
77 // If this value is named, destroy the name. This should not be in a symtab
82 // There should be no uses of this object anymore, remove it.
83 LeakDetector::removeGarbageObject(this);
86 /// hasNUses - Return true if this Value has exactly N users.
88 bool Value::hasNUses(unsigned N) const {
89 use_const_iterator UI = use_begin(), E = use_end();
92 if (UI == E) return false; // Too few.
96 /// hasNUsesOrMore - Return true if this value has N users or more. This is
97 /// logically equivalent to getNumUses() >= N.
99 bool Value::hasNUsesOrMore(unsigned N) const {
100 use_const_iterator UI = use_begin(), E = use_end();
103 if (UI == E) return false; // Too few.
108 /// isUsedInBasicBlock - Return true if this value is used in the specified
110 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
111 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
112 const Instruction *User = dyn_cast<Instruction>(*I);
113 if (User && User->getParent() == BB)
120 /// getNumUses - This method computes the number of uses of this Value. This
121 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
123 unsigned Value::getNumUses() const {
124 return (unsigned)std::distance(use_begin(), use_end());
127 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
129 if (Instruction *I = dyn_cast<Instruction>(V)) {
130 if (BasicBlock *P = I->getParent())
131 if (Function *PP = P->getParent())
132 ST = &PP->getValueSymbolTable();
133 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
134 if (Function *P = BB->getParent())
135 ST = &P->getValueSymbolTable();
136 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
137 if (Module *P = GV->getParent())
138 ST = &P->getValueSymbolTable();
139 } else if (Argument *A = dyn_cast<Argument>(V)) {
140 if (Function *P = A->getParent())
141 ST = &P->getValueSymbolTable();
142 } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
143 if (Module *P = N->getParent()) {
144 ST = &P->getValueSymbolTable();
146 } else if (isa<MDString>(V))
149 assert(isa<Constant>(V) && "Unknown value type!");
150 return true; // no name is setable for this.
155 StringRef Value::getName() const {
156 // Make sure the empty string is still a C string. For historical reasons,
157 // some clients want to call .data() on the result and expect it to be null
159 if (!Name) return StringRef("", 0);
160 return Name->getKey();
163 std::string Value::getNameStr() const {
164 return getName().str();
167 void Value::setName(const Twine &NewName) {
168 // Fast path for common IRBuilder case of setName("") when there is no name.
169 if (NewName.isTriviallyEmpty() && !hasName())
172 SmallString<256> NameData;
173 StringRef NameRef = NewName.toStringRef(NameData);
175 // Name isn't changing?
176 if (getName() == NameRef)
179 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
181 // Get the symbol table to update for this object.
182 ValueSymbolTable *ST;
183 if (getSymTab(this, ST))
184 return; // Cannot set a name on this value (e.g. constant).
186 if (!ST) { // No symbol table to update? Just do the change.
187 if (NameRef.empty()) {
188 // Free the name for this value.
197 // NOTE: Could optimize for the case the name is shrinking to not deallocate
200 // Create the new name.
201 Name = ValueName::Create(NameRef.begin(), NameRef.end());
202 Name->setValue(this);
206 // NOTE: Could optimize for the case the name is shrinking to not deallocate
210 ST->removeValueName(Name);
218 // Name is changing to something new.
219 Name = ST->createValueName(NameRef, this);
223 /// takeName - transfer the name from V to this value, setting V's name to
224 /// empty. It is an error to call V->takeName(V).
225 void Value::takeName(Value *V) {
226 ValueSymbolTable *ST = 0;
227 // If this value has a name, drop it.
229 // Get the symtab this is in.
230 if (getSymTab(this, ST)) {
231 // We can't set a name on this value, but we need to clear V's name if
233 if (V->hasName()) V->setName("");
234 return; // Cannot set a name on this value (e.g. constant).
239 ST->removeValueName(Name);
244 // Now we know that this has no name.
246 // If V has no name either, we're done.
247 if (!V->hasName()) return;
249 // Get this's symtab if we didn't before.
251 if (getSymTab(this, ST)) {
254 return; // Cannot set a name on this value (e.g. constant).
258 // Get V's ST, this should always succed, because V has a name.
259 ValueSymbolTable *VST;
260 bool Failure = getSymTab(V, VST);
261 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
263 // If these values are both in the same symtab, we can do this very fast.
264 // This works even if both values have no symtab yet.
269 Name->setValue(this);
273 // Otherwise, things are slightly more complex. Remove V's name from VST and
274 // then reinsert it into ST.
277 VST->removeValueName(V->Name);
280 Name->setValue(this);
283 ST->reinsertValue(this);
287 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
288 // except that it doesn't have all of the asserts. The asserts fail because we
289 // are half-way done resolving types, which causes some types to exist as two
290 // different Type*'s at the same time. This is a sledgehammer to work around
293 void Value::uncheckedReplaceAllUsesWith(Value *New) {
294 // Notify all ValueHandles (if present) that this value is going away.
296 ValueHandleBase::ValueIsRAUWd(this, New);
298 while (!use_empty()) {
300 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
301 // constant because they are uniqued.
302 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
303 if (!isa<GlobalValue>(C)) {
304 C->replaceUsesOfWithOnConstant(this, New, &U);
313 void Value::replaceAllUsesWith(Value *New) {
314 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
315 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
316 assert(New->getType() == getType() &&
317 "replaceAllUses of value with new value of different type!");
319 uncheckedReplaceAllUsesWith(New);
322 Value *Value::stripPointerCasts() {
323 if (!isa<PointerType>(getType()))
327 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
328 if (!GEP->hasAllZeroIndices())
330 V = GEP->getPointerOperand();
331 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
332 V = cast<Operator>(V)->getOperand(0);
333 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
334 if (GA->mayBeOverridden())
336 V = GA->getAliasee();
340 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
344 Value *Value::getUnderlyingObject() {
345 if (!isa<PointerType>(getType()))
348 unsigned MaxLookup = 6;
350 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
351 V = GEP->getPointerOperand();
352 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
353 V = cast<Operator>(V)->getOperand(0);
354 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
355 if (GA->mayBeOverridden())
357 V = GA->getAliasee();
361 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
362 } while (--MaxLookup);
366 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
367 /// return the value in the PHI node corresponding to PredBB. If not, return
368 /// ourself. This is useful if you want to know the value something has in a
369 /// predecessor block.
370 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
371 const BasicBlock *PredBB) {
372 PHINode *PN = dyn_cast<PHINode>(this);
373 if (PN && PN->getParent() == CurBB)
374 return PN->getIncomingValueForBlock(PredBB);
378 LLVMContext &Value::getContext() const { return VTy->getContext(); }
380 //===----------------------------------------------------------------------===//
381 // ValueHandleBase Class
382 //===----------------------------------------------------------------------===//
384 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
385 /// List is known to point into the existing use list.
386 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
387 assert(List && "Handle list is null?");
389 // Splice ourselves into the list.
394 Next->setPrevPtr(&Next);
395 assert(VP == Next->VP && "Added to wrong list?");
399 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
400 assert(List && "Must insert after existing node");
403 setPrevPtr(&List->Next);
406 Next->setPrevPtr(&Next);
409 /// AddToUseList - Add this ValueHandle to the use list for VP.
410 void ValueHandleBase::AddToUseList() {
411 assert(VP && "Null pointer doesn't have a use list!");
413 LLVMContextImpl *pImpl = VP->getContext().pImpl;
415 if (VP->HasValueHandle) {
416 // If this value already has a ValueHandle, then it must be in the
417 // ValueHandles map already.
418 ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
419 assert(Entry != 0 && "Value doesn't have any handles?");
420 AddToExistingUseList(&Entry);
424 // Ok, it doesn't have any handles yet, so we must insert it into the
425 // DenseMap. However, doing this insertion could cause the DenseMap to
426 // reallocate itself, which would invalidate all of the PrevP pointers that
427 // point into the old table. Handle this by checking for reallocation and
428 // updating the stale pointers only if needed.
429 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
430 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
432 ValueHandleBase *&Entry = Handles[VP];
433 assert(Entry == 0 && "Value really did already have handles?");
434 AddToExistingUseList(&Entry);
435 VP->HasValueHandle = true;
437 // If reallocation didn't happen or if this was the first insertion, don't
439 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
440 Handles.size() == 1) {
444 // Okay, reallocation did happen. Fix the Prev Pointers.
445 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
446 E = Handles.end(); I != E; ++I) {
447 assert(I->second && I->first == I->second->VP && "List invariant broken!");
448 I->second->setPrevPtr(&I->second);
452 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
453 void ValueHandleBase::RemoveFromUseList() {
454 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
456 // Unlink this from its use list.
457 ValueHandleBase **PrevPtr = getPrevPtr();
458 assert(*PrevPtr == this && "List invariant broken");
462 assert(Next->getPrevPtr() == &Next && "List invariant broken");
463 Next->setPrevPtr(PrevPtr);
467 // If the Next pointer was null, then it is possible that this was the last
468 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
470 LLVMContextImpl *pImpl = VP->getContext().pImpl;
471 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
472 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
474 VP->HasValueHandle = false;
479 void ValueHandleBase::ValueIsDeleted(Value *V) {
480 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
482 // Get the linked list base, which is guaranteed to exist since the
483 // HasValueHandle flag is set.
484 LLVMContextImpl *pImpl = V->getContext().pImpl;
485 ValueHandleBase *Entry = pImpl->ValueHandles[V];
486 assert(Entry && "Value bit set but no entries exist");
488 // We use a local ValueHandleBase as an iterator so that
489 // ValueHandles can add and remove themselves from the list without
490 // breaking our iteration. This is not really an AssertingVH; we
491 // just have to give ValueHandleBase some kind.
492 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
493 Iterator.RemoveFromUseList();
494 Iterator.AddToExistingUseListAfter(Entry);
495 assert(Entry->Next == &Iterator && "Loop invariant broken.");
497 switch (Entry->getKind()) {
501 // Mark that this value has been deleted by setting it to an invalid Value
503 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
506 // Weak just goes to null, which will unlink it from the list.
510 // Forward to the subclass's implementation.
511 static_cast<CallbackVH*>(Entry)->deleted();
516 // All callbacks, weak references, and assertingVHs should be dropped by now.
517 if (V->HasValueHandle) {
518 #ifndef NDEBUG // Only in +Asserts mode...
519 dbgs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
521 if (pImpl->ValueHandles[V]->getKind() == Assert)
522 llvm_unreachable("An asserting value handle still pointed to this"
526 llvm_unreachable("All references to V were not removed?");
531 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
532 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
533 assert(Old != New && "Changing value into itself!");
535 // Get the linked list base, which is guaranteed to exist since the
536 // HasValueHandle flag is set.
537 LLVMContextImpl *pImpl = Old->getContext().pImpl;
538 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
540 assert(Entry && "Value bit set but no entries exist");
542 // We use a local ValueHandleBase as an iterator so that
543 // ValueHandles can add and remove themselves from the list without
544 // breaking our iteration. This is not really an AssertingVH; we
545 // just have to give ValueHandleBase some kind.
546 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
547 Iterator.RemoveFromUseList();
548 Iterator.AddToExistingUseListAfter(Entry);
549 assert(Entry->Next == &Iterator && "Loop invariant broken.");
551 switch (Entry->getKind()) {
553 // Asserting handle does not follow RAUW implicitly.
556 // Tracking goes to new value like a WeakVH. Note that this may make it
557 // something incompatible with its templated type. We don't want to have a
558 // virtual (or inline) interface to handle this though, so instead we make
559 // the TrackingVH accessors guarantee that a client never sees this value.
563 // Weak goes to the new value, which will unlink it from Old's list.
564 Entry->operator=(New);
567 // Forward to the subclass's implementation.
568 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
574 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
576 CallbackVH::~CallbackVH() {}
579 //===----------------------------------------------------------------------===//
581 //===----------------------------------------------------------------------===//
583 // replaceUsesOfWith - Replaces all references to the "From" definition with
584 // references to the "To" definition.
586 void User::replaceUsesOfWith(Value *From, Value *To) {
587 if (From == To) return; // Duh what?
589 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
590 "Cannot call User::replaceUsesOfWith on a constant!");
592 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
593 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
594 // The side effects of this setOperand call include linking to
595 // "To", adding "this" to the uses list of To, and
596 // most importantly, removing "this" from the use list of "From".
597 setOperand(i, To); // Fix it now...