487196cffce030e89690dfe532938414fbaabadc
[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/ErrorHandling.h"
26 #include "llvm/Support/LeakDetector.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/ValueHandle.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),
44     SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
45     UseList(0), Name(0) {
46   if (isa<CallInst>(this) || isa<InvokeInst>(this))
47     assert((VTy->isFirstClassType() || VTy->isVoidTy() ||
48             ty->isOpaqueTy() || VTy->isStructTy()) &&
49            "invalid CallInst  type!");
50   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
51     assert((VTy->isFirstClassType() || VTy->isVoidTy() ||
52             ty->isOpaqueTy()) &&
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!"); Failure=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
309 void Value::replaceAllUsesWith(Value *New) {
310   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
311   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
312   assert(New->getType() == getType() &&
313          "replaceAllUses of value with new value of different type!");
314
315   uncheckedReplaceAllUsesWith(New);
316 }
317
318 Value *Value::stripPointerCasts() {
319   if (!getType()->isPointerTy())
320     return this;
321
322   // Even though we don't look through PHI nodes, we could be called on an
323   // instruction in an unreachable block, which may be on a cycle.
324   SmallPtrSet<Value *, 4> Visited;
325
326   Value *V = this;
327   Visited.insert(V);
328   do {
329     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
330       if (!GEP->hasAllZeroIndices())
331         return V;
332       V = GEP->getPointerOperand();
333     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
334       V = cast<Operator>(V)->getOperand(0);
335     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
336       if (GA->mayBeOverridden())
337         return V;
338       V = GA->getAliasee();
339     } else {
340       return V;
341     }
342     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
343   } while (Visited.insert(V));
344
345   return V;
346 }
347
348 Value *Value::getUnderlyingObject(unsigned MaxLookup) {
349   if (!getType()->isPointerTy())
350     return this;
351   Value *V = this;
352   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
353     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
354       V = GEP->getPointerOperand();
355     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
356       V = cast<Operator>(V)->getOperand(0);
357     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
358       if (GA->mayBeOverridden())
359         return V;
360       V = GA->getAliasee();
361     } else {
362       return V;
363     }
364     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
365   }
366   return V;
367 }
368
369 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
370 /// return the value in the PHI node corresponding to PredBB.  If not, return
371 /// ourself.  This is useful if you want to know the value something has in a
372 /// predecessor block.
373 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
374                                const BasicBlock *PredBB) {
375   PHINode *PN = dyn_cast<PHINode>(this);
376   if (PN && PN->getParent() == CurBB)
377     return PN->getIncomingValueForBlock(PredBB);
378   return this;
379 }
380
381 LLVMContext &Value::getContext() const { return VTy->getContext(); }
382
383 //===----------------------------------------------------------------------===//
384 //                             ValueHandleBase Class
385 //===----------------------------------------------------------------------===//
386
387 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
388 /// List is known to point into the existing use list.
389 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
390   assert(List && "Handle list is null?");
391
392   // Splice ourselves into the list.
393   Next = *List;
394   *List = this;
395   setPrevPtr(List);
396   if (Next) {
397     Next->setPrevPtr(&Next);
398     assert(VP == Next->VP && "Added to wrong list?");
399   }
400 }
401
402 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
403   assert(List && "Must insert after existing node");
404
405   Next = List->Next;
406   setPrevPtr(&List->Next);
407   List->Next = this;
408   if (Next)
409     Next->setPrevPtr(&Next);
410 }
411
412 /// AddToUseList - Add this ValueHandle to the use list for VP.
413 void ValueHandleBase::AddToUseList() {
414   assert(VP && "Null pointer doesn't have a use list!");
415
416   LLVMContextImpl *pImpl = VP->getContext().pImpl;
417
418   if (VP->HasValueHandle) {
419     // If this value already has a ValueHandle, then it must be in the
420     // ValueHandles map already.
421     ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
422     assert(Entry != 0 && "Value doesn't have any handles?");
423     AddToExistingUseList(&Entry);
424     return;
425   }
426
427   // Ok, it doesn't have any handles yet, so we must insert it into the
428   // DenseMap.  However, doing this insertion could cause the DenseMap to
429   // reallocate itself, which would invalidate all of the PrevP pointers that
430   // point into the old table.  Handle this by checking for reallocation and
431   // updating the stale pointers only if needed.
432   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
433   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
434
435   ValueHandleBase *&Entry = Handles[VP];
436   assert(Entry == 0 && "Value really did already have handles?");
437   AddToExistingUseList(&Entry);
438   VP->HasValueHandle = true;
439
440   // If reallocation didn't happen or if this was the first insertion, don't
441   // walk the table.
442   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
443       Handles.size() == 1) {
444     return;
445   }
446
447   // Okay, reallocation did happen.  Fix the Prev Pointers.
448   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
449        E = Handles.end(); I != E; ++I) {
450     assert(I->second && I->first == I->second->VP && "List invariant broken!");
451     I->second->setPrevPtr(&I->second);
452   }
453 }
454
455 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
456 void ValueHandleBase::RemoveFromUseList() {
457   assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
458
459   // Unlink this from its use list.
460   ValueHandleBase **PrevPtr = getPrevPtr();
461   assert(*PrevPtr == this && "List invariant broken");
462
463   *PrevPtr = Next;
464   if (Next) {
465     assert(Next->getPrevPtr() == &Next && "List invariant broken");
466     Next->setPrevPtr(PrevPtr);
467     return;
468   }
469
470   // If the Next pointer was null, then it is possible that this was the last
471   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
472   // map.
473   LLVMContextImpl *pImpl = VP->getContext().pImpl;
474   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
475   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
476     Handles.erase(VP);
477     VP->HasValueHandle = false;
478   }
479 }
480
481
482 void ValueHandleBase::ValueIsDeleted(Value *V) {
483   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
484
485   // Get the linked list base, which is guaranteed to exist since the
486   // HasValueHandle flag is set.
487   LLVMContextImpl *pImpl = V->getContext().pImpl;
488   ValueHandleBase *Entry = pImpl->ValueHandles[V];
489   assert(Entry && "Value bit set but no entries exist");
490
491   // We use a local ValueHandleBase as an iterator so that
492   // ValueHandles can add and remove themselves from the list without
493   // breaking our iteration.  This is not really an AssertingVH; we
494   // just have to give ValueHandleBase some kind.
495   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
496     Iterator.RemoveFromUseList();
497     Iterator.AddToExistingUseListAfter(Entry);
498     assert(Entry->Next == &Iterator && "Loop invariant broken.");
499
500     switch (Entry->getKind()) {
501     case Assert:
502       break;
503     case Tracking:
504       // Mark that this value has been deleted by setting it to an invalid Value
505       // pointer.
506       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
507       break;
508     case Weak:
509       // Weak just goes to null, which will unlink it from the list.
510       Entry->operator=(0);
511       break;
512     case Callback:
513       // Forward to the subclass's implementation.
514       static_cast<CallbackVH*>(Entry)->deleted();
515       break;
516     }
517   }
518
519   // All callbacks, weak references, and assertingVHs should be dropped by now.
520   if (V->HasValueHandle) {
521 #ifndef NDEBUG      // Only in +Asserts mode...
522     dbgs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
523            << "\n";
524     if (pImpl->ValueHandles[V]->getKind() == Assert)
525       llvm_unreachable("An asserting value handle still pointed to this"
526                        " value!");
527
528 #endif
529     llvm_unreachable("All references to V were not removed?");
530   }
531 }
532
533
534 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
535   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
536   assert(Old != New && "Changing value into itself!");
537
538   // Get the linked list base, which is guaranteed to exist since the
539   // HasValueHandle flag is set.
540   LLVMContextImpl *pImpl = Old->getContext().pImpl;
541   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
542
543   assert(Entry && "Value bit set but no entries exist");
544
545   // We use a local ValueHandleBase as an iterator so that
546   // ValueHandles can add and remove themselves from the list without
547   // breaking our iteration.  This is not really an AssertingVH; we
548   // just have to give ValueHandleBase some kind.
549   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
550     Iterator.RemoveFromUseList();
551     Iterator.AddToExistingUseListAfter(Entry);
552     assert(Entry->Next == &Iterator && "Loop invariant broken.");
553
554     switch (Entry->getKind()) {
555     case Assert:
556       // Asserting handle does not follow RAUW implicitly.
557       break;
558     case Tracking:
559       // Tracking goes to new value like a WeakVH. Note that this may make it
560       // something incompatible with its templated type. We don't want to have a
561       // virtual (or inline) interface to handle this though, so instead we make
562       // the TrackingVH accessors guarantee that a client never sees this value.
563
564       // FALLTHROUGH
565     case Weak:
566       // Weak goes to the new value, which will unlink it from Old's list.
567       Entry->operator=(New);
568       break;
569     case Callback:
570       // Forward to the subclass's implementation.
571       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
572       break;
573     }
574   }
575 }
576
577 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
578 /// more than once.
579 CallbackVH::~CallbackVH() {}
580
581
582 //===----------------------------------------------------------------------===//
583 //                                 User Class
584 //===----------------------------------------------------------------------===//
585
586 // replaceUsesOfWith - Replaces all references to the "From" definition with
587 // references to the "To" definition.
588 //
589 void User::replaceUsesOfWith(Value *From, Value *To) {
590   if (From == To) return;   // Duh what?
591
592   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
593          "Cannot call User::replaceUsesOfWith on a constant!");
594
595   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
596     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
597       // The side effects of this setOperand call include linking to
598       // "To", adding "this" to the uses list of To, and
599       // most importantly, removing "this" from the use list of "From".
600       setOperand(i, To); // Fix it now...
601     }
602 }