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/ADT/DenseMap.h"
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 static inline const Type *checkType(const Type *Ty) {
39 assert(Ty && "Value defined with a null type: Error!");
43 Value::Value(const Type *ty, unsigned scid)
44 : SubclassID(scid), HasValueHandle(0), HasMetadata(0),
45 SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
47 if (isa<CallInst>(this) || isa<InvokeInst>(this))
48 assert((VTy->isFirstClassType() ||
49 VTy == Type::getVoidTy(ty->getContext()) ||
50 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
51 "invalid CallInst type!");
52 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
53 assert((VTy->isFirstClassType() ||
54 VTy == Type::getVoidTy(ty->getContext()) ||
55 isa<OpaqueType>(ty)) &&
56 "Cannot create non-first-class values except for constants!");
61 LLVMContext &Context = getContext();
62 Context.pImpl->TheMetadata.ValueIsDeleted(this);
65 // Notify all ValueHandles (if present) that this value is going away.
67 ValueHandleBase::ValueIsDeleted(this);
69 #ifndef NDEBUG // Only in -g mode...
70 // Check to make sure that there are no uses of this value that are still
71 // around when the value is destroyed. If there are, then we have a dangling
72 // reference and something is wrong. This code is here to print out what is
73 // still being referenced. The value in question should be printed as
77 errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
78 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
79 errs() << "Use still stuck around after Def is destroyed:"
83 assert(use_empty() && "Uses remain when a value is destroyed!");
85 // If this value is named, destroy the name. This should not be in a symtab
90 // There should be no uses of this object anymore, remove it.
91 LeakDetector::removeGarbageObject(this);
94 /// hasNUses - Return true if this Value has exactly N users.
96 bool Value::hasNUses(unsigned N) const {
97 use_const_iterator UI = use_begin(), E = use_end();
100 if (UI == E) return false; // Too few.
104 /// hasNUsesOrMore - Return true if this value has N users or more. This is
105 /// logically equivalent to getNumUses() >= N.
107 bool Value::hasNUsesOrMore(unsigned N) const {
108 use_const_iterator UI = use_begin(), E = use_end();
111 if (UI == E) return false; // Too few.
116 /// isUsedInBasicBlock - Return true if this value is used in the specified
118 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
119 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
120 const Instruction *User = dyn_cast<Instruction>(*I);
121 if (User && User->getParent() == BB)
128 /// getNumUses - This method computes the number of uses of this Value. This
129 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
131 unsigned Value::getNumUses() const {
132 return (unsigned)std::distance(use_begin(), use_end());
135 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
137 if (Instruction *I = dyn_cast<Instruction>(V)) {
138 if (BasicBlock *P = I->getParent())
139 if (Function *PP = P->getParent())
140 ST = &PP->getValueSymbolTable();
141 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
142 if (Function *P = BB->getParent())
143 ST = &P->getValueSymbolTable();
144 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
145 if (Module *P = GV->getParent())
146 ST = &P->getValueSymbolTable();
147 } else if (Argument *A = dyn_cast<Argument>(V)) {
148 if (Function *P = A->getParent())
149 ST = &P->getValueSymbolTable();
150 } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
151 if (Module *P = N->getParent()) {
152 ST = &P->getValueSymbolTable();
154 } else if (isa<MDString>(V))
157 assert(isa<Constant>(V) && "Unknown value type!");
158 return true; // no name is setable for this.
163 StringRef Value::getName() const {
164 // Make sure the empty string is still a C string. For historical reasons,
165 // some clients want to call .data() on the result and expect it to be null
167 if (!Name) return StringRef("", 0);
168 return Name->getKey();
171 std::string Value::getNameStr() const {
172 return getName().str();
175 void Value::setName(const Twine &NewName) {
176 // Fast path for common IRBuilder case of setName("") when there is no name.
177 if (NewName.isTriviallyEmpty() && !hasName())
180 SmallString<256> NameData;
181 NewName.toVector(NameData);
183 const char *NameStr = NameData.data();
184 unsigned NameLen = NameData.size();
186 // Name isn't changing?
187 if (getName() == StringRef(NameStr, NameLen))
190 assert(getType() != Type::getVoidTy(getContext()) &&
191 "Cannot assign a name to void values!");
193 // Get the symbol table to update for this object.
194 ValueSymbolTable *ST;
195 if (getSymTab(this, ST))
196 return; // Cannot set a name on this value (e.g. constant).
198 if (!ST) { // No symbol table to update? Just do the change.
200 // Free the name for this value.
209 // NOTE: Could optimize for the case the name is shrinking to not deallocate
212 // Create the new name.
213 Name = ValueName::Create(NameStr, NameStr+NameLen);
214 Name->setValue(this);
218 // NOTE: Could optimize for the case the name is shrinking to not deallocate
222 ST->removeValueName(Name);
230 // Name is changing to something new.
231 Name = ST->createValueName(StringRef(NameStr, NameLen), this);
235 /// takeName - transfer the name from V to this value, setting V's name to
236 /// empty. It is an error to call V->takeName(V).
237 void Value::takeName(Value *V) {
238 ValueSymbolTable *ST = 0;
239 // If this value has a name, drop it.
241 // Get the symtab this is in.
242 if (getSymTab(this, ST)) {
243 // We can't set a name on this value, but we need to clear V's name if
245 if (V->hasName()) V->setName("");
246 return; // Cannot set a name on this value (e.g. constant).
251 ST->removeValueName(Name);
256 // Now we know that this has no name.
258 // If V has no name either, we're done.
259 if (!V->hasName()) return;
261 // Get this's symtab if we didn't before.
263 if (getSymTab(this, ST)) {
266 return; // Cannot set a name on this value (e.g. constant).
270 // Get V's ST, this should always succed, because V has a name.
271 ValueSymbolTable *VST;
272 bool Failure = getSymTab(V, VST);
273 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
275 // If these values are both in the same symtab, we can do this very fast.
276 // This works even if both values have no symtab yet.
281 Name->setValue(this);
285 // Otherwise, things are slightly more complex. Remove V's name from VST and
286 // then reinsert it into ST.
289 VST->removeValueName(V->Name);
292 Name->setValue(this);
295 ST->reinsertValue(this);
299 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
300 // except that it doesn't have all of the asserts. The asserts fail because we
301 // are half-way done resolving types, which causes some types to exist as two
302 // different Type*'s at the same time. This is a sledgehammer to work around
305 void Value::uncheckedReplaceAllUsesWith(Value *New) {
306 // Notify all ValueHandles (if present) that this value is going away.
308 ValueHandleBase::ValueIsRAUWd(this, New);
310 LLVMContext &Context = getContext();
311 Context.pImpl->TheMetadata.ValueIsRAUWd(this, New);
314 while (!use_empty()) {
316 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
317 // constant because they are uniqued.
318 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
319 if (!isa<GlobalValue>(C)) {
320 C->replaceUsesOfWithOnConstant(this, New, &U);
329 void Value::replaceAllUsesWith(Value *New) {
330 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
331 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
332 assert(New->getType() == getType() &&
333 "replaceAllUses of value with new value of different type!");
335 uncheckedReplaceAllUsesWith(New);
338 Value *Value::stripPointerCasts() {
339 if (!isa<PointerType>(getType()))
343 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
344 if (!GEP->hasAllZeroIndices())
346 V = GEP->getPointerOperand();
347 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
348 V = cast<Operator>(V)->getOperand(0);
349 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
350 if (GA->mayBeOverridden())
352 V = GA->getAliasee();
356 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
360 Value *Value::getUnderlyingObject() {
361 if (!isa<PointerType>(getType()))
364 unsigned MaxLookup = 6;
366 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
367 V = GEP->getPointerOperand();
368 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
369 V = cast<Operator>(V)->getOperand(0);
370 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
371 if (GA->mayBeOverridden())
373 V = GA->getAliasee();
377 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
378 } while (--MaxLookup);
382 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
383 /// return the value in the PHI node corresponding to PredBB. If not, return
384 /// ourself. This is useful if you want to know the value something has in a
385 /// predecessor block.
386 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
387 const BasicBlock *PredBB) {
388 PHINode *PN = dyn_cast<PHINode>(this);
389 if (PN && PN->getParent() == CurBB)
390 return PN->getIncomingValueForBlock(PredBB);
394 LLVMContext &Value::getContext() const { return VTy->getContext(); }
396 //===----------------------------------------------------------------------===//
397 // ValueHandleBase Class
398 //===----------------------------------------------------------------------===//
400 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
401 /// List is known to point into the existing use list.
402 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
403 assert(List && "Handle list is null?");
405 // Splice ourselves into the list.
410 Next->setPrevPtr(&Next);
411 assert(VP == Next->VP && "Added to wrong list?");
415 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
416 assert(List && "Must insert after existing node");
419 setPrevPtr(&List->Next);
422 Next->setPrevPtr(&Next);
425 /// AddToUseList - Add this ValueHandle to the use list for VP.
426 void ValueHandleBase::AddToUseList() {
427 assert(VP && "Null pointer doesn't have a use list!");
429 LLVMContextImpl *pImpl = VP->getContext().pImpl;
431 if (VP->HasValueHandle) {
432 // If this value already has a ValueHandle, then it must be in the
433 // ValueHandles map already.
434 ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
435 assert(Entry != 0 && "Value doesn't have any handles?");
436 AddToExistingUseList(&Entry);
440 // Ok, it doesn't have any handles yet, so we must insert it into the
441 // DenseMap. However, doing this insertion could cause the DenseMap to
442 // reallocate itself, which would invalidate all of the PrevP pointers that
443 // point into the old table. Handle this by checking for reallocation and
444 // updating the stale pointers only if needed.
445 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
446 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
448 ValueHandleBase *&Entry = Handles[VP];
449 assert(Entry == 0 && "Value really did already have handles?");
450 AddToExistingUseList(&Entry);
451 VP->HasValueHandle = true;
453 // If reallocation didn't happen or if this was the first insertion, don't
455 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
456 Handles.size() == 1) {
460 // Okay, reallocation did happen. Fix the Prev Pointers.
461 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
462 E = Handles.end(); I != E; ++I) {
463 assert(I->second && I->first == I->second->VP && "List invariant broken!");
464 I->second->setPrevPtr(&I->second);
468 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
469 void ValueHandleBase::RemoveFromUseList() {
470 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
472 // Unlink this from its use list.
473 ValueHandleBase **PrevPtr = getPrevPtr();
474 assert(*PrevPtr == this && "List invariant broken");
478 assert(Next->getPrevPtr() == &Next && "List invariant broken");
479 Next->setPrevPtr(PrevPtr);
483 // If the Next pointer was null, then it is possible that this was the last
484 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
486 LLVMContextImpl *pImpl = VP->getContext().pImpl;
487 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
488 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
490 VP->HasValueHandle = false;
495 void ValueHandleBase::ValueIsDeleted(Value *V) {
496 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
498 // Get the linked list base, which is guaranteed to exist since the
499 // HasValueHandle flag is set.
500 LLVMContextImpl *pImpl = V->getContext().pImpl;
501 ValueHandleBase *Entry = pImpl->ValueHandles[V];
502 assert(Entry && "Value bit set but no entries exist");
504 // We use a local ValueHandleBase as an iterator so that
505 // ValueHandles can add and remove themselves from the list without
506 // breaking our iteration. This is not really an AssertingVH; we
507 // just have to give ValueHandleBase some kind.
508 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
509 Iterator.RemoveFromUseList();
510 Iterator.AddToExistingUseListAfter(Entry);
511 assert(Entry->Next == &Iterator && "Loop invariant broken.");
513 switch (Entry->getKind()) {
517 // Mark that this value has been deleted by setting it to an invalid Value
519 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
522 // Weak just goes to null, which will unlink it from the list.
526 // Forward to the subclass's implementation.
527 static_cast<CallbackVH*>(Entry)->deleted();
532 // All callbacks, weak references, and assertingVHs should be dropped by now.
533 if (V->HasValueHandle) {
534 #ifndef NDEBUG // Only in +Asserts mode...
535 errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
537 if (pImpl->ValueHandles[V]->getKind() == Assert)
538 llvm_unreachable("An asserting value handle still pointed to this"
542 llvm_unreachable("All references to V were not removed?");
547 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
548 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
549 assert(Old != New && "Changing value into itself!");
551 // Get the linked list base, which is guaranteed to exist since the
552 // HasValueHandle flag is set.
553 LLVMContextImpl *pImpl = Old->getContext().pImpl;
554 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
556 assert(Entry && "Value bit set but no entries exist");
558 // We use a local ValueHandleBase as an iterator so that
559 // ValueHandles can add and remove themselves from the list without
560 // breaking our iteration. This is not really an AssertingVH; we
561 // just have to give ValueHandleBase some kind.
562 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
563 Iterator.RemoveFromUseList();
564 Iterator.AddToExistingUseListAfter(Entry);
565 assert(Entry->Next == &Iterator && "Loop invariant broken.");
567 switch (Entry->getKind()) {
569 // Asserting handle does not follow RAUW implicitly.
572 // Tracking goes to new value like a WeakVH. Note that this may make it
573 // something incompatible with its templated type. We don't want to have a
574 // virtual (or inline) interface to handle this though, so instead we make
575 // the TrackingVH accessors guarantee that a client never sees this value.
579 // Weak goes to the new value, which will unlink it from Old's list.
580 Entry->operator=(New);
583 // Forward to the subclass's implementation.
584 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
590 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
592 CallbackVH::~CallbackVH() {}
595 //===----------------------------------------------------------------------===//
597 //===----------------------------------------------------------------------===//
599 // replaceUsesOfWith - Replaces all references to the "From" definition with
600 // references to the "To" definition.
602 void User::replaceUsesOfWith(Value *From, Value *To) {
603 if (From == To) return; // Duh what?
605 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
606 "Cannot call User::replaceUsesOfWith on a constant!");
608 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
609 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
610 // The side effects of this setOperand call include linking to
611 // "To", adding "this" to the uses list of To, and
612 // most importantly, removing "this" from the use list of "From".
613 setOperand(i, To); // Fix it now...