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