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