llvm-gcc issue fixed, revert reversal :)
[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   // There should be no uses of this object anymore, remove it.
60   LeakDetector::removeGarbageObject(this);
61 }
62
63 /// hasNUses - Return true if this Value has exactly N users.
64 ///
65 bool Value::hasNUses(unsigned N) const {
66   use_const_iterator UI = use_begin(), E = use_end();
67
68   for (; N; --N, ++UI)
69     if (UI == E) return false;  // Too few.
70   return UI == E;
71 }
72
73 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
74 /// logically equivalent to getNumUses() >= N.
75 ///
76 bool Value::hasNUsesOrMore(unsigned N) const {
77   use_const_iterator UI = use_begin(), E = use_end();
78
79   for (; N; --N, ++UI)
80     if (UI == E) return false;  // Too few.
81
82   return true;
83 }
84
85
86 /// getNumUses - This method computes the number of uses of this Value.  This
87 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
88 /// values.
89 unsigned Value::getNumUses() const {
90   return (unsigned)std::distance(use_begin(), use_end());
91 }
92
93 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
94   ST = 0;
95   if (Instruction *I = dyn_cast<Instruction>(V)) {
96     if (BasicBlock *P = I->getParent())
97       if (Function *PP = P->getParent())
98         ST = &PP->getValueSymbolTable();
99   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
100     if (Function *P = BB->getParent()) 
101       ST = &P->getValueSymbolTable();
102   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
103     if (Module *P = GV->getParent()) 
104       ST = &P->getValueSymbolTable();
105   } else if (Argument *A = dyn_cast<Argument>(V)) {
106     if (Function *P = A->getParent()) 
107       ST = &P->getValueSymbolTable();
108   } else {
109     assert(isa<Constant>(V) && "Unknown value type!");
110     return true;  // no name is setable for this.
111   }
112   return false;
113 }
114
115 std::string Value::getNameStr() const {
116   if (Name == 0) return "";
117   return std::string(Name->getKeyData(),
118                      Name->getKeyData()+Name->getKeyLength());
119 }
120
121 void Value::setName(const std::string &name) {
122   setName(&name[0], name.size());
123 }
124
125 void Value::setName(const char *Name) {
126   setName(Name, Name ? strlen(Name) : 0);
127 }
128
129 void Value::setName(const char *NameStr, unsigned NameLen) {
130   if (NameLen == 0 && !hasName()) return;
131   if (getType() != Type::VoidTy && "Cannot assign a name to void values!");
132   
133   // Get the symbol table to update for this object.
134   ValueSymbolTable *ST;
135   if (getSymTab(this, ST))
136     return;  // Cannot set a name on this value (e.g. constant).
137
138   if (!ST) { // No symbol table to update?  Just do the change.
139     if (NameLen == 0) {
140       // Free the name for this value.
141       Name->Destroy();
142       Name = 0;
143       return;
144     }
145     
146     if (Name) {
147       // Name isn't changing?
148       if (NameLen == Name->getKeyLength() &&
149           !memcmp(Name->getKeyData(), NameStr, NameLen))
150         return;
151       Name->Destroy();
152     }
153     
154     // NOTE: Could optimize for the case the name is shrinking to not deallocate
155     // then reallocated.
156       
157     // Create the new name.
158     Name = ValueName::Create(NameStr, NameStr+NameLen);
159     Name->setValue(this);
160     return;
161   }
162   
163   // NOTE: Could optimize for the case the name is shrinking to not deallocate
164   // then reallocated.
165   if (hasName()) {
166     // Name isn't changing?
167     if (NameLen == Name->getKeyLength() &&
168         !memcmp(Name->getKeyData(), NameStr, NameLen))
169       return;
170
171     // Remove old name.
172     ST->removeValueName(Name);
173     Name->Destroy();
174     Name = 0;
175
176     if (NameLen == 0)
177       return;
178   }
179
180   // Name is changing to something new.
181   Name = ST->createValueName(NameStr, NameLen, this);
182 }
183
184
185 /// takeName - transfer the name from V to this value, setting V's name to
186 /// empty.  It is an error to call V->takeName(V). 
187 void Value::takeName(Value *V) {
188   ValueSymbolTable *ST = 0;
189   // If this value has a name, drop it.
190   if (hasName()) {
191     // Get the symtab this is in.
192     if (getSymTab(this, ST)) {
193       // We can't set a name on this value, but we need to clear V's name if
194       // it has one.
195       if (V->hasName()) V->setName(0, 0);
196       return;  // Cannot set a name on this value (e.g. constant).
197     }
198     
199     // Remove old name.
200     if (ST)
201       ST->removeValueName(Name);
202     Name->Destroy();
203     Name = 0;
204   } 
205   
206   // Now we know that this has no name.
207   
208   // If V has no name either, we're done.
209   if (!V->hasName()) return;
210    
211   // Get this's symtab if we didn't before.
212   if (!ST) {
213     if (getSymTab(this, ST)) {
214       // Clear V's name.
215       V->setName(0, 0);
216       return;  // Cannot set a name on this value (e.g. constant).
217     }
218   }
219   
220   // Get V's ST, this should always succed, because V has a name.
221   ValueSymbolTable *VST;
222   bool Failure = getSymTab(V, VST);
223   assert(!Failure && "V has a name, so it should have a ST!");
224   
225   // If these values are both in the same symtab, we can do this very fast.
226   // This works even if both values have no symtab yet.
227   if (ST == VST) {
228     // Take the name!
229     Name = V->Name;
230     V->Name = 0;
231     Name->setValue(this);
232     return;
233   }
234   
235   // Otherwise, things are slightly more complex.  Remove V's name from VST and
236   // then reinsert it into ST.
237   
238   if (VST)
239     VST->removeValueName(V->Name);
240   Name = V->Name;
241   V->Name = 0;
242   Name->setValue(this);
243   
244   if (ST)
245     ST->reinsertValue(this);
246 }
247
248
249 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
250 // except that it doesn't have all of the asserts.  The asserts fail because we
251 // are half-way done resolving types, which causes some types to exist as two
252 // different Type*'s at the same time.  This is a sledgehammer to work around
253 // this problem.
254 //
255 void Value::uncheckedReplaceAllUsesWith(Value *New) {
256   while (!use_empty()) {
257     Use &U = *UseList;
258     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
259     // constant!
260     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
261       if (!isa<GlobalValue>(C))
262         C->replaceUsesOfWithOnConstant(this, New, &U);
263       else
264         U.set(New);
265     } else {
266       U.set(New);
267     }
268   }
269 }
270
271 void Value::replaceAllUsesWith(Value *New) {
272   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
273   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
274   assert(New->getType() == getType() &&
275          "replaceAllUses of value with new value of different type!");
276
277   uncheckedReplaceAllUsesWith(New);
278 }
279
280 //===----------------------------------------------------------------------===//
281 //                                 User Class
282 //===----------------------------------------------------------------------===//
283
284 // replaceUsesOfWith - Replaces all references to the "From" definition with
285 // references to the "To" definition.
286 //
287 void User::replaceUsesOfWith(Value *From, Value *To) {
288   if (From == To) return;   // Duh what?
289
290   assert(!isa<Constant>(this) || isa<GlobalValue>(this) &&
291          "Cannot call User::replaceUsesofWith on a constant!");
292
293   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
294     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
295       // The side effects of this setOperand call include linking to
296       // "To", adding "this" to the uses list of To, and
297       // most importantly, removing "this" from the use list of "From".
298       setOperand(i, To); // Fix it now...
299     }
300 }
301