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