add a method for comparing to see if a value has a specified name.
[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 and User classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constant.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/InstrTypes.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/ValueSymbolTable.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include <algorithm>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 //                                Value Class
27 //===----------------------------------------------------------------------===//
28
29 static inline const Type *checkType(const Type *Ty) {
30   assert(Ty && "Value defined with a null type: Error!");
31   return Ty;
32 }
33
34 Value::Value(const Type *ty, unsigned scid)
35   : SubclassID(scid), SubclassData(0), Ty(checkType(ty)),
36     UseList(0), Name(0) {
37   if (isa<CallInst>(this) || isa<InvokeInst>(this))
38     assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
39             isa<OpaqueType>(ty) || Ty->getTypeID() == Type::StructTyID) &&
40            "invalid CallInst  type!");
41   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
42     assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
43            isa<OpaqueType>(ty)) &&
44            "Cannot create non-first-class values except for constants!");
45 }
46
47 Value::~Value() {
48 #ifndef NDEBUG      // Only in -g mode...
49   // Check to make sure that there are no uses of this value that are still
50   // around when the value is destroyed.  If there are, then we have a dangling
51   // reference and something is wrong.  This code is here to print out what is
52   // still being referenced.  The value in question should be printed as
53   // a <badref>
54   //
55   if (!use_empty()) {
56     DOUT << "While deleting: " << *Ty << " %" << getNameStr() << "\n";
57     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
58       DOUT << "Use still stuck around after Def is destroyed:"
59            << **I << "\n";
60   }
61 #endif
62   assert(use_empty() && "Uses remain when a value is destroyed!");
63
64   // If this value is named, destroy the name.  This should not be in a symtab
65   // at this point.
66   if (Name)
67     Name->Destroy();
68   
69   // There should be no uses of this object anymore, remove it.
70   LeakDetector::removeGarbageObject(this);
71 }
72
73 /// hasNUses - Return true if this Value has exactly N users.
74 ///
75 bool Value::hasNUses(unsigned N) const {
76   use_const_iterator UI = use_begin(), E = use_end();
77
78   for (; N; --N, ++UI)
79     if (UI == E) return false;  // Too few.
80   return UI == E;
81 }
82
83 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
84 /// logically equivalent to getNumUses() >= N.
85 ///
86 bool Value::hasNUsesOrMore(unsigned N) const {
87   use_const_iterator UI = use_begin(), E = use_end();
88
89   for (; N; --N, ++UI)
90     if (UI == E) return false;  // Too few.
91
92   return true;
93 }
94
95
96 /// getNumUses - This method computes the number of uses of this Value.  This
97 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
98 /// values.
99 unsigned Value::getNumUses() const {
100   return (unsigned)std::distance(use_begin(), use_end());
101 }
102
103 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
104   ST = 0;
105   if (Instruction *I = dyn_cast<Instruction>(V)) {
106     if (BasicBlock *P = I->getParent())
107       if (Function *PP = P->getParent())
108         ST = &PP->getValueSymbolTable();
109   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
110     if (Function *P = BB->getParent()) 
111       ST = &P->getValueSymbolTable();
112   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
113     if (Module *P = GV->getParent()) 
114       ST = &P->getValueSymbolTable();
115   } else if (Argument *A = dyn_cast<Argument>(V)) {
116     if (Function *P = A->getParent()) 
117       ST = &P->getValueSymbolTable();
118   } else {
119     assert(isa<Constant>(V) && "Unknown value type!");
120     return true;  // no name is setable for this.
121   }
122   return false;
123 }
124
125 /// getNameStart - Return a pointer to a null terminated string for this name.
126 /// Note that names can have null characters within the string as well as at
127 /// their end.  This always returns a non-null pointer.
128 const char *Value::getNameStart() const {
129   if (Name == 0) return "";
130   return Name->getKeyData();
131 }
132
133 /// getNameLen - Return the length of the string, correctly handling nul
134 /// characters embedded into them.
135 unsigned Value::getNameLen() const {
136   return Name ? Name->getKeyLength() : 0;
137 }
138
139 /// isName - Return true if this value has the name specified by the provided
140 /// nul terminated string.
141 bool Value::isName(const char *N) const {
142   unsigned InLen = strlen(N);
143   return InLen = getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
144 }
145
146
147 std::string Value::getNameStr() const {
148   if (Name == 0) return "";
149   return std::string(Name->getKeyData(),
150                      Name->getKeyData()+Name->getKeyLength());
151 }
152
153 void Value::setName(const std::string &name) {
154   setName(&name[0], name.size());
155 }
156
157 void Value::setName(const char *Name) {
158   setName(Name, Name ? strlen(Name) : 0);
159 }
160
161 void Value::setName(const char *NameStr, unsigned NameLen) {
162   if (NameLen == 0 && !hasName()) return;
163   assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
164   
165   // Get the symbol table to update for this object.
166   ValueSymbolTable *ST;
167   if (getSymTab(this, ST))
168     return;  // Cannot set a name on this value (e.g. constant).
169
170   if (!ST) { // No symbol table to update?  Just do the change.
171     if (NameLen == 0) {
172       // Free the name for this value.
173       Name->Destroy();
174       Name = 0;
175       return;
176     }
177     
178     if (Name) {
179       // Name isn't changing?
180       if (NameLen == Name->getKeyLength() &&
181           !memcmp(Name->getKeyData(), NameStr, NameLen))
182         return;
183       Name->Destroy();
184     }
185     
186     // NOTE: Could optimize for the case the name is shrinking to not deallocate
187     // then reallocated.
188       
189     // Create the new name.
190     Name = ValueName::Create(NameStr, NameStr+NameLen);
191     Name->setValue(this);
192     return;
193   }
194   
195   // NOTE: Could optimize for the case the name is shrinking to not deallocate
196   // then reallocated.
197   if (hasName()) {
198     // Name isn't changing?
199     if (NameLen == Name->getKeyLength() &&
200         !memcmp(Name->getKeyData(), NameStr, NameLen))
201       return;
202
203     // Remove old name.
204     ST->removeValueName(Name);
205     Name->Destroy();
206     Name = 0;
207
208     if (NameLen == 0)
209       return;
210   }
211
212   // Name is changing to something new.
213   Name = ST->createValueName(NameStr, NameLen, this);
214 }
215
216
217 /// takeName - transfer the name from V to this value, setting V's name to
218 /// empty.  It is an error to call V->takeName(V). 
219 void Value::takeName(Value *V) {
220   ValueSymbolTable *ST = 0;
221   // If this value has a name, drop it.
222   if (hasName()) {
223     // Get the symtab this is in.
224     if (getSymTab(this, ST)) {
225       // We can't set a name on this value, but we need to clear V's name if
226       // it has one.
227       if (V->hasName()) V->setName(0, 0);
228       return;  // Cannot set a name on this value (e.g. constant).
229     }
230     
231     // Remove old name.
232     if (ST)
233       ST->removeValueName(Name);
234     Name->Destroy();
235     Name = 0;
236   } 
237   
238   // Now we know that this has no name.
239   
240   // If V has no name either, we're done.
241   if (!V->hasName()) return;
242    
243   // Get this's symtab if we didn't before.
244   if (!ST) {
245     if (getSymTab(this, ST)) {
246       // Clear V's name.
247       V->setName(0, 0);
248       return;  // Cannot set a name on this value (e.g. constant).
249     }
250   }
251   
252   // Get V's ST, this should always succed, because V has a name.
253   ValueSymbolTable *VST;
254   bool Failure = getSymTab(V, VST);
255   assert(!Failure && "V has a name, so it should have a ST!");
256   
257   // If these values are both in the same symtab, we can do this very fast.
258   // This works even if both values have no symtab yet.
259   if (ST == VST) {
260     // Take the name!
261     Name = V->Name;
262     V->Name = 0;
263     Name->setValue(this);
264     return;
265   }
266   
267   // Otherwise, things are slightly more complex.  Remove V's name from VST and
268   // then reinsert it into ST.
269   
270   if (VST)
271     VST->removeValueName(V->Name);
272   Name = V->Name;
273   V->Name = 0;
274   Name->setValue(this);
275   
276   if (ST)
277     ST->reinsertValue(this);
278 }
279
280
281 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
282 // except that it doesn't have all of the asserts.  The asserts fail because we
283 // are half-way done resolving types, which causes some types to exist as two
284 // different Type*'s at the same time.  This is a sledgehammer to work around
285 // this problem.
286 //
287 void Value::uncheckedReplaceAllUsesWith(Value *New) {
288   while (!use_empty()) {
289     Use &U = *UseList;
290     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
291     // constant because they are uniqued.
292     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
293       if (!isa<GlobalValue>(C)) {
294         C->replaceUsesOfWithOnConstant(this, New, &U);
295         continue;
296       }
297     }
298     
299     U.set(New);
300   }
301 }
302
303 void Value::replaceAllUsesWith(Value *New) {
304   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
305   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
306   assert(New->getType() == getType() &&
307          "replaceAllUses of value with new value of different type!");
308
309   uncheckedReplaceAllUsesWith(New);
310 }
311
312 //===----------------------------------------------------------------------===//
313 //                                 User Class
314 //===----------------------------------------------------------------------===//
315
316 // replaceUsesOfWith - Replaces all references to the "From" definition with
317 // references to the "To" definition.
318 //
319 void User::replaceUsesOfWith(Value *From, Value *To) {
320   if (From == To) return;   // Duh what?
321
322   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
323          "Cannot call User::replaceUsesofWith on a constant!");
324
325   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
326     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
327       // The side effects of this setOperand call include linking to
328       // "To", adding "this" to the uses list of To, and
329       // most importantly, removing "this" from the use list of "From".
330       setOperand(i, To); // Fix it now...
331     }
332 }
333