revert r78048, it isn't worth using assertingvh here.
[oota-llvm.git] / lib / VMCore / Value.cpp
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Value, ValueHandle, and User classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constant.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/InstrTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Module.h"
21 #include "llvm/Metadata.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/Support/raw_ostream.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 //                                Value Class
38 //===----------------------------------------------------------------------===//
39
40 static inline const Type *checkType(const Type *Ty) {
41   assert(Ty && "Value defined with a null type: Error!");
42   return Ty;
43 }
44
45 Value::Value(const Type *ty, unsigned scid)
46   : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0),
47     SubclassData(0), VTy(checkType(ty)),
48     UseList(0), Name(0) {
49   if (isa<CallInst>(this) || isa<InvokeInst>(this))
50     assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
51             isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
52            "invalid CallInst  type!");
53   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
54     assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
55            isa<OpaqueType>(ty)) &&
56            "Cannot create non-first-class values except for constants!");
57 }
58
59 Value::~Value() {
60   // Notify all ValueHandles (if present) that this value is going away.
61   if (HasValueHandle)
62     ValueHandleBase::ValueIsDeleted(this);
63   
64 #ifndef NDEBUG      // Only in -g mode...
65   // Check to make sure that there are no uses of this value that are still
66   // around when the value is destroyed.  If there are, then we have a dangling
67   // reference and something is wrong.  This code is here to print out what is
68   // still being referenced.  The value in question should be printed as
69   // a <badref>
70   //
71   if (!use_empty()) {
72     errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
73     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
74       errs() << "Use still stuck around after Def is destroyed:"
75            << **I << "\n";
76   }
77 #endif
78   assert(use_empty() && "Uses remain when a value is destroyed!");
79
80   // If this value is named, destroy the name.  This should not be in a symtab
81   // at this point.
82   if (Name)
83     Name->Destroy();
84   
85   // There should be no uses of this object anymore, remove it.
86   LeakDetector::removeGarbageObject(this);
87 }
88
89 /// hasNUses - Return true if this Value has exactly N users.
90 ///
91 bool Value::hasNUses(unsigned N) const {
92   use_const_iterator UI = use_begin(), E = use_end();
93
94   for (; N; --N, ++UI)
95     if (UI == E) return false;  // Too few.
96   return UI == E;
97 }
98
99 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
100 /// logically equivalent to getNumUses() >= N.
101 ///
102 bool Value::hasNUsesOrMore(unsigned N) const {
103   use_const_iterator UI = use_begin(), E = use_end();
104
105   for (; N; --N, ++UI)
106     if (UI == E) return false;  // Too few.
107
108   return true;
109 }
110
111 /// isUsedInBasicBlock - Return true if this value is used in the specified
112 /// basic block.
113 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
114   for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
115     const Instruction *User = dyn_cast<Instruction>(*I);
116     if (User && User->getParent() == BB)
117       return true;
118   }
119   return false;
120 }
121
122
123 /// getNumUses - This method computes the number of uses of this Value.  This
124 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
125 /// values.
126 unsigned Value::getNumUses() const {
127   return (unsigned)std::distance(use_begin(), use_end());
128 }
129
130 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
131   ST = 0;
132   if (Instruction *I = dyn_cast<Instruction>(V)) {
133     if (BasicBlock *P = I->getParent())
134       if (Function *PP = P->getParent())
135         ST = &PP->getValueSymbolTable();
136   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
137     if (Function *P = BB->getParent()) 
138       ST = &P->getValueSymbolTable();
139   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
140     if (Module *P = GV->getParent()) 
141       ST = &P->getValueSymbolTable();
142   } else if (Argument *A = dyn_cast<Argument>(V)) {
143     if (Function *P = A->getParent()) 
144       ST = &P->getValueSymbolTable();
145   } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
146     if (Module *P = N->getParent()) {
147       ST = &P->getValueSymbolTable();
148     }
149   } else if (isa<MDString>(V))
150     return true;
151   else {
152     assert(isa<Constant>(V) && "Unknown value type!");
153     return true;  // no name is setable for this.
154   }
155   return false;
156 }
157
158 StringRef Value::getName() const {
159   // Make sure the empty string is still a C string. For historical reasons,
160   // some clients want to call .data() on the result and expect it to be null
161   // terminated.
162   if (!Name) return StringRef("", 0);
163   return Name->getKey();
164 }
165
166 std::string Value::getNameStr() const {
167   return getName().str();
168 }
169
170 void Value::setName(const Twine &NewName) {
171   SmallString<32> NameData;
172   NewName.toVector(NameData);
173
174   const char *NameStr = NameData.data();
175   unsigned NameLen = NameData.size();
176
177   // Name isn't changing?
178   if (getName() == StringRef(NameStr, NameLen))
179     return;
180
181   assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
182   
183   // Get the symbol table to update for this object.
184   ValueSymbolTable *ST;
185   if (getSymTab(this, ST))
186     return;  // Cannot set a name on this value (e.g. constant).
187
188   if (!ST) { // No symbol table to update?  Just do the change.
189     if (NameLen == 0) {
190       // Free the name for this value.
191       Name->Destroy();
192       Name = 0;
193       return;
194     }
195     
196     if (Name)
197       Name->Destroy();
198     
199     // NOTE: Could optimize for the case the name is shrinking to not deallocate
200     // then reallocated.
201       
202     // Create the new name.
203     Name = ValueName::Create(NameStr, NameStr+NameLen);
204     Name->setValue(this);
205     return;
206   }
207   
208   // NOTE: Could optimize for the case the name is shrinking to not deallocate
209   // then reallocated.
210   if (hasName()) {
211     // Remove old name.
212     ST->removeValueName(Name);
213     Name->Destroy();
214     Name = 0;
215
216     if (NameLen == 0)
217       return;
218   }
219
220   // Name is changing to something new.
221   Name = ST->createValueName(StringRef(NameStr, NameLen), this);
222 }
223
224
225 /// takeName - transfer the name from V to this value, setting V's name to
226 /// empty.  It is an error to call V->takeName(V). 
227 void Value::takeName(Value *V) {
228   ValueSymbolTable *ST = 0;
229   // If this value has a name, drop it.
230   if (hasName()) {
231     // Get the symtab this is in.
232     if (getSymTab(this, ST)) {
233       // We can't set a name on this value, but we need to clear V's name if
234       // it has one.
235       if (V->hasName()) V->setName("");
236       return;  // Cannot set a name on this value (e.g. constant).
237     }
238     
239     // Remove old name.
240     if (ST)
241       ST->removeValueName(Name);
242     Name->Destroy();
243     Name = 0;
244   } 
245   
246   // Now we know that this has no name.
247   
248   // If V has no name either, we're done.
249   if (!V->hasName()) return;
250    
251   // Get this's symtab if we didn't before.
252   if (!ST) {
253     if (getSymTab(this, ST)) {
254       // Clear V's name.
255       V->setName("");
256       return;  // Cannot set a name on this value (e.g. constant).
257     }
258   }
259   
260   // Get V's ST, this should always succed, because V has a name.
261   ValueSymbolTable *VST;
262   bool Failure = getSymTab(V, VST);
263   assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
264   
265   // If these values are both in the same symtab, we can do this very fast.
266   // This works even if both values have no symtab yet.
267   if (ST == VST) {
268     // Take the name!
269     Name = V->Name;
270     V->Name = 0;
271     Name->setValue(this);
272     return;
273   }
274   
275   // Otherwise, things are slightly more complex.  Remove V's name from VST and
276   // then reinsert it into ST.
277   
278   if (VST)
279     VST->removeValueName(V->Name);
280   Name = V->Name;
281   V->Name = 0;
282   Name->setValue(this);
283   
284   if (ST)
285     ST->reinsertValue(this);
286 }
287
288
289 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
290 // except that it doesn't have all of the asserts.  The asserts fail because we
291 // are half-way done resolving types, which causes some types to exist as two
292 // different Type*'s at the same time.  This is a sledgehammer to work around
293 // this problem.
294 //
295 void Value::uncheckedReplaceAllUsesWith(Value *New) {
296   // Notify all ValueHandles (if present) that this value is going away.
297   if (HasValueHandle)
298     ValueHandleBase::ValueIsRAUWd(this, New);
299  
300   while (!use_empty()) {
301     Use &U = *UseList;
302     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
303     // constant because they are uniqued.
304     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
305       if (!isa<GlobalValue>(C)) {
306         C->replaceUsesOfWithOnConstant(this, New, &U);
307         continue;
308       }
309     }
310     
311     U.set(New);
312   }
313 }
314
315 void Value::replaceAllUsesWith(Value *New) {
316   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
317   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
318   assert(New->getType() == getType() &&
319          "replaceAllUses of value with new value of different type!");
320
321   uncheckedReplaceAllUsesWith(New);
322 }
323
324 Value *Value::stripPointerCasts() {
325   if (!isa<PointerType>(getType()))
326     return this;
327   Value *V = this;
328   do {
329     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
330       if (!GEP->hasAllZeroIndices())
331         return V;
332       V = GEP->getPointerOperand();
333     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
334       V = cast<Operator>(V)->getOperand(0);
335     } else {
336       return V;
337     }
338     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
339   } while (1);
340 }
341
342 Value *Value::getUnderlyingObject() {
343   if (!isa<PointerType>(getType()))
344     return this;
345   Value *V = this;
346   unsigned MaxLookup = 6;
347   do {
348     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
349       V = GEP->getPointerOperand();
350     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
351       V = cast<Operator>(V)->getOperand(0);
352     } else {
353       return V;
354     }
355     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
356   } while (--MaxLookup);
357   return V;
358 }
359
360 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
361 /// return the value in the PHI node corresponding to PredBB.  If not, return
362 /// ourself.  This is useful if you want to know the value something has in a
363 /// predecessor block.
364 Value *Value::DoPHITranslation(const BasicBlock *CurBB, 
365                                const BasicBlock *PredBB) {
366   PHINode *PN = dyn_cast<PHINode>(this);
367   if (PN && PN->getParent() == CurBB)
368     return PN->getIncomingValueForBlock(PredBB);
369   return this;
370 }
371
372 LLVMContext &Value::getContext() const { return VTy->getContext(); }
373
374 //===----------------------------------------------------------------------===//
375 //                             ValueHandleBase Class
376 //===----------------------------------------------------------------------===//
377
378 /// ValueHandles - This map keeps track of all of the value handles that are
379 /// watching a Value*.  The Value::HasValueHandle bit is used to know whether or
380 /// not a value has an entry in this map.
381 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
382 static ManagedStatic<ValueHandlesTy> ValueHandles;
383 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
384
385 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
386 /// List is known to point into the existing use list.
387 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
388   assert(List && "Handle list is null?");
389   
390   // Splice ourselves into the list.
391   Next = *List;
392   *List = this;
393   setPrevPtr(List);
394   if (Next) {
395     Next->setPrevPtr(&Next);
396     assert(VP == Next->VP && "Added to wrong list?");
397   }
398 }
399
400 /// AddToUseList - Add this ValueHandle to the use list for VP.
401 void ValueHandleBase::AddToUseList() {
402   assert(VP && "Null pointer doesn't have a use list!");
403   if (VP->HasValueHandle) {
404     // If this value already has a ValueHandle, then it must be in the
405     // ValueHandles map already.
406     sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
407     ValueHandleBase *&Entry = (*ValueHandles)[VP];
408     assert(Entry != 0 && "Value doesn't have any handles?");
409     AddToExistingUseList(&Entry);
410     return;
411   }
412   
413   // Ok, it doesn't have any handles yet, so we must insert it into the
414   // DenseMap.  However, doing this insertion could cause the DenseMap to
415   // reallocate itself, which would invalidate all of the PrevP pointers that
416   // point into the old table.  Handle this by checking for reallocation and
417   // updating the stale pointers only if needed.
418   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
419   ValueHandlesTy &Handles = *ValueHandles;
420   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
421   
422   ValueHandleBase *&Entry = Handles[VP];
423   assert(Entry == 0 && "Value really did already have handles?");
424   AddToExistingUseList(&Entry);
425   VP->HasValueHandle = true;
426   
427   // If reallocation didn't happen or if this was the first insertion, don't
428   // walk the table.
429   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 
430       Handles.size() == 1) {
431     return;
432   }
433   
434   // Okay, reallocation did happen.  Fix the Prev Pointers.
435   for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
436        I != E; ++I) {
437     assert(I->second && I->first == I->second->VP && "List invariant broken!");
438     I->second->setPrevPtr(&I->second);
439   }
440 }
441
442 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
443 void ValueHandleBase::RemoveFromUseList() {
444   assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
445
446   // Unlink this from its use list.
447   ValueHandleBase **PrevPtr = getPrevPtr();
448   assert(*PrevPtr == this && "List invariant broken");
449   
450   *PrevPtr = Next;
451   if (Next) {
452     assert(Next->getPrevPtr() == &Next && "List invariant broken");
453     Next->setPrevPtr(PrevPtr);
454     return;
455   }
456   
457   // If the Next pointer was null, then it is possible that this was the last
458   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
459   // map.
460   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
461   ValueHandlesTy &Handles = *ValueHandles;
462   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
463     Handles.erase(VP);
464     VP->HasValueHandle = false;
465   }
466 }
467
468
469 void ValueHandleBase::ValueIsDeleted(Value *V) {
470   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
471
472   // Get the linked list base, which is guaranteed to exist since the
473   // HasValueHandle flag is set.
474   ValueHandlesLock->reader_acquire();
475   ValueHandleBase *Entry = (*ValueHandles)[V];
476   ValueHandlesLock->reader_release();
477   assert(Entry && "Value bit set but no entries exist");
478   
479   while (Entry) {
480     // Advance pointer to avoid invalidation.
481     ValueHandleBase *ThisNode = Entry;
482     Entry = Entry->Next;
483     
484     switch (ThisNode->getKind()) {
485     case Assert:
486 #ifndef NDEBUG      // Only in -g mode...
487       errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
488              << "\n";
489 #endif
490       llvm_unreachable("An asserting value handle still pointed to this"
491                        " value!");
492     case Weak:
493       // Weak just goes to null, which will unlink it from the list.
494       ThisNode->operator=(0);
495       break;
496     case Callback:
497       // Forward to the subclass's implementation.
498       static_cast<CallbackVH*>(ThisNode)->deleted();
499       break;
500     }
501   }
502   
503   // All callbacks and weak references should be dropped by now.
504   assert(!V->HasValueHandle && "All references to V were not removed?");
505 }
506
507
508 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
509   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
510   assert(Old != New && "Changing value into itself!");
511   
512   // Get the linked list base, which is guaranteed to exist since the
513   // HasValueHandle flag is set.
514   ValueHandlesLock->reader_acquire();
515   ValueHandleBase *Entry = (*ValueHandles)[Old];
516   ValueHandlesLock->reader_release();
517   assert(Entry && "Value bit set but no entries exist");
518   
519   while (Entry) {
520     // Advance pointer to avoid invalidation.
521     ValueHandleBase *ThisNode = Entry;
522     Entry = Entry->Next;
523     
524     switch (ThisNode->getKind()) {
525     case Assert:
526       // Asserting handle does not follow RAUW implicitly.
527       break;
528     case Weak:
529       // Weak goes to the new value, which will unlink it from Old's list.
530       ThisNode->operator=(New);
531       break;
532     case Callback:
533       // Forward to the subclass's implementation.
534       static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
535       break;
536     }
537   }
538 }
539
540 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
541 /// more than once.
542 CallbackVH::~CallbackVH() {}
543
544
545 //===----------------------------------------------------------------------===//
546 //                                 User Class
547 //===----------------------------------------------------------------------===//
548
549 // replaceUsesOfWith - Replaces all references to the "From" definition with
550 // references to the "To" definition.
551 //
552 void User::replaceUsesOfWith(Value *From, Value *To) {
553   if (From == To) return;   // Duh what?
554
555   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
556          "Cannot call User::replaceUsesofWith on a constant!");
557
558   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
559     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
560       // The side effects of this setOperand call include linking to
561       // "To", adding "this" to the uses list of To, and
562       // most importantly, removing "this" from the use list of "From".
563       setOperand(i, To); // Fix it now...
564     }
565 }