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