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