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