Remove Value::setName(const char*, unsigned).
[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/MDNode.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 (isa<MDString>(V))
146     return true;
147   else {
148     assert(isa<Constant>(V) && "Unknown value type!");
149     return true;  // no name is setable for this.
150   }
151   return false;
152 }
153
154 /// getNameStart - Return a pointer to a null terminated string for this name.
155 /// Note that names can have null characters within the string as well as at
156 /// their end.  This always returns a non-null pointer.
157 const char *Value::getNameStart() const {
158   if (Name == 0) return "";
159   return Name->getKeyData();
160 }
161
162 /// getNameLen - Return the length of the string, correctly handling nul
163 /// characters embedded into them.
164 unsigned Value::getNameLen() const {
165   return Name ? Name->getKeyLength() : 0;
166 }
167
168
169 std::string Value::getNameStr() const {
170   return getName().str();
171 }
172
173 void Value::setName(const Twine &NewName) {
174   SmallString<32> NameData;
175   NewName.toVector(NameData);
176
177   const char *NameStr = NameData.data();
178   unsigned NameLen = NameData.size();
179
180   if (NameLen == 0 && !hasName()) return;
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 isn't changing?
198       if (NameLen == Name->getKeyLength() &&
199           !memcmp(Name->getKeyData(), NameStr, NameLen))
200         return;
201       Name->Destroy();
202     }
203     
204     // NOTE: Could optimize for the case the name is shrinking to not deallocate
205     // then reallocated.
206       
207     // Create the new name.
208     Name = ValueName::Create(NameStr, NameStr+NameLen);
209     Name->setValue(this);
210     return;
211   }
212   
213   // NOTE: Could optimize for the case the name is shrinking to not deallocate
214   // then reallocated.
215   if (hasName()) {
216     // Name isn't changing?
217     if (NameLen == Name->getKeyLength() &&
218         !memcmp(Name->getKeyData(), NameStr, NameLen))
219       return;
220
221     // Remove old name.
222     ST->removeValueName(Name);
223     Name->Destroy();
224     Name = 0;
225
226     if (NameLen == 0)
227       return;
228   }
229
230   // Name is changing to something new.
231   Name = ST->createValueName(StringRef(NameStr, NameLen), this);
232 }
233
234
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.
240   if (hasName()) {
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
244       // it has one.
245       if (V->hasName()) V->setName("");
246       return;  // Cannot set a name on this value (e.g. constant).
247     }
248     
249     // Remove old name.
250     if (ST)
251       ST->removeValueName(Name);
252     Name->Destroy();
253     Name = 0;
254   } 
255   
256   // Now we know that this has no name.
257   
258   // If V has no name either, we're done.
259   if (!V->hasName()) return;
260    
261   // Get this's symtab if we didn't before.
262   if (!ST) {
263     if (getSymTab(this, ST)) {
264       // Clear V's name.
265       V->setName("");
266       return;  // Cannot set a name on this value (e.g. constant).
267     }
268   }
269   
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;
274   
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.
277   if (ST == VST) {
278     // Take the name!
279     Name = V->Name;
280     V->Name = 0;
281     Name->setValue(this);
282     return;
283   }
284   
285   // Otherwise, things are slightly more complex.  Remove V's name from VST and
286   // then reinsert it into ST.
287   
288   if (VST)
289     VST->removeValueName(V->Name);
290   Name = V->Name;
291   V->Name = 0;
292   Name->setValue(this);
293   
294   if (ST)
295     ST->reinsertValue(this);
296 }
297
298
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
303 // this problem.
304 //
305 void Value::uncheckedReplaceAllUsesWith(Value *New) {
306   // Notify all ValueHandles (if present) that this value is going away.
307   if (HasValueHandle)
308     ValueHandleBase::ValueIsRAUWd(this, New);
309  
310   while (!use_empty()) {
311     Use &U = *UseList;
312     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
313     // constant because they are uniqued.
314     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
315       if (!isa<GlobalValue>(C)) {
316         C->replaceUsesOfWithOnConstant(this, New, &U);
317         continue;
318       }
319     }
320     
321     U.set(New);
322   }
323 }
324
325 void Value::replaceAllUsesWith(Value *New) {
326   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
327   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
328   assert(New->getType() == getType() &&
329          "replaceAllUses of value with new value of different type!");
330
331   uncheckedReplaceAllUsesWith(New);
332 }
333
334 Value *Value::stripPointerCasts() {
335   if (!isa<PointerType>(getType()))
336     return this;
337   Value *V = this;
338   do {
339     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
340       if (!GEP->hasAllZeroIndices())
341         return V;
342       V = GEP->getPointerOperand();
343     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
344       V = cast<Operator>(V)->getOperand(0);
345     } else {
346       return V;
347     }
348     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
349   } while (1);
350 }
351
352 Value *Value::getUnderlyingObject() {
353   if (!isa<PointerType>(getType()))
354     return this;
355   Value *V = this;
356   unsigned MaxLookup = 6;
357   do {
358     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
359       V = GEP->getPointerOperand();
360     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
361       V = cast<Operator>(V)->getOperand(0);
362     } else {
363       return V;
364     }
365     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
366   } while (--MaxLookup);
367   return V;
368 }
369
370 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
371 /// return the value in the PHI node corresponding to PredBB.  If not, return
372 /// ourself.  This is useful if you want to know the value something has in a
373 /// predecessor block.
374 Value *Value::DoPHITranslation(const BasicBlock *CurBB, 
375                                const BasicBlock *PredBB) {
376   PHINode *PN = dyn_cast<PHINode>(this);
377   if (PN && PN->getParent() == CurBB)
378     return PN->getIncomingValueForBlock(PredBB);
379   return this;
380 }
381
382 LLVMContext &Value::getContext() const { return VTy->getContext(); }
383
384 //===----------------------------------------------------------------------===//
385 //                             ValueHandleBase Class
386 //===----------------------------------------------------------------------===//
387
388 /// ValueHandles - This map keeps track of all of the value handles that are
389 /// watching a Value*.  The Value::HasValueHandle bit is used to know whether or
390 /// not a value has an entry in this map.
391 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
392 static ManagedStatic<ValueHandlesTy> ValueHandles;
393 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
394
395 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
396 /// List is known to point into the existing use list.
397 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
398   assert(List && "Handle list is null?");
399   
400   // Splice ourselves into the list.
401   Next = *List;
402   *List = this;
403   setPrevPtr(List);
404   if (Next) {
405     Next->setPrevPtr(&Next);
406     assert(VP == Next->VP && "Added to wrong list?");
407   }
408 }
409
410 /// AddToUseList - Add this ValueHandle to the use list for VP.
411 void ValueHandleBase::AddToUseList() {
412   assert(VP && "Null pointer doesn't have a use list!");
413   if (VP->HasValueHandle) {
414     // If this value already has a ValueHandle, then it must be in the
415     // ValueHandles map already.
416     sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
417     ValueHandleBase *&Entry = (*ValueHandles)[VP];
418     assert(Entry != 0 && "Value doesn't have any handles?");
419     AddToExistingUseList(&Entry);
420     return;
421   }
422   
423   // Ok, it doesn't have any handles yet, so we must insert it into the
424   // DenseMap.  However, doing this insertion could cause the DenseMap to
425   // reallocate itself, which would invalidate all of the PrevP pointers that
426   // point into the old table.  Handle this by checking for reallocation and
427   // updating the stale pointers only if needed.
428   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
429   ValueHandlesTy &Handles = *ValueHandles;
430   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
431   
432   ValueHandleBase *&Entry = Handles[VP];
433   assert(Entry == 0 && "Value really did already have handles?");
434   AddToExistingUseList(&Entry);
435   VP->HasValueHandle = true;
436   
437   // If reallocation didn't happen or if this was the first insertion, don't
438   // walk the table.
439   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 
440       Handles.size() == 1) {
441     return;
442   }
443   
444   // Okay, reallocation did happen.  Fix the Prev Pointers.
445   for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
446        I != E; ++I) {
447     assert(I->second && I->first == I->second->VP && "List invariant broken!");
448     I->second->setPrevPtr(&I->second);
449   }
450 }
451
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!");
455
456   // Unlink this from its use list.
457   ValueHandleBase **PrevPtr = getPrevPtr();
458   assert(*PrevPtr == this && "List invariant broken");
459   
460   *PrevPtr = Next;
461   if (Next) {
462     assert(Next->getPrevPtr() == &Next && "List invariant broken");
463     Next->setPrevPtr(PrevPtr);
464     return;
465   }
466   
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
469   // map.
470   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
471   ValueHandlesTy &Handles = *ValueHandles;
472   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
473     Handles.erase(VP);
474     VP->HasValueHandle = false;
475   }
476 }
477
478
479 void ValueHandleBase::ValueIsDeleted(Value *V) {
480   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
481
482   // Get the linked list base, which is guaranteed to exist since the
483   // HasValueHandle flag is set.
484   ValueHandlesLock->reader_acquire();
485   ValueHandleBase *Entry = (*ValueHandles)[V];
486   ValueHandlesLock->reader_release();
487   assert(Entry && "Value bit set but no entries exist");
488   
489   while (Entry) {
490     // Advance pointer to avoid invalidation.
491     ValueHandleBase *ThisNode = Entry;
492     Entry = Entry->Next;
493     
494     switch (ThisNode->getKind()) {
495     case Assert:
496 #ifndef NDEBUG      // Only in -g mode...
497       errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
498              << "\n";
499 #endif
500       llvm_unreachable("An asserting value handle still pointed to this"
501                        " value!");
502     case Weak:
503       // Weak just goes to null, which will unlink it from the list.
504       ThisNode->operator=(0);
505       break;
506     case Callback:
507       // Forward to the subclass's implementation.
508       static_cast<CallbackVH*>(ThisNode)->deleted();
509       break;
510     }
511   }
512   
513   // All callbacks and weak references should be dropped by now.
514   assert(!V->HasValueHandle && "All references to V were not removed?");
515 }
516
517
518 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
519   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
520   assert(Old != New && "Changing value into itself!");
521   
522   // Get the linked list base, which is guaranteed to exist since the
523   // HasValueHandle flag is set.
524   ValueHandlesLock->reader_acquire();
525   ValueHandleBase *Entry = (*ValueHandles)[Old];
526   ValueHandlesLock->reader_release();
527   assert(Entry && "Value bit set but no entries exist");
528   
529   while (Entry) {
530     // Advance pointer to avoid invalidation.
531     ValueHandleBase *ThisNode = Entry;
532     Entry = Entry->Next;
533     
534     switch (ThisNode->getKind()) {
535     case Assert:
536       // Asserting handle does not follow RAUW implicitly.
537       break;
538     case Weak:
539       // Weak goes to the new value, which will unlink it from Old's list.
540       ThisNode->operator=(New);
541       break;
542     case Callback:
543       // Forward to the subclass's implementation.
544       static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
545       break;
546     }
547   }
548 }
549
550 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
551 /// more than once.
552 CallbackVH::~CallbackVH() {}
553
554
555 //===----------------------------------------------------------------------===//
556 //                                 User Class
557 //===----------------------------------------------------------------------===//
558
559 // replaceUsesOfWith - Replaces all references to the "From" definition with
560 // references to the "To" definition.
561 //
562 void User::replaceUsesOfWith(Value *From, Value *To) {
563   if (From == To) return;   // Duh what?
564
565   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
566          "Cannot call User::replaceUsesofWith on a constant!");
567
568   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
569     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
570       // The side effects of this setOperand call include linking to
571       // "To", adding "this" to the uses list of To, and
572       // most importantly, removing "this" from the use list of "From".
573       setOperand(i, To); // Fix it now...
574     }
575 }