Remove attribution from file headers, per discussion on llvmdev.
[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/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_empty()) {
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_empty() && "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 /// getNameStart - Return a pointer to a null terminated string for this name.
121 /// Note that names can have null characters within the string as well as at
122 /// their end.  This always returns a non-null pointer.
123 const char *Value::getNameStart() const {
124   if (Name == 0) return "";
125   return Name->getKeyData();
126 }
127
128 /// getNameLen - Return the length of the string, correctly handling nul
129 /// characters embedded into them.
130 unsigned Value::getNameLen() const {
131   return Name ? Name->getKeyLength() : 0;
132 }
133
134
135 std::string Value::getNameStr() const {
136   if (Name == 0) return "";
137   return std::string(Name->getKeyData(),
138                      Name->getKeyData()+Name->getKeyLength());
139 }
140
141 void Value::setName(const std::string &name) {
142   setName(&name[0], name.size());
143 }
144
145 void Value::setName(const char *Name) {
146   setName(Name, Name ? strlen(Name) : 0);
147 }
148
149 void Value::setName(const char *NameStr, unsigned NameLen) {
150   if (NameLen == 0 && !hasName()) return;
151   assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
152   
153   // Get the symbol table to update for this object.
154   ValueSymbolTable *ST;
155   if (getSymTab(this, ST))
156     return;  // Cannot set a name on this value (e.g. constant).
157
158   if (!ST) { // No symbol table to update?  Just do the change.
159     if (NameLen == 0) {
160       // Free the name for this value.
161       Name->Destroy();
162       Name = 0;
163       return;
164     }
165     
166     if (Name) {
167       // Name isn't changing?
168       if (NameLen == Name->getKeyLength() &&
169           !memcmp(Name->getKeyData(), NameStr, NameLen))
170         return;
171       Name->Destroy();
172     }
173     
174     // NOTE: Could optimize for the case the name is shrinking to not deallocate
175     // then reallocated.
176       
177     // Create the new name.
178     Name = ValueName::Create(NameStr, NameStr+NameLen);
179     Name->setValue(this);
180     return;
181   }
182   
183   // NOTE: Could optimize for the case the name is shrinking to not deallocate
184   // then reallocated.
185   if (hasName()) {
186     // Name isn't changing?
187     if (NameLen == Name->getKeyLength() &&
188         !memcmp(Name->getKeyData(), NameStr, NameLen))
189       return;
190
191     // Remove old name.
192     ST->removeValueName(Name);
193     Name->Destroy();
194     Name = 0;
195
196     if (NameLen == 0)
197       return;
198   }
199
200   // Name is changing to something new.
201   Name = ST->createValueName(NameStr, NameLen, this);
202 }
203
204
205 /// takeName - transfer the name from V to this value, setting V's name to
206 /// empty.  It is an error to call V->takeName(V). 
207 void Value::takeName(Value *V) {
208   ValueSymbolTable *ST = 0;
209   // If this value has a name, drop it.
210   if (hasName()) {
211     // Get the symtab this is in.
212     if (getSymTab(this, ST)) {
213       // We can't set a name on this value, but we need to clear V's name if
214       // it has one.
215       if (V->hasName()) V->setName(0, 0);
216       return;  // Cannot set a name on this value (e.g. constant).
217     }
218     
219     // Remove old name.
220     if (ST)
221       ST->removeValueName(Name);
222     Name->Destroy();
223     Name = 0;
224   } 
225   
226   // Now we know that this has no name.
227   
228   // If V has no name either, we're done.
229   if (!V->hasName()) return;
230    
231   // Get this's symtab if we didn't before.
232   if (!ST) {
233     if (getSymTab(this, ST)) {
234       // Clear V's name.
235       V->setName(0, 0);
236       return;  // Cannot set a name on this value (e.g. constant).
237     }
238   }
239   
240   // Get V's ST, this should always succed, because V has a name.
241   ValueSymbolTable *VST;
242   bool Failure = getSymTab(V, VST);
243   assert(!Failure && "V has a name, so it should have a ST!");
244   
245   // If these values are both in the same symtab, we can do this very fast.
246   // This works even if both values have no symtab yet.
247   if (ST == VST) {
248     // Take the name!
249     Name = V->Name;
250     V->Name = 0;
251     Name->setValue(this);
252     return;
253   }
254   
255   // Otherwise, things are slightly more complex.  Remove V's name from VST and
256   // then reinsert it into ST.
257   
258   if (VST)
259     VST->removeValueName(V->Name);
260   Name = V->Name;
261   V->Name = 0;
262   Name->setValue(this);
263   
264   if (ST)
265     ST->reinsertValue(this);
266 }
267
268
269 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
270 // except that it doesn't have all of the asserts.  The asserts fail because we
271 // are half-way done resolving types, which causes some types to exist as two
272 // different Type*'s at the same time.  This is a sledgehammer to work around
273 // this problem.
274 //
275 void Value::uncheckedReplaceAllUsesWith(Value *New) {
276   while (!use_empty()) {
277     Use &U = *UseList;
278     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
279     // constant because they are uniqued.
280     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
281       if (!isa<GlobalValue>(C)) {
282         C->replaceUsesOfWithOnConstant(this, New, &U);
283         continue;
284       }
285     }
286     
287     U.set(New);
288   }
289 }
290
291 void Value::replaceAllUsesWith(Value *New) {
292   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
293   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
294   assert(New->getType() == getType() &&
295          "replaceAllUses of value with new value of different type!");
296
297   uncheckedReplaceAllUsesWith(New);
298 }
299
300 //===----------------------------------------------------------------------===//
301 //                                 User Class
302 //===----------------------------------------------------------------------===//
303
304 // replaceUsesOfWith - Replaces all references to the "From" definition with
305 // references to the "To" definition.
306 //
307 void User::replaceUsesOfWith(Value *From, Value *To) {
308   if (From == To) return;   // Duh what?
309
310   assert(!isa<Constant>(this) || isa<GlobalValue>(this) &&
311          "Cannot call User::replaceUsesofWith on a constant!");
312
313   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
314     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
315       // The side effects of this setOperand call include linking to
316       // "To", adding "this" to the uses list of To, and
317       // most importantly, removing "this" from the use list of "From".
318       setOperand(i, To); // Fix it now...
319     }
320 }
321