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/Support/raw_ostream.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 static inline const Type *checkType(const Type *Ty) {
42 assert(Ty && "Value defined with a null type: Error!");
46 Value::Value(const Type *ty, unsigned scid)
47 : SubclassID(scid), HasValueHandle(0), HasMetadata(0),
48 SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
50 if (isa<CallInst>(this) || isa<InvokeInst>(this))
51 assert((VTy->isFirstClassType() ||
52 VTy == Type::getVoidTy(ty->getContext()) ||
53 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
54 "invalid CallInst type!");
55 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
56 assert((VTy->isFirstClassType() ||
57 VTy == Type::getVoidTy(ty->getContext()) ||
58 isa<OpaqueType>(ty)) &&
59 "Cannot create non-first-class values except for constants!");
64 LLVMContext &Context = getContext();
65 Context.pImpl->TheMetadata.ValueIsDeleted(this);
68 // Notify all ValueHandles (if present) that this value is going away.
70 ValueHandleBase::ValueIsDeleted(this);
72 #ifndef NDEBUG // Only in -g mode...
73 // Check to make sure that there are no uses of this value that are still
74 // around when the value is destroyed. If there are, then we have a dangling
75 // reference and something is wrong. This code is here to print out what is
76 // still being referenced. The value in question should be printed as
80 errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
81 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
82 errs() << "Use still stuck around after Def is destroyed:"
86 assert(use_empty() && "Uses remain when a value is destroyed!");
88 // If this value is named, destroy the name. This should not be in a symtab
93 // There should be no uses of this object anymore, remove it.
94 LeakDetector::removeGarbageObject(this);
97 /// hasNUses - Return true if this Value has exactly N users.
99 bool Value::hasNUses(unsigned N) const {
100 use_const_iterator UI = use_begin(), E = use_end();
103 if (UI == E) return false; // Too few.
107 /// hasNUsesOrMore - Return true if this value has N users or more. This is
108 /// logically equivalent to getNumUses() >= N.
110 bool Value::hasNUsesOrMore(unsigned N) const {
111 use_const_iterator UI = use_begin(), E = use_end();
114 if (UI == E) return false; // Too few.
119 /// isUsedInBasicBlock - Return true if this value is used in the specified
121 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
122 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
123 const Instruction *User = dyn_cast<Instruction>(*I);
124 if (User && User->getParent() == BB)
131 /// getNumUses - This method computes the number of uses of this Value. This
132 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
134 unsigned Value::getNumUses() const {
135 return (unsigned)std::distance(use_begin(), use_end());
138 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
140 if (Instruction *I = dyn_cast<Instruction>(V)) {
141 if (BasicBlock *P = I->getParent())
142 if (Function *PP = P->getParent())
143 ST = &PP->getValueSymbolTable();
144 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
145 if (Function *P = BB->getParent())
146 ST = &P->getValueSymbolTable();
147 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
148 if (Module *P = GV->getParent())
149 ST = &P->getValueSymbolTable();
150 } else if (Argument *A = dyn_cast<Argument>(V)) {
151 if (Function *P = A->getParent())
152 ST = &P->getValueSymbolTable();
153 } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
154 if (Module *P = N->getParent()) {
155 ST = &P->getValueSymbolTable();
157 } else if (isa<MDString>(V))
160 assert(isa<Constant>(V) && "Unknown value type!");
161 return true; // no name is setable for this.
166 StringRef Value::getName() const {
167 // Make sure the empty string is still a C string. For historical reasons,
168 // some clients want to call .data() on the result and expect it to be null
170 if (!Name) return StringRef("", 0);
171 return Name->getKey();
174 std::string Value::getNameStr() const {
175 return getName().str();
178 void Value::setName(const Twine &NewName) {
179 // Fast path for common IRBuilder case of setName("") when there is no name.
180 if (NewName.isTriviallyEmpty() && !hasName())
183 SmallString<256> NameData;
184 NewName.toVector(NameData);
186 const char *NameStr = NameData.data();
187 unsigned NameLen = NameData.size();
189 // Name isn't changing?
190 if (getName() == StringRef(NameStr, NameLen))
193 assert(getType() != Type::getVoidTy(getContext()) &&
194 "Cannot assign a name to void values!");
196 // Get the symbol table to update for this object.
197 ValueSymbolTable *ST;
198 if (getSymTab(this, ST))
199 return; // Cannot set a name on this value (e.g. constant).
201 if (!ST) { // No symbol table to update? Just do the change.
203 // Free the name for this value.
212 // NOTE: Could optimize for the case the name is shrinking to not deallocate
215 // Create the new name.
216 Name = ValueName::Create(NameStr, NameStr+NameLen);
217 Name->setValue(this);
221 // NOTE: Could optimize for the case the name is shrinking to not deallocate
225 ST->removeValueName(Name);
233 // Name is changing to something new.
234 Name = ST->createValueName(StringRef(NameStr, NameLen), this);
238 /// takeName - transfer the name from V to this value, setting V's name to
239 /// empty. It is an error to call V->takeName(V).
240 void Value::takeName(Value *V) {
241 ValueSymbolTable *ST = 0;
242 // If this value has a name, drop it.
244 // Get the symtab this is in.
245 if (getSymTab(this, ST)) {
246 // We can't set a name on this value, but we need to clear V's name if
248 if (V->hasName()) V->setName("");
249 return; // Cannot set a name on this value (e.g. constant).
254 ST->removeValueName(Name);
259 // Now we know that this has no name.
261 // If V has no name either, we're done.
262 if (!V->hasName()) return;
264 // Get this's symtab if we didn't before.
266 if (getSymTab(this, ST)) {
269 return; // Cannot set a name on this value (e.g. constant).
273 // Get V's ST, this should always succed, because V has a name.
274 ValueSymbolTable *VST;
275 bool Failure = getSymTab(V, VST);
276 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
278 // If these values are both in the same symtab, we can do this very fast.
279 // This works even if both values have no symtab yet.
284 Name->setValue(this);
288 // Otherwise, things are slightly more complex. Remove V's name from VST and
289 // then reinsert it into ST.
292 VST->removeValueName(V->Name);
295 Name->setValue(this);
298 ST->reinsertValue(this);
302 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
303 // except that it doesn't have all of the asserts. The asserts fail because we
304 // are half-way done resolving types, which causes some types to exist as two
305 // different Type*'s at the same time. This is a sledgehammer to work around
308 void Value::uncheckedReplaceAllUsesWith(Value *New) {
309 // Notify all ValueHandles (if present) that this value is going away.
311 ValueHandleBase::ValueIsRAUWd(this, New);
313 LLVMContext &Context = getContext();
314 Context.pImpl->TheMetadata.ValueIsRAUWd(this, New);
317 while (!use_empty()) {
319 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
320 // constant because they are uniqued.
321 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
322 if (!isa<GlobalValue>(C)) {
323 C->replaceUsesOfWithOnConstant(this, New, &U);
332 void Value::replaceAllUsesWith(Value *New) {
333 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
334 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
335 assert(New->getType() == getType() &&
336 "replaceAllUses of value with new value of different type!");
338 uncheckedReplaceAllUsesWith(New);
341 Value *Value::stripPointerCasts() {
342 if (!isa<PointerType>(getType()))
346 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
347 if (!GEP->hasAllZeroIndices())
349 V = GEP->getPointerOperand();
350 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
351 V = cast<Operator>(V)->getOperand(0);
352 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
353 if (GA->mayBeOverridden())
355 V = GA->getAliasee();
359 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
363 Value *Value::getUnderlyingObject() {
364 if (!isa<PointerType>(getType()))
367 unsigned MaxLookup = 6;
369 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
370 V = GEP->getPointerOperand();
371 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
372 V = cast<Operator>(V)->getOperand(0);
373 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
374 if (GA->mayBeOverridden())
376 V = GA->getAliasee();
380 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
381 } while (--MaxLookup);
385 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
386 /// return the value in the PHI node corresponding to PredBB. If not, return
387 /// ourself. This is useful if you want to know the value something has in a
388 /// predecessor block.
389 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
390 const BasicBlock *PredBB) {
391 PHINode *PN = dyn_cast<PHINode>(this);
392 if (PN && PN->getParent() == CurBB)
393 return PN->getIncomingValueForBlock(PredBB);
397 LLVMContext &Value::getContext() const { return VTy->getContext(); }
399 //===----------------------------------------------------------------------===//
400 // ValueHandleBase Class
401 //===----------------------------------------------------------------------===//
403 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
404 /// List is known to point into the existing use list.
405 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
406 assert(List && "Handle list is null?");
408 // Splice ourselves into the list.
413 Next->setPrevPtr(&Next);
414 assert(VP == Next->VP && "Added to wrong list?");
418 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
419 assert(List && "Must insert after existing node");
422 setPrevPtr(&List->Next);
425 Next->setPrevPtr(&Next);
428 /// AddToUseList - Add this ValueHandle to the use list for VP.
429 void ValueHandleBase::AddToUseList() {
430 assert(VP && "Null pointer doesn't have a use list!");
432 LLVMContextImpl *pImpl = VP->getContext().pImpl;
434 if (VP->HasValueHandle) {
435 // If this value already has a ValueHandle, then it must be in the
436 // ValueHandles map already.
437 ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
438 assert(Entry != 0 && "Value doesn't have any handles?");
439 AddToExistingUseList(&Entry);
443 // Ok, it doesn't have any handles yet, so we must insert it into the
444 // DenseMap. However, doing this insertion could cause the DenseMap to
445 // reallocate itself, which would invalidate all of the PrevP pointers that
446 // point into the old table. Handle this by checking for reallocation and
447 // updating the stale pointers only if needed.
448 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
449 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
451 ValueHandleBase *&Entry = Handles[VP];
452 assert(Entry == 0 && "Value really did already have handles?");
453 AddToExistingUseList(&Entry);
454 VP->HasValueHandle = true;
456 // If reallocation didn't happen or if this was the first insertion, don't
458 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
459 Handles.size() == 1) {
463 // Okay, reallocation did happen. Fix the Prev Pointers.
464 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
465 E = Handles.end(); I != E; ++I) {
466 assert(I->second && I->first == I->second->VP && "List invariant broken!");
467 I->second->setPrevPtr(&I->second);
471 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
472 void ValueHandleBase::RemoveFromUseList() {
473 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
475 // Unlink this from its use list.
476 ValueHandleBase **PrevPtr = getPrevPtr();
477 assert(*PrevPtr == this && "List invariant broken");
481 assert(Next->getPrevPtr() == &Next && "List invariant broken");
482 Next->setPrevPtr(PrevPtr);
486 // If the Next pointer was null, then it is possible that this was the last
487 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
489 LLVMContextImpl *pImpl = VP->getContext().pImpl;
490 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
491 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
493 VP->HasValueHandle = false;
498 void ValueHandleBase::ValueIsDeleted(Value *V) {
499 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
501 // Get the linked list base, which is guaranteed to exist since the
502 // HasValueHandle flag is set.
503 LLVMContextImpl *pImpl = V->getContext().pImpl;
504 ValueHandleBase *Entry = pImpl->ValueHandles[V];
505 assert(Entry && "Value bit set but no entries exist");
507 // We use a local ValueHandleBase as an iterator so that
508 // ValueHandles can add and remove themselves from the list without
509 // breaking our iteration. This is not really an AssertingVH; we
510 // just have to give ValueHandleBase some kind.
511 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
512 Iterator.RemoveFromUseList();
513 Iterator.AddToExistingUseListAfter(Entry);
514 assert(Entry->Next == &Iterator && "Loop invariant broken.");
516 switch (Entry->getKind()) {
520 // Mark that this value has been deleted by setting it to an invalid Value
522 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
525 // Weak just goes to null, which will unlink it from the list.
529 // Forward to the subclass's implementation.
530 static_cast<CallbackVH*>(Entry)->deleted();
535 // All callbacks, weak references, and assertingVHs should be dropped by now.
536 if (V->HasValueHandle) {
537 #ifndef NDEBUG // Only in +Asserts mode...
538 errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
540 if (pImpl->ValueHandles[V]->getKind() == Assert)
541 llvm_unreachable("An asserting value handle still pointed to this"
545 llvm_unreachable("All references to V were not removed?");
550 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
551 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
552 assert(Old != New && "Changing value into itself!");
554 // Get the linked list base, which is guaranteed to exist since the
555 // HasValueHandle flag is set.
556 LLVMContextImpl *pImpl = Old->getContext().pImpl;
557 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
559 assert(Entry && "Value bit set but no entries exist");
561 // We use a local ValueHandleBase as an iterator so that
562 // ValueHandles can add and remove themselves from the list without
563 // breaking our iteration. This is not really an AssertingVH; we
564 // just have to give ValueHandleBase some kind.
565 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
566 Iterator.RemoveFromUseList();
567 Iterator.AddToExistingUseListAfter(Entry);
568 assert(Entry->Next == &Iterator && "Loop invariant broken.");
570 switch (Entry->getKind()) {
572 // Asserting handle does not follow RAUW implicitly.
575 // Tracking goes to new value like a WeakVH. Note that this may make it
576 // something incompatible with its templated type. We don't want to have a
577 // virtual (or inline) interface to handle this though, so instead we make
578 // the TrackingVH accessors guarantee that a client never sees this value.
582 // Weak goes to the new value, which will unlink it from Old's list.
583 Entry->operator=(New);
586 // Forward to the subclass's implementation.
587 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
593 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
595 CallbackVH::~CallbackVH() {}
598 //===----------------------------------------------------------------------===//
600 //===----------------------------------------------------------------------===//
602 // replaceUsesOfWith - Replaces all references to the "From" definition with
603 // references to the "To" definition.
605 void User::replaceUsesOfWith(Value *From, Value *To) {
606 if (From == To) return; // Duh what?
608 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
609 "Cannot call User::replaceUsesOfWith on a constant!");
611 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
612 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
613 // The side effects of this setOperand call include linking to
614 // "To", adding "this" to the uses list of To, and
615 // most importantly, removing "this" from the use list of "From".
616 setOperand(i, To); // Fix it now...