Add support for vectors of pointers.
[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(Type *Ty) {
39   assert(Ty && "Value defined with a null type: Error!");
40   return const_cast<Type*>(Ty);
41 }
42
43 Value::Value(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 << " %" << getName() << "\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 void Value::setName(const Twine &NewName) {
160   // Fast path for common IRBuilder case of setName("") when there is no name.
161   if (NewName.isTriviallyEmpty() && !hasName())
162     return;
163
164   SmallString<256> NameData;
165   StringRef NameRef = NewName.toStringRef(NameData);
166
167   // Name isn't changing?
168   if (getName() == NameRef)
169     return;
170
171   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
172
173   // Get the symbol table to update for this object.
174   ValueSymbolTable *ST;
175   if (getSymTab(this, ST))
176     return;  // Cannot set a name on this value (e.g. constant).
177
178   if (!ST) { // No symbol table to update?  Just do the change.
179     if (NameRef.empty()) {
180       // Free the name for this value.
181       Name->Destroy();
182       Name = 0;
183       return;
184     }
185
186     if (Name)
187       Name->Destroy();
188
189     // NOTE: Could optimize for the case the name is shrinking to not deallocate
190     // then reallocated.
191
192     // Create the new name.
193     Name = ValueName::Create(NameRef.begin(), NameRef.end());
194     Name->setValue(this);
195     return;
196   }
197
198   // NOTE: Could optimize for the case the name is shrinking to not deallocate
199   // then reallocated.
200   if (hasName()) {
201     // Remove old name.
202     ST->removeValueName(Name);
203     Name->Destroy();
204     Name = 0;
205
206     if (NameRef.empty())
207       return;
208   }
209
210   // Name is changing to something new.
211   Name = ST->createValueName(NameRef, this);
212 }
213
214
215 /// takeName - transfer the name from V to this value, setting V's name to
216 /// empty.  It is an error to call V->takeName(V).
217 void Value::takeName(Value *V) {
218   ValueSymbolTable *ST = 0;
219   // If this value has a name, drop it.
220   if (hasName()) {
221     // Get the symtab this is in.
222     if (getSymTab(this, ST)) {
223       // We can't set a name on this value, but we need to clear V's name if
224       // it has one.
225       if (V->hasName()) V->setName("");
226       return;  // Cannot set a name on this value (e.g. constant).
227     }
228
229     // Remove old name.
230     if (ST)
231       ST->removeValueName(Name);
232     Name->Destroy();
233     Name = 0;
234   }
235
236   // Now we know that this has no name.
237
238   // If V has no name either, we're done.
239   if (!V->hasName()) return;
240
241   // Get this's symtab if we didn't before.
242   if (!ST) {
243     if (getSymTab(this, ST)) {
244       // Clear V's name.
245       V->setName("");
246       return;  // Cannot set a name on this value (e.g. constant).
247     }
248   }
249
250   // Get V's ST, this should always succed, because V has a name.
251   ValueSymbolTable *VST;
252   bool Failure = getSymTab(V, VST);
253   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
254
255   // If these values are both in the same symtab, we can do this very fast.
256   // This works even if both values have no symtab yet.
257   if (ST == VST) {
258     // Take the name!
259     Name = V->Name;
260     V->Name = 0;
261     Name->setValue(this);
262     return;
263   }
264
265   // Otherwise, things are slightly more complex.  Remove V's name from VST and
266   // then reinsert it into ST.
267
268   if (VST)
269     VST->removeValueName(V->Name);
270   Name = V->Name;
271   V->Name = 0;
272   Name->setValue(this);
273
274   if (ST)
275     ST->reinsertValue(this);
276 }
277
278
279 void Value::replaceAllUsesWith(Value *New) {
280   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
281   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
282   assert(New->getType() == getType() &&
283          "replaceAllUses of value with new value of different type!");
284
285   // Notify all ValueHandles (if present) that this value is going away.
286   if (HasValueHandle)
287     ValueHandleBase::ValueIsRAUWd(this, New);
288   
289   while (!use_empty()) {
290     Use &U = *UseList;
291     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
292     // constant because they are uniqued.
293     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
294       if (!isa<GlobalValue>(C)) {
295         C->replaceUsesOfWithOnConstant(this, New, &U);
296         continue;
297       }
298     }
299     
300     U.set(New);
301   }
302   
303   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
304     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
305 }
306
307 Value *Value::stripPointerCasts() {
308   if (!getType()->isPointerTy())
309     return this;
310
311   // Even though we don't look through PHI nodes, we could be called on an
312   // instruction in an unreachable block, which may be on a cycle.
313   SmallPtrSet<Value *, 4> Visited;
314
315   Value *V = this;
316   Visited.insert(V);
317   do {
318     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
319       if (!GEP->hasAllZeroIndices())
320         return V;
321       V = GEP->getPointerOperand();
322     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
323       V = cast<Operator>(V)->getOperand(0);
324     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
325       if (GA->mayBeOverridden())
326         return V;
327       V = GA->getAliasee();
328     } else {
329       return V;
330     }
331     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
332   } while (Visited.insert(V));
333
334   return V;
335 }
336
337 /// isDereferenceablePointer - Test if this value is always a pointer to
338 /// allocated and suitably aligned memory for a simple load or store.
339 bool Value::isDereferenceablePointer() const {
340   // Note that it is not safe to speculate into a malloc'd region because
341   // malloc may return null.
342   // It's also not always safe to follow a bitcast, for example:
343   //   bitcast i8* (alloca i8) to i32*
344   // would result in a 4-byte load from a 1-byte alloca. Some cases could
345   // be handled using TargetData to check sizes and alignments though.
346
347   // These are obviously ok.
348   if (isa<AllocaInst>(this)) return true;
349
350   // Global variables which can't collapse to null are ok.
351   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
352     return !GV->hasExternalWeakLinkage();
353
354   // byval arguments are ok.
355   if (const Argument *A = dyn_cast<Argument>(this))
356     return A->hasByValAttr();
357   
358   // For GEPs, determine if the indexing lands within the allocated object.
359   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(this)) {
360     // Conservatively require that the base pointer be fully dereferenceable.
361     if (!GEP->getOperand(0)->isDereferenceablePointer())
362       return false;
363     // Check the indices.
364     gep_type_iterator GTI = gep_type_begin(GEP);
365     for (User::const_op_iterator I = GEP->op_begin()+1,
366          E = GEP->op_end(); I != E; ++I) {
367       Value *Index = *I;
368       Type *Ty = *GTI++;
369       // Struct indices can't be out of bounds.
370       if (isa<StructType>(Ty))
371         continue;
372       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
373       if (!CI)
374         return false;
375       // Zero is always ok.
376       if (CI->isZero())
377         continue;
378       // Check to see that it's within the bounds of an array.
379       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
380       if (!ATy)
381         return false;
382       if (CI->getValue().getActiveBits() > 64)
383         return false;
384       if (CI->getZExtValue() >= ATy->getNumElements())
385         return false;
386     }
387     // Indices check out; this is dereferenceable.
388     return true;
389   }
390
391   // If we don't know, assume the worst.
392   return false;
393 }
394
395 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
396 /// return the value in the PHI node corresponding to PredBB.  If not, return
397 /// ourself.  This is useful if you want to know the value something has in a
398 /// predecessor block.
399 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
400                                const BasicBlock *PredBB) {
401   PHINode *PN = dyn_cast<PHINode>(this);
402   if (PN && PN->getParent() == CurBB)
403     return PN->getIncomingValueForBlock(PredBB);
404   return this;
405 }
406
407 LLVMContext &Value::getContext() const { return VTy->getContext(); }
408
409 //===----------------------------------------------------------------------===//
410 //                             ValueHandleBase Class
411 //===----------------------------------------------------------------------===//
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 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
429   assert(List && "Must insert after existing node");
430
431   Next = List->Next;
432   setPrevPtr(&List->Next);
433   List->Next = this;
434   if (Next)
435     Next->setPrevPtr(&Next);
436 }
437
438 /// AddToUseList - Add this ValueHandle to the use list for VP.
439 void ValueHandleBase::AddToUseList() {
440   assert(VP && "Null pointer doesn't have a use list!");
441
442   LLVMContextImpl *pImpl = VP->getContext().pImpl;
443
444   if (VP->HasValueHandle) {
445     // If this value already has a ValueHandle, then it must be in the
446     // ValueHandles map already.
447     ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
448     assert(Entry != 0 && "Value doesn't have any handles?");
449     AddToExistingUseList(&Entry);
450     return;
451   }
452
453   // Ok, it doesn't have any handles yet, so we must insert it into the
454   // DenseMap.  However, doing this insertion could cause the DenseMap to
455   // reallocate itself, which would invalidate all of the PrevP pointers that
456   // point into the old table.  Handle this by checking for reallocation and
457   // updating the stale pointers only if needed.
458   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
459   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
460
461   ValueHandleBase *&Entry = Handles[VP];
462   assert(Entry == 0 && "Value really did already have handles?");
463   AddToExistingUseList(&Entry);
464   VP->HasValueHandle = true;
465
466   // If reallocation didn't happen or if this was the first insertion, don't
467   // walk the table.
468   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
469       Handles.size() == 1) {
470     return;
471   }
472
473   // Okay, reallocation did happen.  Fix the Prev Pointers.
474   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
475        E = Handles.end(); I != E; ++I) {
476     assert(I->second && I->first == I->second->VP && "List invariant broken!");
477     I->second->setPrevPtr(&I->second);
478   }
479 }
480
481 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
482 void ValueHandleBase::RemoveFromUseList() {
483   assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
484
485   // Unlink this from its use list.
486   ValueHandleBase **PrevPtr = getPrevPtr();
487   assert(*PrevPtr == this && "List invariant broken");
488
489   *PrevPtr = Next;
490   if (Next) {
491     assert(Next->getPrevPtr() == &Next && "List invariant broken");
492     Next->setPrevPtr(PrevPtr);
493     return;
494   }
495
496   // If the Next pointer was null, then it is possible that this was the last
497   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
498   // map.
499   LLVMContextImpl *pImpl = VP->getContext().pImpl;
500   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
501   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
502     Handles.erase(VP);
503     VP->HasValueHandle = false;
504   }
505 }
506
507
508 void ValueHandleBase::ValueIsDeleted(Value *V) {
509   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
510
511   // Get the linked list base, which is guaranteed to exist since the
512   // HasValueHandle flag is set.
513   LLVMContextImpl *pImpl = V->getContext().pImpl;
514   ValueHandleBase *Entry = pImpl->ValueHandles[V];
515   assert(Entry && "Value bit set but no entries exist");
516
517   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
518   // and remove themselves from the list without breaking our iteration.  This
519   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
520   // Note that we deliberately do not the support the case when dropping a value
521   // handle results in a new value handle being permanently added to the list
522   // (as might occur in theory for CallbackVH's): the new value handle will not
523   // be processed and the checking code will mete out righteous punishment if
524   // the handle is still present once we have finished processing all the other
525   // value handles (it is fine to momentarily add then remove a value handle).
526   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
527     Iterator.RemoveFromUseList();
528     Iterator.AddToExistingUseListAfter(Entry);
529     assert(Entry->Next == &Iterator && "Loop invariant broken.");
530
531     switch (Entry->getKind()) {
532     case Assert:
533       break;
534     case Tracking:
535       // Mark that this value has been deleted by setting it to an invalid Value
536       // pointer.
537       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
538       break;
539     case Weak:
540       // Weak just goes to null, which will unlink it from the list.
541       Entry->operator=(0);
542       break;
543     case Callback:
544       // Forward to the subclass's implementation.
545       static_cast<CallbackVH*>(Entry)->deleted();
546       break;
547     }
548   }
549
550   // All callbacks, weak references, and assertingVHs should be dropped by now.
551   if (V->HasValueHandle) {
552 #ifndef NDEBUG      // Only in +Asserts mode...
553     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
554            << "\n";
555     if (pImpl->ValueHandles[V]->getKind() == Assert)
556       llvm_unreachable("An asserting value handle still pointed to this"
557                        " value!");
558
559 #endif
560     llvm_unreachable("All references to V were not removed?");
561   }
562 }
563
564
565 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
566   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
567   assert(Old != New && "Changing value into itself!");
568
569   // Get the linked list base, which is guaranteed to exist since the
570   // HasValueHandle flag is set.
571   LLVMContextImpl *pImpl = Old->getContext().pImpl;
572   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
573
574   assert(Entry && "Value bit set but no entries exist");
575
576   // We use a local ValueHandleBase as an iterator so that
577   // ValueHandles can add and remove themselves from the list without
578   // breaking our iteration.  This is not really an AssertingVH; we
579   // just have to give ValueHandleBase some kind.
580   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
581     Iterator.RemoveFromUseList();
582     Iterator.AddToExistingUseListAfter(Entry);
583     assert(Entry->Next == &Iterator && "Loop invariant broken.");
584
585     switch (Entry->getKind()) {
586     case Assert:
587       // Asserting handle does not follow RAUW implicitly.
588       break;
589     case Tracking:
590       // Tracking goes to new value like a WeakVH. Note that this may make it
591       // something incompatible with its templated type. We don't want to have a
592       // virtual (or inline) interface to handle this though, so instead we make
593       // the TrackingVH accessors guarantee that a client never sees this value.
594
595       // FALLTHROUGH
596     case Weak:
597       // Weak goes to the new value, which will unlink it from Old's list.
598       Entry->operator=(New);
599       break;
600     case Callback:
601       // Forward to the subclass's implementation.
602       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
603       break;
604     }
605   }
606
607 #ifndef NDEBUG
608   // If any new tracking or weak value handles were added while processing the
609   // list, then complain about it now.
610   if (Old->HasValueHandle)
611     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
612       switch (Entry->getKind()) {
613       case Tracking:
614       case Weak:
615         dbgs() << "After RAUW from " << *Old->getType() << " %"
616                << Old->getName() << " to " << *New->getType() << " %"
617                << New->getName() << "\n";
618         llvm_unreachable("A tracking or weak value handle still pointed to the"
619                          " old value!\n");
620       default:
621         break;
622       }
623 #endif
624 }
625
626 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
627 /// more than once.
628 CallbackVH::~CallbackVH() {}