Land the long talked about "type system rewrite" patch. This
[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 "LLVMContextImpl.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InstrTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Operator.h"
21 #include "llvm/Module.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LeakDetector.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include <algorithm>
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 //                                Value Class
36 //===----------------------------------------------------------------------===//
37
38 static inline Type *checkType(const Type *Ty) {
39   assert(Ty && "Value defined with a null type: Error!");
40   return const_cast<Type*>(Ty);
41 }
42
43 Value::Value(const Type *ty, unsigned scid)
44   : SubclassID(scid), HasValueHandle(0),
45     SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
46     UseList(0), Name(0) {
47   // FIXME: Why isn't this in the subclass gunk??
48   if (isa<CallInst>(this) || isa<InvokeInst>(this))
49     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
50            "invalid CallInst type!");
51   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
52     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
53            "Cannot create non-first-class values except for constants!");
54 }
55
56 Value::~Value() {
57   // Notify all ValueHandles (if present) that this value is going away.
58   if (HasValueHandle)
59     ValueHandleBase::ValueIsDeleted(this);
60
61 #ifndef NDEBUG      // Only in -g mode...
62   // Check to make sure that there are no uses of this value that are still
63   // around when the value is destroyed.  If there are, then we have a dangling
64   // reference and something is wrong.  This code is here to print out what is
65   // still being referenced.  The value in question should be printed as
66   // a <badref>
67   //
68   if (!use_empty()) {
69     dbgs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
70     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
71       dbgs() << "Use still stuck around after Def is destroyed:"
72            << **I << "\n";
73   }
74 #endif
75   assert(use_empty() && "Uses remain when a value is destroyed!");
76
77   // If this value is named, destroy the name.  This should not be in a symtab
78   // at this point.
79   if (Name)
80     Name->Destroy();
81
82   // There should be no uses of this object anymore, remove it.
83   LeakDetector::removeGarbageObject(this);
84 }
85
86 /// hasNUses - Return true if this Value has exactly N users.
87 ///
88 bool Value::hasNUses(unsigned N) const {
89   const_use_iterator UI = use_begin(), E = use_end();
90
91   for (; N; --N, ++UI)
92     if (UI == E) return false;  // Too few.
93   return UI == E;
94 }
95
96 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
97 /// logically equivalent to getNumUses() >= N.
98 ///
99 bool Value::hasNUsesOrMore(unsigned N) const {
100   const_use_iterator UI = use_begin(), E = use_end();
101
102   for (; N; --N, ++UI)
103     if (UI == E) return false;  // Too few.
104
105   return true;
106 }
107
108 /// isUsedInBasicBlock - Return true if this value is used in the specified
109 /// basic block.
110 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
111   for (const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
112     const Instruction *User = dyn_cast<Instruction>(*I);
113     if (User && User->getParent() == BB)
114       return true;
115   }
116   return false;
117 }
118
119
120 /// getNumUses - This method computes the number of uses of this Value.  This
121 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
122 /// values.
123 unsigned Value::getNumUses() const {
124   return (unsigned)std::distance(use_begin(), use_end());
125 }
126
127 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
128   ST = 0;
129   if (Instruction *I = dyn_cast<Instruction>(V)) {
130     if (BasicBlock *P = I->getParent())
131       if (Function *PP = P->getParent())
132         ST = &PP->getValueSymbolTable();
133   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
134     if (Function *P = BB->getParent())
135       ST = &P->getValueSymbolTable();
136   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
137     if (Module *P = GV->getParent())
138       ST = &P->getValueSymbolTable();
139   } else if (Argument *A = dyn_cast<Argument>(V)) {
140     if (Function *P = A->getParent())
141       ST = &P->getValueSymbolTable();
142   } else if (isa<MDString>(V))
143     return true;
144   else {
145     assert(isa<Constant>(V) && "Unknown value type!");
146     return true;  // no name is setable for this.
147   }
148   return false;
149 }
150
151 StringRef Value::getName() const {
152   // Make sure the empty string is still a C string. For historical reasons,
153   // some clients want to call .data() on the result and expect it to be null
154   // terminated.
155   if (!Name) return StringRef("", 0);
156   return Name->getKey();
157 }
158
159 std::string Value::getNameStr() const {
160   return getName().str();
161 }
162
163 void Value::setName(const Twine &NewName) {
164   // Fast path for common IRBuilder case of setName("") when there is no name.
165   if (NewName.isTriviallyEmpty() && !hasName())
166     return;
167
168   SmallString<256> NameData;
169   StringRef NameRef = NewName.toStringRef(NameData);
170
171   // Name isn't changing?
172   if (getName() == NameRef)
173     return;
174
175   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
176
177   // Get the symbol table to update for this object.
178   ValueSymbolTable *ST;
179   if (getSymTab(this, ST))
180     return;  // Cannot set a name on this value (e.g. constant).
181
182   if (!ST) { // No symbol table to update?  Just do the change.
183     if (NameRef.empty()) {
184       // Free the name for this value.
185       Name->Destroy();
186       Name = 0;
187       return;
188     }
189
190     if (Name)
191       Name->Destroy();
192
193     // NOTE: Could optimize for the case the name is shrinking to not deallocate
194     // then reallocated.
195
196     // Create the new name.
197     Name = ValueName::Create(NameRef.begin(), NameRef.end());
198     Name->setValue(this);
199     return;
200   }
201
202   // NOTE: Could optimize for the case the name is shrinking to not deallocate
203   // then reallocated.
204   if (hasName()) {
205     // Remove old name.
206     ST->removeValueName(Name);
207     Name->Destroy();
208     Name = 0;
209
210     if (NameRef.empty())
211       return;
212   }
213
214   // Name is changing to something new.
215   Name = ST->createValueName(NameRef, this);
216 }
217
218
219 /// takeName - transfer the name from V to this value, setting V's name to
220 /// empty.  It is an error to call V->takeName(V).
221 void Value::takeName(Value *V) {
222   ValueSymbolTable *ST = 0;
223   // If this value has a name, drop it.
224   if (hasName()) {
225     // Get the symtab this is in.
226     if (getSymTab(this, ST)) {
227       // We can't set a name on this value, but we need to clear V's name if
228       // it has one.
229       if (V->hasName()) V->setName("");
230       return;  // Cannot set a name on this value (e.g. constant).
231     }
232
233     // Remove old name.
234     if (ST)
235       ST->removeValueName(Name);
236     Name->Destroy();
237     Name = 0;
238   }
239
240   // Now we know that this has no name.
241
242   // If V has no name either, we're done.
243   if (!V->hasName()) return;
244
245   // Get this's symtab if we didn't before.
246   if (!ST) {
247     if (getSymTab(this, ST)) {
248       // Clear V's name.
249       V->setName("");
250       return;  // Cannot set a name on this value (e.g. constant).
251     }
252   }
253
254   // Get V's ST, this should always succed, because V has a name.
255   ValueSymbolTable *VST;
256   bool Failure = getSymTab(V, VST);
257   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
258
259   // If these values are both in the same symtab, we can do this very fast.
260   // This works even if both values have no symtab yet.
261   if (ST == VST) {
262     // Take the name!
263     Name = V->Name;
264     V->Name = 0;
265     Name->setValue(this);
266     return;
267   }
268
269   // Otherwise, things are slightly more complex.  Remove V's name from VST and
270   // then reinsert it into ST.
271
272   if (VST)
273     VST->removeValueName(V->Name);
274   Name = V->Name;
275   V->Name = 0;
276   Name->setValue(this);
277
278   if (ST)
279     ST->reinsertValue(this);
280 }
281
282
283 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
284 // except that it doesn't have all of the asserts.  The asserts fail because we
285 // are half-way done resolving types, which causes some types to exist as two
286 // different Type*'s at the same time.  This is a sledgehammer to work around
287 // this problem.
288 //
289 void Value::uncheckedReplaceAllUsesWith(Value *New) {
290   // Notify all ValueHandles (if present) that this value is going away.
291   if (HasValueHandle)
292     ValueHandleBase::ValueIsRAUWd(this, New);
293
294   while (!use_empty()) {
295     Use &U = *UseList;
296     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
297     // constant because they are uniqued.
298     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
299       if (!isa<GlobalValue>(C)) {
300         C->replaceUsesOfWithOnConstant(this, New, &U);
301         continue;
302       }
303     }
304
305     U.set(New);
306   }
307
308   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
309     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
310 }
311
312 void Value::replaceAllUsesWith(Value *New) {
313   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
314   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
315   assert(New->getType() == getType() &&
316          "replaceAllUses of value with new value of different type!");
317
318   uncheckedReplaceAllUsesWith(New);
319 }
320
321 Value *Value::stripPointerCasts() {
322   if (!getType()->isPointerTy())
323     return this;
324
325   // Even though we don't look through PHI nodes, we could be called on an
326   // instruction in an unreachable block, which may be on a cycle.
327   SmallPtrSet<Value *, 4> Visited;
328
329   Value *V = this;
330   Visited.insert(V);
331   do {
332     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
333       if (!GEP->hasAllZeroIndices())
334         return V;
335       V = GEP->getPointerOperand();
336     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
337       V = cast<Operator>(V)->getOperand(0);
338     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
339       if (GA->mayBeOverridden())
340         return V;
341       V = GA->getAliasee();
342     } else {
343       return V;
344     }
345     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
346   } while (Visited.insert(V));
347
348   return V;
349 }
350
351 /// isDereferenceablePointer - Test if this value is always a pointer to
352 /// allocated and suitably aligned memory for a simple load or store.
353 bool Value::isDereferenceablePointer() const {
354   // Note that it is not safe to speculate into a malloc'd region because
355   // malloc may return null.
356   // It's also not always safe to follow a bitcast, for example:
357   //   bitcast i8* (alloca i8) to i32*
358   // would result in a 4-byte load from a 1-byte alloca. Some cases could
359   // be handled using TargetData to check sizes and alignments though.
360
361   // These are obviously ok.
362   if (isa<AllocaInst>(this)) return true;
363
364   // Global variables which can't collapse to null are ok.
365   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
366     return !GV->hasExternalWeakLinkage();
367
368   // byval arguments are ok.
369   if (const Argument *A = dyn_cast<Argument>(this))
370     return A->hasByValAttr();
371   
372   // For GEPs, determine if the indexing lands within the allocated object.
373   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(this)) {
374     // Conservatively require that the base pointer be fully dereferenceable.
375     if (!GEP->getOperand(0)->isDereferenceablePointer())
376       return false;
377     // Check the indices.
378     gep_type_iterator GTI = gep_type_begin(GEP);
379     for (User::const_op_iterator I = GEP->op_begin()+1,
380          E = GEP->op_end(); I != E; ++I) {
381       Value *Index = *I;
382       const Type *Ty = *GTI++;
383       // Struct indices can't be out of bounds.
384       if (isa<StructType>(Ty))
385         continue;
386       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
387       if (!CI)
388         return false;
389       // Zero is always ok.
390       if (CI->isZero())
391         continue;
392       // Check to see that it's within the bounds of an array.
393       const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
394       if (!ATy)
395         return false;
396       if (CI->getValue().getActiveBits() > 64)
397         return false;
398       if (CI->getZExtValue() >= ATy->getNumElements())
399         return false;
400     }
401     // Indices check out; this is dereferenceable.
402     return true;
403   }
404
405   // If we don't know, assume the worst.
406   return false;
407 }
408
409 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
410 /// return the value in the PHI node corresponding to PredBB.  If not, return
411 /// ourself.  This is useful if you want to know the value something has in a
412 /// predecessor block.
413 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
414                                const BasicBlock *PredBB) {
415   PHINode *PN = dyn_cast<PHINode>(this);
416   if (PN && PN->getParent() == CurBB)
417     return PN->getIncomingValueForBlock(PredBB);
418   return this;
419 }
420
421 LLVMContext &Value::getContext() const { return VTy->getContext(); }
422
423 //===----------------------------------------------------------------------===//
424 //                             ValueHandleBase Class
425 //===----------------------------------------------------------------------===//
426
427 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
428 /// List is known to point into the existing use list.
429 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
430   assert(List && "Handle list is null?");
431
432   // Splice ourselves into the list.
433   Next = *List;
434   *List = this;
435   setPrevPtr(List);
436   if (Next) {
437     Next->setPrevPtr(&Next);
438     assert(VP == Next->VP && "Added to wrong list?");
439   }
440 }
441
442 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
443   assert(List && "Must insert after existing node");
444
445   Next = List->Next;
446   setPrevPtr(&List->Next);
447   List->Next = this;
448   if (Next)
449     Next->setPrevPtr(&Next);
450 }
451
452 /// AddToUseList - Add this ValueHandle to the use list for VP.
453 void ValueHandleBase::AddToUseList() {
454   assert(VP && "Null pointer doesn't have a use list!");
455
456   LLVMContextImpl *pImpl = VP->getContext().pImpl;
457
458   if (VP->HasValueHandle) {
459     // If this value already has a ValueHandle, then it must be in the
460     // ValueHandles map already.
461     ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
462     assert(Entry != 0 && "Value doesn't have any handles?");
463     AddToExistingUseList(&Entry);
464     return;
465   }
466
467   // Ok, it doesn't have any handles yet, so we must insert it into the
468   // DenseMap.  However, doing this insertion could cause the DenseMap to
469   // reallocate itself, which would invalidate all of the PrevP pointers that
470   // point into the old table.  Handle this by checking for reallocation and
471   // updating the stale pointers only if needed.
472   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
473   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
474
475   ValueHandleBase *&Entry = Handles[VP];
476   assert(Entry == 0 && "Value really did already have handles?");
477   AddToExistingUseList(&Entry);
478   VP->HasValueHandle = true;
479
480   // If reallocation didn't happen or if this was the first insertion, don't
481   // walk the table.
482   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
483       Handles.size() == 1) {
484     return;
485   }
486
487   // Okay, reallocation did happen.  Fix the Prev Pointers.
488   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
489        E = Handles.end(); I != E; ++I) {
490     assert(I->second && I->first == I->second->VP && "List invariant broken!");
491     I->second->setPrevPtr(&I->second);
492   }
493 }
494
495 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
496 void ValueHandleBase::RemoveFromUseList() {
497   assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
498
499   // Unlink this from its use list.
500   ValueHandleBase **PrevPtr = getPrevPtr();
501   assert(*PrevPtr == this && "List invariant broken");
502
503   *PrevPtr = Next;
504   if (Next) {
505     assert(Next->getPrevPtr() == &Next && "List invariant broken");
506     Next->setPrevPtr(PrevPtr);
507     return;
508   }
509
510   // If the Next pointer was null, then it is possible that this was the last
511   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
512   // map.
513   LLVMContextImpl *pImpl = VP->getContext().pImpl;
514   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
515   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
516     Handles.erase(VP);
517     VP->HasValueHandle = false;
518   }
519 }
520
521
522 void ValueHandleBase::ValueIsDeleted(Value *V) {
523   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
524
525   // Get the linked list base, which is guaranteed to exist since the
526   // HasValueHandle flag is set.
527   LLVMContextImpl *pImpl = V->getContext().pImpl;
528   ValueHandleBase *Entry = pImpl->ValueHandles[V];
529   assert(Entry && "Value bit set but no entries exist");
530
531   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
532   // and remove themselves from the list without breaking our iteration.  This
533   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
534   // Note that we deliberately do not the support the case when dropping a value
535   // handle results in a new value handle being permanently added to the list
536   // (as might occur in theory for CallbackVH's): the new value handle will not
537   // be processed and the checking code will mete out righteous punishment if
538   // the handle is still present once we have finished processing all the other
539   // value handles (it is fine to momentarily add then remove a value handle).
540   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
541     Iterator.RemoveFromUseList();
542     Iterator.AddToExistingUseListAfter(Entry);
543     assert(Entry->Next == &Iterator && "Loop invariant broken.");
544
545     switch (Entry->getKind()) {
546     case Assert:
547       break;
548     case Tracking:
549       // Mark that this value has been deleted by setting it to an invalid Value
550       // pointer.
551       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
552       break;
553     case Weak:
554       // Weak just goes to null, which will unlink it from the list.
555       Entry->operator=(0);
556       break;
557     case Callback:
558       // Forward to the subclass's implementation.
559       static_cast<CallbackVH*>(Entry)->deleted();
560       break;
561     }
562   }
563
564   // All callbacks, weak references, and assertingVHs should be dropped by now.
565   if (V->HasValueHandle) {
566 #ifndef NDEBUG      // Only in +Asserts mode...
567     dbgs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
568            << "\n";
569     if (pImpl->ValueHandles[V]->getKind() == Assert)
570       llvm_unreachable("An asserting value handle still pointed to this"
571                        " value!");
572
573 #endif
574     llvm_unreachable("All references to V were not removed?");
575   }
576 }
577
578
579 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
580   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
581   assert(Old != New && "Changing value into itself!");
582
583   // Get the linked list base, which is guaranteed to exist since the
584   // HasValueHandle flag is set.
585   LLVMContextImpl *pImpl = Old->getContext().pImpl;
586   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
587
588   assert(Entry && "Value bit set but no entries exist");
589
590   // We use a local ValueHandleBase as an iterator so that
591   // ValueHandles can add and remove themselves from the list without
592   // breaking our iteration.  This is not really an AssertingVH; we
593   // just have to give ValueHandleBase some kind.
594   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
595     Iterator.RemoveFromUseList();
596     Iterator.AddToExistingUseListAfter(Entry);
597     assert(Entry->Next == &Iterator && "Loop invariant broken.");
598
599     switch (Entry->getKind()) {
600     case Assert:
601       // Asserting handle does not follow RAUW implicitly.
602       break;
603     case Tracking:
604       // Tracking goes to new value like a WeakVH. Note that this may make it
605       // something incompatible with its templated type. We don't want to have a
606       // virtual (or inline) interface to handle this though, so instead we make
607       // the TrackingVH accessors guarantee that a client never sees this value.
608
609       // FALLTHROUGH
610     case Weak:
611       // Weak goes to the new value, which will unlink it from Old's list.
612       Entry->operator=(New);
613       break;
614     case Callback:
615       // Forward to the subclass's implementation.
616       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
617       break;
618     }
619   }
620
621 #ifndef NDEBUG
622   // If any new tracking or weak value handles were added while processing the
623   // list, then complain about it now.
624   if (Old->HasValueHandle)
625     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
626       switch (Entry->getKind()) {
627       case Tracking:
628       case Weak:
629         dbgs() << "After RAUW from " << *Old->getType() << " %"
630           << Old->getNameStr() << " to " << *New->getType() << " %"
631           << New->getNameStr() << "\n";
632         llvm_unreachable("A tracking or weak value handle still pointed to the"
633                          " old value!\n");
634       default:
635         break;
636       }
637 #endif
638 }
639
640 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
641 /// more than once.
642 CallbackVH::~CallbackVH() {}